Java Swing编程:基本组件

开发 后端
今天还是继续我们的JAVA的GUI,前几天讲了AWT,这个太重了。Swing开发图形界面比AWT更加优秀,切实轻量级的,100%的JAVA实现,唯一的缺点就是比AWT略慢。

今天还是继续我们的JAVA的GUI,前几天讲了AWT,这个太重了。Swing开发图形界面比AWT更加优秀,切实轻量级的,100%的JAVA实现,唯一的缺点就是比AWT略慢。

先讲下Swing和AWT组件的相似处,以下图显示相同的组件

Swing多出来的组件

组件比较多,那些和AWT相同的组件用起来差不多,我就不多讲了,就贴段全面的代码让大家把玩下,eg

  1. public class SwingComponent  
  2. {  
  3.     JFrame f = new JFrame("测试");  
  4.     //定义一个按钮,并为之指定图标  
  5.     Icon okIcon = new ImageIcon("ico/ok.png");  
  6.     JButton ok = new JButton("确认" , okIcon);  
  7.     //定义一个单选按钮,初始处于选中状态  
  8.     JRadioButton male = new JRadioButton("男" , true);  
  9.     //定义一个单按钮,初始处于没有选中状态  
  10.     JRadioButton female = new JRadioButton("女" , false);  
  11.     //定义一个ButtonGroup,用于将上面两个JRadioButton组合在一起  
  12.     ButtonGroup bg = new ButtonGroup();  
  13.     //定义一个复选框,初始处于没有选中状态。  
  14.     JCheckBox married = new JCheckBox("是否已婚?" , false);  
  15.     String[] colors = new String[]{"红色" , "绿色"  , "蓝色"};  
  16.     //定义一个下拉选择框  
  17.     JComboBox colorChooser = new JComboBox(colors);  
  18.     //定义一个列表选择框  
  19.     JList colorList = new JList(colors);  
  20.     //定义一个8行、20列的多行文本域  
  21.     JTextArea ta = new JTextArea(820);  
  22.     //定义一个40列的单行文本域  
  23.     JTextField name = new JTextField(40);  
  24.     JMenuBar mb = new JMenuBar();  
  25.     JMenu file = new JMenu("文件");  
  26.     JMenu edit = new JMenu("编辑");  
  27.     //创建“新建”菜单项,并为之指定图标  
  28.     Icon newIcon = new ImageIcon("ico/new.png");  
  29.     JMenuItem newItem = new JMenuItem("新建" , newIcon);  
  30.     //创建“保存”菜单项,并为之指定图标  
  31.     Icon saveIcon = new ImageIcon("ico/save.png");  
  32.     JMenuItem saveItem = new JMenuItem("保存" , saveIcon);  
  33.     //创建“退出”菜单项,并为之指定图标  
  34.     Icon exitIcon = new ImageIcon("ico/exit.png");  
  35.     JMenuItem exitItem = new JMenuItem("退出" , exitIcon);      
  36.     JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自动换行");  
  37.     //创建“复制”菜单项,并为之指定图标  
  38.     JMenuItem copyItem = new JMenuItem("复制" , new ImageIcon("ico/copy.png"));  
  39.     //创建“粘贴”菜单项,并为之指定图标  
  40.     JMenuItem pasteItem = new JMenuItem("粘贴" , new ImageIcon("ico/paste.png"));  
  41.     JMenu format = new JMenu("格式");  
  42.     JMenuItem commentItem = new JMenuItem("注释");  
  43.     JMenuItem cancelItem = new JMenuItem("取消注释");  
  44.       
  45.     //定义一个右键菜单用于设置程序风格  
  46.     JPopupMenu pop = new JPopupMenu();  
  47.     //用于组合三个风格菜单项的ButtonGroup  
  48.     ButtonGroup flavorGroup = new ButtonGroup();  
  49.     //创建三个单选框按钮,用于设定程序的外观风格  
  50.     JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal风格" , true);  
  51.     JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows风格");  
  52.     JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif风格");  
  53.  
  54.     public void init()  
  55.     {  
  56.         //创建一个装载了文本框、按钮的JPanel  
  57.         JPanel bottom = new JPanel();  
  58.         bottom.add(name);  
  59.         bottom.add(ok);  
  60.         f.add(bottom , BorderLayout.SOUTH);  
  61.         //创建一个装载了下拉选择框、三个JCheckBox的JPanel  
  62.         JPanel checkPanel = new JPanel();  
  63.         checkPanel.add(colorChooser);  
  64.         bg.add(male);  
  65.         bg.add(female);  
  66.         checkPanel.add(male);  
  67.         checkPanel.add(female);  
  68.         checkPanel.add(married);  
  69.         //创建一个垂直排列组件的Box,盛装多行文本域JPanel  
  70.         Box topLeft = Box.createVerticalBox();  
  71.         //使用JScrollPane作为普通组件的JViewPort  
  72.         JScrollPane taJsp = new JScrollPane(ta);  
  73.         topLeft.add(taJsp);  
  74.         topLeft.add(checkPanel);  
  75.         //创建一个垂直排列组件的Box,盛装topLeft、colorList  
  76.         Box top = Box.createHorizontalBox();  
  77.         top.add(topLeft);  
  78.         top.add(colorList);  
  79.         //将top Box容器添加到窗口的中间  
  80.         f.add(top);   
  81.         //-----------下面开始组合菜单、并为菜单添加事件监听器----------  
  82.         //为newItem设置快捷键,设置快捷键时要使用大写字母  
  83.         newItem.setAccelerator(KeyStroke.getKeyStroke('N' , InputEvent.CTRL_MASK));   
  84.         newItem.addActionListener(new ActionListener()  
  85.         {  
  86.             public void actionPerformed(ActionEvent e)  
  87.             {  
  88.                 ta.append("用户单击了“新建”菜单/n");  
  89.             }  
  90.         });  
  91.         //为file菜单添加菜单项  
  92.         file.add(newItem);  
  93.         file.add(saveItem);  
  94.         file.add(exitItem);  
  95.         //为edit菜单添加菜单项  
  96.         edit.add(autoWrap);  
  97.         //使用addSeparator方法来添加菜单分隔线  
  98.         edit.addSeparator();  
  99.         edit.add(copyItem);  
  100.         edit.add(pasteItem);  
  101.         commentItem.setToolTipText("将程序代码注释起来!");  
  102.         //为format菜单添加菜单项  
  103.         format.add(commentItem);  
  104.         format.add(cancelItem);  
  105.         //使用添加new JMenuItem("-")的方式不能添加菜单分隔符  
  106.         edit.add(new JMenuItem("-"));  
  107.         //将format菜单组合到edit菜单中,从而形成二级菜单  
  108.         edit.add(format);  
  109.         //将file、edit菜单添加到mb菜单条中  
  110.         mb.add(file);  
  111.         mb.add(edit);  
  112.         //为f窗口设置菜单条  
  113.         f.setJMenuBar(mb);  
  114.         //-----------下面开始组合右键菜单、并安装右键菜单----------  
  115.         flavorGroup.add(metalItem);  
  116.         flavorGroup.add(windowsItem);  
  117.         flavorGroup.add(motifItem);  
  118.         pop.add(metalItem);  
  119.         pop.add(windowsItem);  
  120.         pop.add(motifItem);  
  121.         //为三个菜单创建事件监听器  
  122.         ActionListener flavorListener = new ActionListener()  
  123.         {  
  124.             public void actionPerformed(ActionEvent e)  
  125.             {  
  126.                 try 
  127.                 {  
  128.                     if (e.getActionCommand().equals("Metal风格"))  
  129.                     {  
  130.                         changeFlavor(1);  
  131.                     }  
  132.                     else if (e.getActionCommand().equals("Windows风格"))  
  133.                     {  
  134.                         changeFlavor(2);  
  135.                     }  
  136.                     else if (e.getActionCommand().equals("Motif风格"))  
  137.                     {  
  138.                         changeFlavor(3);  
  139.                     }  
  140.                 }  
  141.                 catch (Exception ee)  
  142.                 {  
  143.                     ee.printStackTrace();  
  144.                 }  
  145.             }  
  146.         };  
  147.         //为三个菜单添加事件监听器  
  148.         metalItem.addActionListener(flavorListener);  
  149.         windowsItem.addActionListener(flavorListener);  
  150.         motifItem.addActionListener(flavorListener);  
  151.         //调用该方法即可设置右键菜单,无需使用事件机制  
  152.         ta.setComponentPopupMenu(pop);   
  153.         //设置关闭窗口时,退出程序  
  154.         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  155.         f.pack();  
  156.         f.setVisible(true);  
  157.     }  
  158.  
  159.     //定义一个方法,用于改变界面风格  
  160.     private void changeFlavor(int flavor)throws Exception  
  161.     {  
  162.         switch (flavor)  
  163.         {  
  164.             //设置Metal风格  
  165.             case 1:  
  166.                 UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");  
  167.                 break;  
  168.             //设置Windows风格  
  169.             case 2:  
  170.                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");  
  171.                 break;  
  172.             //设置Motif风格  
  173.             case 3:  
  174.                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");  
  175.                 break;            
  176.         }  
  177.         //更新f窗口内顶级容器以及内部所有组件的UI  
  178.         SwingUtilities.updateComponentTreeUI(f.getContentPane());  
  179.         //更新mb菜单条以及内部所有组件的UI  
  180.         SwingUtilities.updateComponentTreeUI(mb);  
  181.         //更新pop右键菜单以及内部所有组件的UI  
  182.         SwingUtilities.updateComponentTreeUI(pop);  
  183.  
  184.     }  
  185.     public static void main(String[] args)   
  186.     {  
  187.         //设置Swing窗口使用Java风格  
  188.         JFrame.setDefaultLookAndFeelDecorated(true);   
  189.         new SwingComponent().init();  
  190.     }  
  191. }  

下面Swing的特殊组件,我将以举例的形式,这样最能主观理解,大家一定要动手试试

首先是JToolBar

  1. public class TestJToolBar  
  2. {  
  3.     JFrame jf = new JFrame("测试工具条");  
  4.     JTextArea jta = new JTextArea(635);  
  5.     JToolBar jtb = new JToolBar();  
  6.     JMenuBar jmb = new JMenuBar();  
  7.     JMenu edit = new JMenu("编辑");  
  8.     Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  
  9.     //创建"粘贴"Action,该Action用于创建菜单项、工具按钮和普通按钮  
  10.     Action pasteAction = new AbstractAction("粘贴"new ImageIcon("ico/paste.png"))  
  11.     {  
  12.         public void actionPerformed(ActionEvent e)  
  13.         {  
  14.             //如果剪贴板中包含stringFlavor内容  
  15.             if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
  16.             {  
  17.                 try 
  18.                 {  
  19.                     //取出剪贴板中stringFlavor内容  
  20.                     String content = (String)clipboard.getData(DataFlavor.stringFlavor);  
  21.                     //将选中内容替换成剪贴板中的内容  
  22.                     jta.replaceRange(content , jta.getSelectionStart() , jta.getSelectionEnd());  
  23.                 }  
  24.                 catch (Exception ee)  
  25.                 {  
  26.                     ee.printStackTrace();  
  27.                 }  
  28.             }  
  29.         }  
  30.     };  
  31.     //创建"复制"Action  
  32.     Action copyAction = new AbstractAction("复制"new ImageIcon("ico/copy.png"))  
  33.     {  
  34.         public void actionPerformed(ActionEvent e)  
  35.         {  
  36.             StringSelection contents = new StringSelection(jta.getSelectedText());  
  37.             //将StringSelection对象放入剪贴板  
  38.             clipboard.setContents(contents, null);  
  39.             //如果剪贴板中包含stringFlavor内容  
  40.             if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
  41.             {  
  42.                 //将pasteAction激活  
  43.                 pasteAction.setEnabled(true);  
  44.             }  
  45.         }  
  46.     };  
  47.     public void init()  
  48.     {  
  49.         //pasteAction默认处于不激活状态  
  50.         pasteAction.setEnabled(false);  
  51.         jf.add(new JScrollPane(jta));  
  52.         //以Action创建按钮,并将该按钮添加到Panel中  
  53.         JButton copyBn = new JButton(copyAction);  
  54.         JButton pasteBn = new JButton(pasteAction);  
  55.         JPanel jp = new JPanel();  
  56.         jp.add(copyBn);  
  57.         jp.add(pasteBn);  
  58.         jf.add(jp , BorderLayout.SOUTH);  
  59.         //向工具条中添加Action对象,该对象将会转换成工具按钮  
  60.         jtb.add(copyAction);  
  61.         jtb.addSeparator();  
  62.         jtb.add(pasteAction);  
  63.         //向菜单中添加Action对象,该对象将会转换成菜单项  
  64.         edit.add(copyAction);  
  65.         edit.add(pasteAction);  
  66.         //将edit菜单添加到菜单条中  
  67.         jmb.add(edit);  
  68.         jf.setJMenuBar(jmb);  
  69.         //设置工具条和工具按钮之间的距离  
  70.         jtb.setMargin(new Insets(20 ,10 , 5 , 30));  
  71.         //向窗口中添加工具条  
  72.         jf.add(jtb , BorderLayout.NORTH);  
  73.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  74.         jf.pack();  
  75.         jf.setVisible(true);  
  76.     }  
  77.     public static void main(String[] args)   
  78.     {  
  79.         new TestJToolBar().init();  
  80.     }  

继续讲Swing的特殊组件,JColorChooser和JFileChooser这两个东西在awt中都是利用系统的控件,这样导致不同操作系统有不同的界面,用Swing就避免了这些问题。下面就先看JColorChooser的例子,eg(一个简单画图程序)

  1. public class HandDraw  
  2. {  
  3.     //画图区的宽度   
  4.     private final int AREA_WIDTH = 500;  
  5.     //画图区的高度  
  6.     private final int AREA_HEIGHT = 400;  
  7.     //下面的preX、preY保存了上一次鼠标拖动事件的鼠标座标  
  8.     private int preX = -1;  
  9.     private int preY = -1;  
  10.     //定义一个右键菜单用于设置画笔颜色  
  11.     JPopupMenu pop = new JPopupMenu();  
  12.     JMenuItem chooseColor = new JMenuItem("选择颜色");  
  13.     //定义一个BufferedImage对象  
  14.     BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT ,   
  15.         BufferedImage.TYPE_INT_RGB);  
  16.     //获取image对象的Graphics  
  17.     Graphics g = image.getGraphics();  
  18.     private JFrame f = new JFrame("简单手绘程序");  
  19.     private DrawCanvas drawArea = new DrawCanvas();  
  20.     //用于保存需要绘制什么图形的字符串属性  
  21.     private String shape = "";  
  22.     //用于保存画笔颜色  
  23.     private Color foreColor = new Color(2550 ,0);  
  24.     public void init()  
  25.     {  
  26.         chooseColor.addActionListener(new ActionListener()  
  27.         {  
  28.             public void actionPerformed(ActionEvent ae)  
  29.             {  
  30.                 //下面代码直接弹出一个模式的颜色选择器对话框,并返回用户选择的颜色  
  31.                 //foreColor = JColorChooser.showDialog(f , "选择画笔颜色" , foreColor);  
  32.                 //下面代码则可以弹出一个非模式的颜色选择对话框,  
  33.                 //并可以分别为“确定”按钮、“取消”按钮指定事件监听器  
  34.                 final JColorChooser colorPane = new JColorChooser(foreColor);  
  35.                 JDialog jd = JColorChooser.createDialog(f ,"选择画笔颜色",false,   
  36.                     colorPane, new ActionListener()  
  37.                     {  
  38.                         public void actionPerformed(ActionEvent ae)  
  39.                         {  
  40.                             foreColor = colorPane.getColor();  
  41.                         }  
  42.                     }, null);  
  43.                 jd.setVisible(true);  
  44.             }  
  45.         });  
  46.         //将菜单项组合成右键菜单  
  47.         pop.add(chooseColor);  
  48.         //将右键菜单添加到drawArea对象中  
  49.         drawArea.setComponentPopupMenu(pop);  
  50.         //将image对象的背景色填充成白色  
  51.         g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);  
  52.         drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT));  
  53.         //监听鼠标移动动作  
  54.         drawArea.addMouseMotionListener(new MouseMotionAdapter()  
  55.         {  
  56.             //实现按下鼠标键并拖动的事件处理器  
  57.             public void mouseDragged(MouseEvent e)  
  58.             {  
  59.                 //如果preX和preY大于0  
  60.                 if (preX > 0 && preY > 0)  
  61.                 {  
  62.                     //设置当前颜色  
  63.                     g.setColor(foreColor);  
  64.                     //绘制从上一次鼠标拖动事件点到本次鼠标拖动事件点的线段  
  65.                     g.drawLine(preX , preY , e.getX() , e.getY());  
  66.                 }  
  67.                 //将当前鼠标事件点的X、Y座标保存起来  
  68.                 preX = e.getX();  
  69.                 preY = e.getY();  
  70.                 //重绘drawArea对象  
  71.                 drawArea.repaint();  
  72.             }  
  73.         });  
  74.         //监听鼠标事件  
  75.         drawArea.addMouseListener(new MouseAdapter()  
  76.         {  
  77.             //实现鼠标松开的事件处理器  
  78.             public void mouseReleased(MouseEvent e)  
  79.             {  
  80.                 //松开鼠标键时,把上一次鼠标拖动事件的X、Y座标设为-1。  
  81.                 preX = -1;  
  82.                 preY = -1;  
  83.             }  
  84.         });  
  85.         f.add(drawArea);  
  86.         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  87.         f.pack();  
  88.         f.setVisible(true);  
  89.     }  
  90.     public static void main(String[] args)   
  91.     {  
  92.         new HandDraw().init();  
  93.     }  
  94.     //让画图区域继承JPanel类  
  95.     class DrawCanvas extends JPanel  
  96.     {  
  97.         //重写JPanel的paint方法,实现绘画  
  98.         public void paint(Graphics g)  
  99.         {  
  100.             //将image绘制到该组件上  
  101.             g.drawImage(image , 0 , 0 , null);  
  102.         }  
  103.     }  
  104. }  

下面举个JFileChooser,这些东西组件不是很常用,大家可以收藏着,到用的时候翻出来看,eg

  1. public class ImageViewer  
  2. {  
  3.     final int PREVIEW_SIZE = 100;  
  4.     JFrame jf = new JFrame("简单图片查看器");  
  5.     JMenuBar menuBar = new JMenuBar();  
  6.     //该label用于显示图片  
  7.     JLabel label = new JLabel();  
  8.     //以当前路径创建文件选择器  
  9.     JFileChooser chooser = new JFileChooser(".");  
  10.     JLabel accessory = new JLabel();  
  11.     ExtensionFileFilter filter = new ExtensionFileFilter();  
  12.     public void init()  
  13.     {  
  14.         //-------------------下面开始初始化JFileChooser的相关属性-----------------  
  15.         // 创建一个FileFilter  
  16.         filter.addExtension("jpg");  
  17.         filter.addExtension("jpeg");  
  18.         filter.addExtension("gif");  
  19.         filter.addExtension("png");  
  20.         filter.setDescription("图片文件(*.jpg,*.jpeg,*.gif,*.png)");  
  21.         chooser.addChoosableFileFilter(filter);  
  22.         //禁止“文件类型”下拉列表中显示“所有文件”选项。  
  23.         chooser.setAcceptAllFileFilterUsed(false);   
  24.         //为文件选择器指定自定义的FileView对象  
  25.         chooser.setFileView(new FileIconView(filter));  
  26.         //为文件选择器指定一个预览图片的附件组件  
  27.         chooser.setAccessory(accessory);  
  28.         //设置预览图片组件的大小和边框  
  29.         accessory.setPreferredSize(new Dimension(PREVIEW_SIZE, PREVIEW_SIZE));  
  30.         accessory.setBorder(BorderFactory.createEtchedBorder());  
  31.         //用于检测被选择文件的改变事件  
  32.         chooser.addPropertyChangeListener(new PropertyChangeListener()  
  33.         {  
  34.             public void propertyChange(PropertyChangeEvent event)   
  35.             {  
  36.                 //JFileChooser的被选文件已经发生了改变  
  37.                 if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)  
  38.                 {  
  39.                     //获取用户选择的新文件   
  40.                     File f = (File) event.getNewValue();  
  41.                     if (f == null)  
  42.                     {   
  43.                         accessory.setIcon(null);   
  44.                         return;   
  45.                     }  
  46.                     //将所文件读入ImageIcon对象中  
  47.                     ImageIcon icon = new ImageIcon(f.getPath());  
  48.                     //如果图像太大,则缩小它  
  49.                     if(icon.getIconWidth() > PREVIEW_SIZE)  
  50.                     {     
  51.                         icon = new ImageIcon(icon.getImage()  
  52.                             .getScaledInstance(PREVIEW_SIZE, -1, Image.SCALE_DEFAULT));  
  53.                     }  
  54.                     //改变accessory Label的图标  
  55.                     accessory.setIcon(icon);  
  56.                 }  
  57.             }  
  58.         });  
  59.  
  60.         //----------下面代码开始为该窗口安装菜单------------  
  61.         JMenu menu = new JMenu("文件");  
  62.         menuBar.add(menu);  
  63.         JMenuItem openItem = new JMenuItem("打开");  
  64.         menu.add(openItem);  
  65.         //单击openItem菜单项显示“打开文件”的对话框  
  66.         openItem.addActionListener(new ActionListener()  
  67.         {  
  68.             public void actionPerformed(ActionEvent event)  
  69.             {  
  70.                 //设置文件对话框的当前路径  
  71.                 //chooser.setCurrentDirectory(new File("."));  
  72.                 //显示文件对话框  
  73.                 int result = chooser.showDialog(jf , "打开图片文件");  
  74.                 //如果用户选择了APPROVE(赞同)按钮,即打开,保存及其等效按钮  
  75.                 if(result == JFileChooser.APPROVE_OPTION)  
  76.                 {  
  77.                     String name = chooser.getSelectedFile().getPath();  
  78.                     //显示指定图片  
  79.                     label.setIcon(new ImageIcon(name));  
  80.                 }  
  81.             }  
  82.         });  
  83.         JMenuItem exitItem = new JMenuItem("退出");  
  84.         menu.add(exitItem);  
  85.         exitItem.addActionListener(new ActionListener()  
  86.         {  
  87.             public void actionPerformed(ActionEvent event)  
  88.             {  
  89.                 System.exit(0);  
  90.             }  
  91.         });  
  92.         jf.setJMenuBar(menuBar);  
  93.         //添加用于显示图片的JLabel组件。  
  94.         jf.add(new JScrollPane(label));  
  95.         jf.setSize(500400);  
  96.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  97.         jf.setVisible(true);  
  98.     }  
  99.  
  100.     public static void main(String[] args)  
  101.     {  
  102.         new ImageViewer().init();  
  103.     }  
  104. }  
  105.  
  106. //创建FileFilter的子类,用以实现文件过滤功能  
  107. class ExtensionFileFilter extends FileFilter  
  108. {  
  109.  
  110.     private String description = "";  
  111.     private ArrayList<String> extensions = new ArrayList<String>();  
  112.     //自定义方法,用于添加文件扩展名  
  113.     public void addExtension(String extension)  
  114.     {  
  115.         if (!extension.startsWith("."))  
  116.         {  
  117.             extension = "." + extension;  
  118.             extensions.add(extension.toLowerCase());  
  119.         }  
  120.     }  
  121.     //用于设置该文件过滤器的描述文本  
  122.     public void setDescription(String aDescription)  
  123.     {  
  124.         description = aDescription;  
  125.     }  
  126.     //继承FileFilter类必须实现的抽象方法,返回该文件过滤器的描述文本  
  127.     public String getDescription()  
  128.     {  
  129.         return description;   
  130.     }  
  131.     //继承FileFilter类必须实现的抽象方法,判断该文件过滤器是否接受该文件  
  132.     public boolean accept(File f)  
  133.     {  
  134.         //如果该文件是路径,接受该文件  
  135.         if (f.isDirectory()) return true;  
  136.         //将文件名转为小写(全部转为小写后比较,用于忽略文件名大小写)  
  137.         String name = f.getName().toLowerCase();  
  138.         //遍历所有可接受的扩展名,如果扩展名相同,该文件就可接受。  
  139.         for (String extension : extensions)  
  140.         {  
  141.             if (name.endsWith(extension))   
  142.             {  
  143.                 return true;  
  144.             }  
  145.         }  
  146.         return false;  
  147.     }  
  148. }  
  149. //自定义一个FileView类,用于为指定类型的指定图标  
  150. class FileIconView extends FileView  
  151. {  
  152.     private FileFilter filter;  
  153.     public FileIconView(FileFilter filter)  
  154.     {  
  155.         this.filter = filter;  
  156.     }  
  157.     //如果文件不是目录,并且不是  
  158.     public Icon getIcon(File f)  
  159.     {  
  160.         if (!f.isDirectory() && filter.accept(f))  
  161.         {  
  162.             return new ImageIcon("ico/pict.png");  
  163.         }  
  164.         else if (f.isDirectory())  
  165.         {  
  166.             //获取所有根路径  
  167.             File[] fList = File.listRoots();  
  168.             for (File tmp : fList)  
  169.             {  
  170.                 //如果该路径是根路径  
  171.                 if (tmp.equals(f))  
  172.                 {  
  173.                     return  new ImageIcon("ico/dsk.png");  
  174.                 }  
  175.             }  
  176.             return new ImageIcon("ico/folder.png");  
  177.         }  
  178.         //使用默认图标  
  179.         else 
  180.         {  
  181.             return null;  
  182.         }  
  183.     }  

注意:以上图片我都没给,自己随便弄几张看看效果

JOptionPane是一种特殊的JFrame,他的出现是为了方便我们创建一些简单的对话框,你也可以用JFrame搞一个,但很繁琐,但如果你用UI的拖拽工具那就没什么了。eg(各种对话框)

  1. public class TestJOptionPane  
  2. {  
  3.     JFrame jf = new JFrame("测试JOptionPane");  
  4.     //分别定义6个面板用于定义对话框的几种选项  
  5.     private ButtonPanel messagePanel;  
  6.     private ButtonPanel messageTypePanel;  
  7.     private ButtonPanel msgPanel;  
  8.     private ButtonPanel confirmPanel;  
  9.     private ButtonPanel optionsPanel;  
  10.     private ButtonPanel inputPanel;  
  11.     private String messageString = "消息区内容";  
  12.     private Icon messageIcon = new ImageIcon("ico/heart.png");  
  13.     private Object messageObject = new Date();  
  14.     private Component messageComponent = new JButton("组件消息");  
  15.     private JButton msgBn = new JButton("消息对话框");  
  16.     private JButton confrimBn = new JButton("确认对话框");  
  17.     private JButton inputBn = new JButton("输入对话框");  
  18.     private JButton optionBn = new JButton("选项对话框");  
  19.  
  20.     public void init()  
  21.     {  
  22.         JPanel top = new JPanel();  
  23.         top.setBorder(new TitledBorder(new EtchedBorder(), "对话框的通用选项" ,   
  24.             TitledBorder.CENTER ,TitledBorder.TOP ));  
  25.         top.setLayout(new GridLayout(1 , 2));  
  26.         //消息类型Panel,该Panel中的选项决定对话框的图标  
  27.         messageTypePanel = new ButtonPanel("选择消息的类型",   
  28.             new String[]{"ERROR_MESSAGE""INFORMATION_MESSAGE""WARNING_MESSAGE",   
  29.             "QUESTION_MESSAGE""PLAIN_MESSAGE" });  
  30.         //消息内容类型的Panel,该Panel中的选项决定对话框的消息区的内容  
  31.         messagePanel = new ButtonPanel("选择消息内容的类型",   
  32.             new String[]{"字符串消息""图标消息""组件消息",   "普通对象消息" , "Object[]消息"});  
  33.         top.add(messageTypePanel);  
  34.         top.add(messagePanel);  
  35.         JPanel bottom = new JPanel();  
  36.         bottom.setBorder(new TitledBorder(new EtchedBorder(), "弹出不同的对话框" ,   
  37.             TitledBorder.CENTER ,TitledBorder.TOP));  
  38.         bottom.setLayout(new GridLayout(1 , 4));  
  39.         //创建用于弹出消息对话框的Panel  
  40.         msgPanel = new ButtonPanel("消息对话框"null);  
  41.         msgBn.addActionListener(new ShowAction());  
  42.         msgPanel.add(msgBn);  
  43.         //创建用于弹出确认对话框的Panel  
  44.         confirmPanel = new ButtonPanel("确认对话框",   
  45.             new String[]{"DEFAULT_OPTION""YES_NO_OPTION""YES_NO_CANCEL_OPTION",  
  46.             "OK_CANCEL_OPTION"});  
  47.         confrimBn.addActionListener(new ShowAction());  
  48.         confirmPanel.add(confrimBn);  
  49.         //创建用于弹出输入对话框的Panel  
  50.         inputPanel = new ButtonPanel("输入对话框",  
  51.             new String[]{"单行文本框","下拉列表选择框"});  
  52.         inputBn.addActionListener(new ShowAction());  
  53.         inputPanel.add(inputBn);  
  54.         //创建用于弹出选项对话框的Panel  
  55.         optionsPanel = new ButtonPanel("选项对话框",   
  56.             new String[]{"字符串选项""图标选项""对象选项"});  
  57.         optionBn.addActionListener(new ShowAction());  
  58.         optionsPanel.add(optionBn);  
  59.         bottom.add(msgPanel);  
  60.         bottom.add(confirmPanel);  
  61.         bottom.add(inputPanel);  
  62.         bottom.add(optionsPanel);  
  63.         Box box = new Box(BoxLayout.Y_AXIS);  
  64.         box.add(top);  
  65.         box.add(bottom);  
  66.         jf.add(box);  
  67.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  68.         jf.pack();  
  69.         jf.setVisible(true);  
  70.     }  
  71.     //根据用户选择返回选项类型  
  72.     private int getOptionType()  
  73.     {  
  74.         if (confirmPanel.getSelection().equals("DEFAULT_OPTION"))  
  75.             return JOptionPane.DEFAULT_OPTION;  
  76.         else if (confirmPanel.getSelection().equals("YES_NO_OPTION"))  
  77.             return JOptionPane.YES_NO_OPTION;  
  78.         else if (confirmPanel.getSelection().equals("YES_NO_CANCEL_OPTION"))  
  79.             return JOptionPane.YES_NO_CANCEL_OPTION;  
  80.         else 
  81.             return JOptionPane.OK_CANCEL_OPTION;  
  82.     }  
  83.     //根据用户选择返回消息  
  84.     private Object getMessage()  
  85.     {  
  86.         if (messagePanel.getSelection().equals("字符串消息"))  
  87.             return messageString;  
  88.         else if (messagePanel.getSelection().equals("图标消息"))  
  89.             return messageIcon;  
  90.         else if (messagePanel.getSelection().equals("组件消息"))  
  91.             return messageComponent;  
  92.         else if(messagePanel.getSelection().equals("普通对象消息"))  
  93.             return messageObject;  
  94.         else 
  95.             return  new Object[]{messageString , messageIcon ,   
  96.                 messageObject , messageComponent};  
  97.     }  
  98.     //根据用户选择返回消息类型(决定图标区的图标)  
  99.     private int getDialogType()  
  100.     {  
  101.         if (messageTypePanel.getSelection().equals("ERROR_MESSAGE"))  
  102.             return JOptionPane.ERROR_MESSAGE;  
  103.         else if (messageTypePanel.getSelection().equals("INFORMATION_MESSAGE"))  
  104.             return JOptionPane.INFORMATION_MESSAGE;  
  105.         else if (messageTypePanel.getSelection().equals("WARNING_MESSAGE"))  
  106.             return JOptionPane.WARNING_MESSAGE;  
  107.         else if(messageTypePanel.getSelection().equals("QUESTION_MESSAGE"))  
  108.             return JOptionPane.QUESTION_MESSAGE;  
  109.         else 
  110.             return JOptionPane.PLAIN_MESSAGE;  
  111.     }  
  112.     private Object[] getOptions()  
  113.     {  
  114.         if (optionsPanel.getSelection().equals("字符串选项"))  
  115.             return new String[]{"a" , "b" , "c" , "d"};  
  116.         else if (optionsPanel.getSelection().equals("图标选项"))  
  117.             return new Icon[]{new ImageIcon("ico/1.gif") , new ImageIcon("ico/2.gif"),  
  118.             new ImageIcon("ico/3.gif"),new ImageIcon("ico/4.gif")};  
  119.         else 
  120.             return new Object[]{new Date() ,new Date() , new Date()};  
  121.     }  
  122.  
  123.     //为各按钮定义事件监听器  
  124.     private class ShowAction implements ActionListener  
  125.     {  
  126.         public void actionPerformed(ActionEvent event)  
  127.         {    
  128.             if (event.getActionCommand().equals("确认对话框"))  
  129.             {  
  130.                 JOptionPane.showConfirmDialog(jf , getMessage(),"确认对话框",   
  131.                     getOptionType(), getDialogType());  
  132.             }  
  133.             else if (event.getActionCommand().equals("输入对话框"))  
  134.             {    
  135.                 if (inputPanel.getSelection().equals("单行文本框"))  
  136.                 {  
  137.                     JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType());  
  138.                 }  
  139.                 else 
  140.                 {  
  141.                     JOptionPane.showInputDialog(jf, getMessage(), "输入对话框", getDialogType(),  
  142.                     null,   new String[] {"轻量级J2EE企业应用实战""Struts2权威指南"},   
  143.                     "Struts2权威指南");  
  144.                 }  
  145.             }  
  146.             else if (event.getActionCommand().equals("消息对话框"))  
  147.             {  
  148.                 JOptionPane.showMessageDialog(jf,getMessage(),"消息对话框",getDialogType());  
  149.             }  
  150.             else if (event.getActionCommand().equals("选项对话框"))  
  151.             {  
  152.                 JOptionPane.showOptionDialog(jf , getMessage() , "选项对话框", getOptionType(),  
  153.                     getDialogType(), null,  getOptions(), "a");  
  154.             }  
  155.         }  
  156.     }  
  157.  
  158.     public static void main(String[] args)  
  159.     {    
  160.         new TestJOptionPane().init();  
  161.     }  
  162. }  
  163.  
  164. //定义一个JPanel类扩展类,该类的对象包含多个纵向排列的JRadioButton控件  
  165. //且Panel扩展类可以指定一个字符串作为TitledBorder  
  166. class ButtonPanel extends JPanel  
  167. {    
  168.     private ButtonGroup group;  
  169.     public ButtonPanel(String title, String[] options)  
  170.     {    
  171.         setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));  
  172.         setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));  
  173.         group = new ButtonGroup();  
  174.         for (int i = 0; options!= null && i < options.length; i++)  
  175.         {    
  176.             JRadioButton b = new JRadioButton(options[i]);  
  177.             b.setActionCommand(options[i]);  
  178.             add(b);  
  179.             group.add(b);  
  180.             b.setSelected(i == 0);  
  181.         }  
  182.     }  
  183.     //定义一个方法,用于返回用户选择的选项  
  184.     public String getSelection()  
  185.     {    
  186.         return group.getSelection().getActionCommand();  
  187.     }     

看似简单,用起来花样还是挺多的。

原文链接:http://blog.csdn.net/terryzero/article/details/3763592

【编辑推荐】

  1. 用Swing制作精美的图层叠加图
  2. 简述Java图形用户界面设计(Swing)
  3. Java编码及网络传输中的编码问题
  4. Rhino 使 JavaScript 应用程序更灵动
  5. 探讨:Java中删除数组中重复元素
责任编辑:林师授 来源: terryzero的博客
相关推荐

2014-03-27 15:34:55

Android组件Activity

2010-03-04 10:01:01

Android基本组件

2020-04-19 17:14:17

服务器监控数据中心

2019-11-27 10:36:23

数据中心边缘计算技术

2012-01-17 14:09:54

JavaSwing

2012-01-17 13:41:34

JavaSwing

2012-01-17 14:05:29

JavaSwing

2012-01-17 13:46:55

JavaSwing

2011-05-24 16:20:44

OpenFlow网络组成

2012-01-17 13:53:16

JavaSwing

2009-07-15 13:06:38

Swing组件

2009-07-10 18:06:59

JTree Swing

2009-07-17 12:54:13

2009-07-10 09:38:06

Java swing组

2009-07-15 11:02:32

Swing组件

2009-07-14 17:21:42

Swing组件

2009-07-17 11:13:46

AWT和SwingSwing组件

2009-07-10 12:30:12

Swing组件

2009-07-10 17:03:17

AWT组件Swing组件

2009-07-17 14:38:51

轻量级Swing组件
点赞
收藏

51CTO技术栈公众号