今天还是继续我们的JAVA的GUI,前几天讲了AWT,这个太重了。Swing开发图形界面比AWT更加优秀,切实轻量级的,100%的JAVA实现,唯一的缺点就是比AWT略慢。
先讲下Swing和AWT组件的相似处,以下图显示相同的组件
Swing多出来的组件
组件比较多,那些和AWT相同的组件用起来差不多,我就不多讲了,就贴段全面的代码让大家把玩下,eg
- public class SwingComponent
- {
- JFrame f = new JFrame("测试");
- //定义一个按钮,并为之指定图标
- Icon okIcon = new ImageIcon("ico/ok.png");
- JButton ok = new JButton("确认" , okIcon);
- //定义一个单选按钮,初始处于选中状态
- JRadioButton male = new JRadioButton("男" , true);
- //定义一个单按钮,初始处于没有选中状态
- JRadioButton female = new JRadioButton("女" , false);
- //定义一个ButtonGroup,用于将上面两个JRadioButton组合在一起
- ButtonGroup bg = new ButtonGroup();
- //定义一个复选框,初始处于没有选中状态。
- JCheckBox married = new JCheckBox("是否已婚?" , false);
- String[] colors = new String[]{"红色" , "绿色" , "蓝色"};
- //定义一个下拉选择框
- JComboBox colorChooser = new JComboBox(colors);
- //定义一个列表选择框
- JList colorList = new JList(colors);
- //定义一个8行、20列的多行文本域
- JTextArea ta = new JTextArea(8, 20);
- //定义一个40列的单行文本域
- JTextField name = new JTextField(40);
- JMenuBar mb = new JMenuBar();
- JMenu file = new JMenu("文件");
- JMenu edit = new JMenu("编辑");
- //创建“新建”菜单项,并为之指定图标
- Icon newIcon = new ImageIcon("ico/new.png");
- JMenuItem newItem = new JMenuItem("新建" , newIcon);
- //创建“保存”菜单项,并为之指定图标
- Icon saveIcon = new ImageIcon("ico/save.png");
- JMenuItem saveItem = new JMenuItem("保存" , saveIcon);
- //创建“退出”菜单项,并为之指定图标
- Icon exitIcon = new ImageIcon("ico/exit.png");
- JMenuItem exitItem = new JMenuItem("退出" , exitIcon);
- JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自动换行");
- //创建“复制”菜单项,并为之指定图标
- JMenuItem copyItem = new JMenuItem("复制" , new ImageIcon("ico/copy.png"));
- //创建“粘贴”菜单项,并为之指定图标
- JMenuItem pasteItem = new JMenuItem("粘贴" , new ImageIcon("ico/paste.png"));
- JMenu format = new JMenu("格式");
- JMenuItem commentItem = new JMenuItem("注释");
- JMenuItem cancelItem = new JMenuItem("取消注释");
- //定义一个右键菜单用于设置程序风格
- JPopupMenu pop = new JPopupMenu();
- //用于组合三个风格菜单项的ButtonGroup
- ButtonGroup flavorGroup = new ButtonGroup();
- //创建三个单选框按钮,用于设定程序的外观风格
- JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal风格" , true);
- JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows风格");
- JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif风格");
- public void init()
- {
- //创建一个装载了文本框、按钮的JPanel
- JPanel bottom = new JPanel();
- bottom.add(name);
- bottom.add(ok);
- f.add(bottom , BorderLayout.SOUTH);
- //创建一个装载了下拉选择框、三个JCheckBox的JPanel
- JPanel checkPanel = new JPanel();
- checkPanel.add(colorChooser);
- bg.add(male);
- bg.add(female);
- checkPanel.add(male);
- checkPanel.add(female);
- checkPanel.add(married);
- //创建一个垂直排列组件的Box,盛装多行文本域JPanel
- Box topLeft = Box.createVerticalBox();
- //使用JScrollPane作为普通组件的JViewPort
- JScrollPane taJsp = new JScrollPane(ta);
- topLeft.add(taJsp);
- topLeft.add(checkPanel);
- //创建一个垂直排列组件的Box,盛装topLeft、colorList
- Box top = Box.createHorizontalBox();
- top.add(topLeft);
- top.add(colorList);
- //将top Box容器添加到窗口的中间
- f.add(top);
- //-----------下面开始组合菜单、并为菜单添加事件监听器----------
- //为newItem设置快捷键,设置快捷键时要使用大写字母
- newItem.setAccelerator(KeyStroke.getKeyStroke('N' , InputEvent.CTRL_MASK));
- newItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ta.append("用户单击了“新建”菜单/n");
- }
- });
- //为file菜单添加菜单项
- file.add(newItem);
- file.add(saveItem);
- file.add(exitItem);
- //为edit菜单添加菜单项
- edit.add(autoWrap);
- //使用addSeparator方法来添加菜单分隔线
- edit.addSeparator();
- edit.add(copyItem);
- edit.add(pasteItem);
- commentItem.setToolTipText("将程序代码注释起来!");
- //为format菜单添加菜单项
- format.add(commentItem);
- format.add(cancelItem);
- //使用添加new JMenuItem("-")的方式不能添加菜单分隔符
- edit.add(new JMenuItem("-"));
- //将format菜单组合到edit菜单中,从而形成二级菜单
- edit.add(format);
- //将file、edit菜单添加到mb菜单条中
- mb.add(file);
- mb.add(edit);
- //为f窗口设置菜单条
- f.setJMenuBar(mb);
- //-----------下面开始组合右键菜单、并安装右键菜单----------
- flavorGroup.add(metalItem);
- flavorGroup.add(windowsItem);
- flavorGroup.add(motifItem);
- pop.add(metalItem);
- pop.add(windowsItem);
- pop.add(motifItem);
- //为三个菜单创建事件监听器
- ActionListener flavorListener = new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- try
- {
- if (e.getActionCommand().equals("Metal风格"))
- {
- changeFlavor(1);
- }
- else if (e.getActionCommand().equals("Windows风格"))
- {
- changeFlavor(2);
- }
- else if (e.getActionCommand().equals("Motif风格"))
- {
- changeFlavor(3);
- }
- }
- catch (Exception ee)
- {
- ee.printStackTrace();
- }
- }
- };
- //为三个菜单添加事件监听器
- metalItem.addActionListener(flavorListener);
- windowsItem.addActionListener(flavorListener);
- motifItem.addActionListener(flavorListener);
- //调用该方法即可设置右键菜单,无需使用事件机制
- ta.setComponentPopupMenu(pop);
- //设置关闭窗口时,退出程序
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.pack();
- f.setVisible(true);
- }
- //定义一个方法,用于改变界面风格
- private void changeFlavor(int flavor)throws Exception
- {
- switch (flavor)
- {
- //设置Metal风格
- case 1:
- UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
- break;
- //设置Windows风格
- case 2:
- UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
- break;
- //设置Motif风格
- case 3:
- UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
- break;
- }
- //更新f窗口内顶级容器以及内部所有组件的UI
- SwingUtilities.updateComponentTreeUI(f.getContentPane());
- //更新mb菜单条以及内部所有组件的UI
- SwingUtilities.updateComponentTreeUI(mb);
- //更新pop右键菜单以及内部所有组件的UI
- SwingUtilities.updateComponentTreeUI(pop);
- }
- public static void main(String[] args)
- {
- //设置Swing窗口使用Java风格
- JFrame.setDefaultLookAndFeelDecorated(true);
- new SwingComponent().init();
- }
- }
下面Swing的特殊组件,我将以举例的形式,这样最能主观理解,大家一定要动手试试
首先是JToolBar
- public class TestJToolBar
- {
- JFrame jf = new JFrame("测试工具条");
- JTextArea jta = new JTextArea(6, 35);
- JToolBar jtb = new JToolBar();
- JMenuBar jmb = new JMenuBar();
- JMenu edit = new JMenu("编辑");
- Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
- //创建"粘贴"Action,该Action用于创建菜单项、工具按钮和普通按钮
- Action pasteAction = new AbstractAction("粘贴", new ImageIcon("ico/paste.png"))
- {
- public void actionPerformed(ActionEvent e)
- {
- //如果剪贴板中包含stringFlavor内容
- if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
- {
- try
- {
- //取出剪贴板中stringFlavor内容
- String content = (String)clipboard.getData(DataFlavor.stringFlavor);
- //将选中内容替换成剪贴板中的内容
- jta.replaceRange(content , jta.getSelectionStart() , jta.getSelectionEnd());
- }
- catch (Exception ee)
- {
- ee.printStackTrace();
- }
- }
- }
- };
- //创建"复制"Action
- Action copyAction = new AbstractAction("复制", new ImageIcon("ico/copy.png"))
- {
- public void actionPerformed(ActionEvent e)
- {
- StringSelection contents = new StringSelection(jta.getSelectedText());
- //将StringSelection对象放入剪贴板
- clipboard.setContents(contents, null);
- //如果剪贴板中包含stringFlavor内容
- if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
- {
- //将pasteAction激活
- pasteAction.setEnabled(true);
- }
- }
- };
- public void init()
- {
- //pasteAction默认处于不激活状态
- pasteAction.setEnabled(false);
- jf.add(new JScrollPane(jta));
- //以Action创建按钮,并将该按钮添加到Panel中
- JButton copyBn = new JButton(copyAction);
- JButton pasteBn = new JButton(pasteAction);
- JPanel jp = new JPanel();
- jp.add(copyBn);
- jp.add(pasteBn);
- jf.add(jp , BorderLayout.SOUTH);
- //向工具条中添加Action对象,该对象将会转换成工具按钮
- jtb.add(copyAction);
- jtb.addSeparator();
- jtb.add(pasteAction);
- //向菜单中添加Action对象,该对象将会转换成菜单项
- edit.add(copyAction);
- edit.add(pasteAction);
- //将edit菜单添加到菜单条中
- jmb.add(edit);
- jf.setJMenuBar(jmb);
- //设置工具条和工具按钮之间的距离
- jtb.setMargin(new Insets(20 ,10 , 5 , 30));
- //向窗口中添加工具条
- jf.add(jtb , BorderLayout.NORTH);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- jf.pack();
- jf.setVisible(true);
- }
- public static void main(String[] args)
- {
- new TestJToolBar().init();
- }
- }
继续讲Swing的特殊组件,JColorChooser和JFileChooser这两个东西在awt中都是利用系统的控件,这样导致不同操作系统有不同的界面,用Swing就避免了这些问题。下面就先看JColorChooser的例子,eg(一个简单画图程序)
- public class HandDraw
- {
- //画图区的宽度
- private final int AREA_WIDTH = 500;
- //画图区的高度
- private final int AREA_HEIGHT = 400;
- //下面的preX、preY保存了上一次鼠标拖动事件的鼠标座标
- private int preX = -1;
- private int preY = -1;
- //定义一个右键菜单用于设置画笔颜色
- JPopupMenu pop = new JPopupMenu();
- JMenuItem chooseColor = new JMenuItem("选择颜色");
- //定义一个BufferedImage对象
- BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT ,
- BufferedImage.TYPE_INT_RGB);
- //获取image对象的Graphics
- Graphics g = image.getGraphics();
- private JFrame f = new JFrame("简单手绘程序");
- private DrawCanvas drawArea = new DrawCanvas();
- //用于保存需要绘制什么图形的字符串属性
- private String shape = "";
- //用于保存画笔颜色
- private Color foreColor = new Color(255, 0 ,0);
- public void init()
- {
- chooseColor.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- {
- //下面代码直接弹出一个模式的颜色选择器对话框,并返回用户选择的颜色
- //foreColor = JColorChooser.showDialog(f , "选择画笔颜色" , foreColor);
- //下面代码则可以弹出一个非模式的颜色选择对话框,
- //并可以分别为“确定”按钮、“取消”按钮指定事件监听器
- final JColorChooser colorPane = new JColorChooser(foreColor);
- JDialog jd = JColorChooser.createDialog(f ,"选择画笔颜色",false,
- colorPane, new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- {
- foreColor = colorPane.getColor();
- }
- }, null);
- jd.setVisible(true);
- }
- });
- //将菜单项组合成右键菜单
- pop.add(chooseColor);
- //将右键菜单添加到drawArea对象中
- drawArea.setComponentPopupMenu(pop);
- //将image对象的背景色填充成白色
- g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);
- drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT));
- //监听鼠标移动动作
- drawArea.addMouseMotionListener(new MouseMotionAdapter()
- {
- //实现按下鼠标键并拖动的事件处理器
- public void mouseDragged(MouseEvent e)
- {
- //如果preX和preY大于0
- if (preX > 0 && preY > 0)
- {
- //设置当前颜色
- g.setColor(foreColor);
- //绘制从上一次鼠标拖动事件点到本次鼠标拖动事件点的线段
- g.drawLine(preX , preY , e.getX() , e.getY());
- }
- //将当前鼠标事件点的X、Y座标保存起来
- preX = e.getX();
- preY = e.getY();
- //重绘drawArea对象
- drawArea.repaint();
- }
- });
- //监听鼠标事件
- drawArea.addMouseListener(new MouseAdapter()
- {
- //实现鼠标松开的事件处理器
- public void mouseReleased(MouseEvent e)
- {
- //松开鼠标键时,把上一次鼠标拖动事件的X、Y座标设为-1。
- preX = -1;
- preY = -1;
- }
- });
- f.add(drawArea);
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.pack();
- f.setVisible(true);
- }
- public static void main(String[] args)
- {
- new HandDraw().init();
- }
- //让画图区域继承JPanel类
- class DrawCanvas extends JPanel
- {
- //重写JPanel的paint方法,实现绘画
- public void paint(Graphics g)
- {
- //将image绘制到该组件上
- g.drawImage(image , 0 , 0 , null);
- }
- }
- }
下面举个JFileChooser,这些东西组件不是很常用,大家可以收藏着,到用的时候翻出来看,eg
- public class ImageViewer
- {
- final int PREVIEW_SIZE = 100;
- JFrame jf = new JFrame("简单图片查看器");
- JMenuBar menuBar = new JMenuBar();
- //该label用于显示图片
- JLabel label = new JLabel();
- //以当前路径创建文件选择器
- JFileChooser chooser = new JFileChooser(".");
- JLabel accessory = new JLabel();
- ExtensionFileFilter filter = new ExtensionFileFilter();
- public void init()
- {
- //-------------------下面开始初始化JFileChooser的相关属性-----------------
- // 创建一个FileFilter
- filter.addExtension("jpg");
- filter.addExtension("jpeg");
- filter.addExtension("gif");
- filter.addExtension("png");
- filter.setDescription("图片文件(*.jpg,*.jpeg,*.gif,*.png)");
- chooser.addChoosableFileFilter(filter);
- //禁止“文件类型”下拉列表中显示“所有文件”选项。
- chooser.setAcceptAllFileFilterUsed(false);
- //为文件选择器指定自定义的FileView对象
- chooser.setFileView(new FileIconView(filter));
- //为文件选择器指定一个预览图片的附件组件
- chooser.setAccessory(accessory);
- //设置预览图片组件的大小和边框
- accessory.setPreferredSize(new Dimension(PREVIEW_SIZE, PREVIEW_SIZE));
- accessory.setBorder(BorderFactory.createEtchedBorder());
- //用于检测被选择文件的改变事件
- chooser.addPropertyChangeListener(new PropertyChangeListener()
- {
- public void propertyChange(PropertyChangeEvent event)
- {
- //JFileChooser的被选文件已经发生了改变
- if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
- {
- //获取用户选择的新文件
- File f = (File) event.getNewValue();
- if (f == null)
- {
- accessory.setIcon(null);
- return;
- }
- //将所文件读入ImageIcon对象中
- ImageIcon icon = new ImageIcon(f.getPath());
- //如果图像太大,则缩小它
- if(icon.getIconWidth() > PREVIEW_SIZE)
- {
- icon = new ImageIcon(icon.getImage()
- .getScaledInstance(PREVIEW_SIZE, -1, Image.SCALE_DEFAULT));
- }
- //改变accessory Label的图标
- accessory.setIcon(icon);
- }
- }
- });
- //----------下面代码开始为该窗口安装菜单------------
- JMenu menu = new JMenu("文件");
- menuBar.add(menu);
- JMenuItem openItem = new JMenuItem("打开");
- menu.add(openItem);
- //单击openItem菜单项显示“打开文件”的对话框
- openItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- //设置文件对话框的当前路径
- //chooser.setCurrentDirectory(new File("."));
- //显示文件对话框
- int result = chooser.showDialog(jf , "打开图片文件");
- //如果用户选择了APPROVE(赞同)按钮,即打开,保存及其等效按钮
- if(result == JFileChooser.APPROVE_OPTION)
- {
- String name = chooser.getSelectedFile().getPath();
- //显示指定图片
- label.setIcon(new ImageIcon(name));
- }
- }
- });
- JMenuItem exitItem = new JMenuItem("退出");
- menu.add(exitItem);
- exitItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- System.exit(0);
- }
- });
- jf.setJMenuBar(menuBar);
- //添加用于显示图片的JLabel组件。
- jf.add(new JScrollPane(label));
- jf.setSize(500, 400);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- jf.setVisible(true);
- }
- public static void main(String[] args)
- {
- new ImageViewer().init();
- }
- }
- //创建FileFilter的子类,用以实现文件过滤功能
- class ExtensionFileFilter extends FileFilter
- {
- private String description = "";
- private ArrayList<String> extensions = new ArrayList<String>();
- //自定义方法,用于添加文件扩展名
- public void addExtension(String extension)
- {
- if (!extension.startsWith("."))
- {
- extension = "." + extension;
- extensions.add(extension.toLowerCase());
- }
- }
- //用于设置该文件过滤器的描述文本
- public void setDescription(String aDescription)
- {
- description = aDescription;
- }
- //继承FileFilter类必须实现的抽象方法,返回该文件过滤器的描述文本
- public String getDescription()
- {
- return description;
- }
- //继承FileFilter类必须实现的抽象方法,判断该文件过滤器是否接受该文件
- public boolean accept(File f)
- {
- //如果该文件是路径,接受该文件
- if (f.isDirectory()) return true;
- //将文件名转为小写(全部转为小写后比较,用于忽略文件名大小写)
- String name = f.getName().toLowerCase();
- //遍历所有可接受的扩展名,如果扩展名相同,该文件就可接受。
- for (String extension : extensions)
- {
- if (name.endsWith(extension))
- {
- return true;
- }
- }
- return false;
- }
- }
- //自定义一个FileView类,用于为指定类型的指定图标
- class FileIconView extends FileView
- {
- private FileFilter filter;
- public FileIconView(FileFilter filter)
- {
- this.filter = filter;
- }
- //如果文件不是目录,并且不是
- public Icon getIcon(File f)
- {
- if (!f.isDirectory() && filter.accept(f))
- {
- return new ImageIcon("ico/pict.png");
- }
- else if (f.isDirectory())
- {
- //获取所有根路径
- File[] fList = File.listRoots();
- for (File tmp : fList)
- {
- //如果该路径是根路径
- if (tmp.equals(f))
- {
- return new ImageIcon("ico/dsk.png");
- }
- }
- return new ImageIcon("ico/folder.png");
- }
- //使用默认图标
- else
- {
- return null;
- }
- }
- }
注意:以上图片我都没给,自己随便弄几张看看效果
JOptionPane是一种特殊的JFrame,他的出现是为了方便我们创建一些简单的对话框,你也可以用JFrame搞一个,但很繁琐,但如果你用UI的拖拽工具那就没什么了。eg(各种对话框)
- public class TestJOptionPane
- {
- JFrame jf = new JFrame("测试JOptionPane");
- //分别定义6个面板用于定义对话框的几种选项
- private ButtonPanel messagePanel;
- private ButtonPanel messageTypePanel;
- private ButtonPanel msgPanel;
- private ButtonPanel confirmPanel;
- private ButtonPanel optionsPanel;
- private ButtonPanel inputPanel;
- private String messageString = "消息区内容";
- private Icon messageIcon = new ImageIcon("ico/heart.png");
- private Object messageObject = new Date();
- private Component messageComponent = new JButton("组件消息");
- private JButton msgBn = new JButton("消息对话框");
- private JButton confrimBn = new JButton("确认对话框");
- private JButton inputBn = new JButton("输入对话框");
- private JButton optionBn = new JButton("选项对话框");
- public void init()
- {
- JPanel top = new JPanel();
- top.setBorder(new TitledBorder(new EtchedBorder(), "对话框的通用选项" ,
- TitledBorder.CENTER ,TitledBorder.TOP ));
- top.setLayout(new GridLayout(1 , 2));
- //消息类型Panel,该Panel中的选项决定对话框的图标
- messageTypePanel = new ButtonPanel("选择消息的类型",
- new String[]{"ERROR_MESSAGE", "INFORMATION_MESSAGE", "WARNING_MESSAGE",
- "QUESTION_MESSAGE", "PLAIN_MESSAGE" });
- //消息内容类型的Panel,该Panel中的选项决定对话框的消息区的内容
- messagePanel = new ButtonPanel("选择消息内容的类型",
- new String[]{"字符串消息", "图标消息", "组件消息", "普通对象消息" , "Object[]消息"});
- top.add(messageTypePanel);
- top.add(messagePanel);
- JPanel bottom = new JPanel();
- bottom.setBorder(new TitledBorder(new EtchedBorder(), "弹出不同的对话框" ,
- TitledBorder.CENTER ,TitledBorder.TOP));
- bottom.setLayout(new GridLayout(1 , 4));
- //创建用于弹出消息对话框的Panel
- msgPanel = new ButtonPanel("消息对话框", null);
- msgBn.addActionListener(new ShowAction());
- msgPanel.add(msgBn);
- //创建用于弹出确认对话框的Panel
- confirmPanel = new ButtonPanel("确认对话框",
- new String[]{"DEFAULT_OPTION", "YES_NO_OPTION", "YES_NO_CANCEL_OPTION",
- "OK_CANCEL_OPTION"});
- confrimBn.addActionListener(new ShowAction());
- confirmPanel.add(confrimBn);
- //创建用于弹出输入对话框的Panel
- inputPanel = new ButtonPanel("输入对话框",
- new String[]{"单行文本框","下拉列表选择框"});
- inputBn.addActionListener(new ShowAction());
- inputPanel.add(inputBn);
- //创建用于弹出选项对话框的Panel
- optionsPanel = new ButtonPanel("选项对话框",
- new String[]{"字符串选项", "图标选项", "对象选项"});
- optionBn.addActionListener(new ShowAction());
- optionsPanel.add(optionBn);
- bottom.add(msgPanel);
- bottom.add(confirmPanel);
- bottom.add(inputPanel);
- bottom.add(optionsPanel);
- Box box = new Box(BoxLayout.Y_AXIS);
- box.add(top);
- box.add(bottom);
- jf.add(box);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- jf.pack();
- jf.setVisible(true);
- }
- //根据用户选择返回选项类型
- private int getOptionType()
- {
- if (confirmPanel.getSelection().equals("DEFAULT_OPTION"))
- return JOptionPane.DEFAULT_OPTION;
- else if (confirmPanel.getSelection().equals("YES_NO_OPTION"))
- return JOptionPane.YES_NO_OPTION;
- else if (confirmPanel.getSelection().equals("YES_NO_CANCEL_OPTION"))
- return JOptionPane.YES_NO_CANCEL_OPTION;
- else
- return JOptionPane.OK_CANCEL_OPTION;
- }
- //根据用户选择返回消息
- private Object getMessage()
- {
- if (messagePanel.getSelection().equals("字符串消息"))
- return messageString;
- else if (messagePanel.getSelection().equals("图标消息"))
- return messageIcon;
- else if (messagePanel.getSelection().equals("组件消息"))
- return messageComponent;
- else if(messagePanel.getSelection().equals("普通对象消息"))
- return messageObject;
- else
- return new Object[]{messageString , messageIcon ,
- messageObject , messageComponent};
- }
- //根据用户选择返回消息类型(决定图标区的图标)
- private int getDialogType()
- {
- if (messageTypePanel.getSelection().equals("ERROR_MESSAGE"))
- return JOptionPane.ERROR_MESSAGE;
- else if (messageTypePanel.getSelection().equals("INFORMATION_MESSAGE"))
- return JOptionPane.INFORMATION_MESSAGE;
- else if (messageTypePanel.getSelection().equals("WARNING_MESSAGE"))
- return JOptionPane.WARNING_MESSAGE;
- else if(messageTypePanel.getSelection().equals("QUESTION_MESSAGE"))
- return JOptionPane.QUESTION_MESSAGE;
- else
- return JOptionPane.PLAIN_MESSAGE;
- }
- private Object[] getOptions()
- {
- if (optionsPanel.getSelection().equals("字符串选项"))
- return new String[]{"a" , "b" , "c" , "d"};
- else if (optionsPanel.getSelection().equals("图标选项"))
- return new Icon[]{new ImageIcon("ico/1.gif") , new ImageIcon("ico/2.gif"),
- new ImageIcon("ico/3.gif"),new ImageIcon("ico/4.gif")};
- else
- return new Object[]{new Date() ,new Date() , new Date()};
- }
- //为各按钮定义事件监听器
- private class ShowAction implements ActionListener
- {
- public void actionPerformed(ActionEvent event)
- {
- if (event.getActionCommand().equals("确认对话框"))
- {
- JOptionPane.showConfirmDialog(jf , getMessage(),"确认对话框",
- getOptionType(), getDialogType());
- }
- else if (event.getActionCommand().equals("输入对话框"))
- {
- if (inputPanel.getSelection().equals("单行文本框"))
- {
- JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType());
- }
- else
- {
- JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType(),
- null, new String[] {"轻量级J2EE企业应用实战", "Struts2权威指南"},
- "Struts2权威指南");
- }
- }
- else if (event.getActionCommand().equals("消息对话框"))
- {
- JOptionPane.showMessageDialog(jf,getMessage(),"消息对话框",getDialogType());
- }
- else if (event.getActionCommand().equals("选项对话框"))
- {
- JOptionPane.showOptionDialog(jf , getMessage() , "选项对话框", getOptionType(),
- getDialogType(), null, getOptions(), "a");
- }
- }
- }
- public static void main(String[] args)
- {
- new TestJOptionPane().init();
- }
- }
- //定义一个JPanel类扩展类,该类的对象包含多个纵向排列的JRadioButton控件
- //且Panel扩展类可以指定一个字符串作为TitledBorder
- class ButtonPanel extends JPanel
- {
- private ButtonGroup group;
- public ButtonPanel(String title, String[] options)
- {
- setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
- setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
- group = new ButtonGroup();
- for (int i = 0; options!= null && i < options.length; i++)
- {
- JRadioButton b = new JRadioButton(options[i]);
- b.setActionCommand(options[i]);
- add(b);
- group.add(b);
- b.setSelected(i == 0);
- }
- }
- //定义一个方法,用于返回用户选择的选项
- public String getSelection()
- {
- return group.getSelection().getActionCommand();
- }
- }
看似简单,用起来花样还是挺多的。
原文链接:http://blog.csdn.net/terryzero/article/details/3763592
【编辑推荐】