100个Java经典例子(11-20)初学者的利器高手的宝典JavaSE

[java]  view plain copy
  1. package test11;  
  2.   
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.awt.event.KeyEvent;  
  6.   
  7. import javax.swing.AbstractButton;  
  8. import javax.swing.ImageIcon;  
  9. import javax.swing.JButton;  
  10. import javax.swing.JFrame;  
  11. import javax.swing.JPanel;  
  12.   
  13. /** 
  14.  * Title: 按钮演示 
  15.  * Description: 提供一个按钮的演示。如何实现按钮和是一个按钮失效 
  16.  * Filename:  
  17.  */  
  18. public class ButtonDemo extends JPanel  
  19.                         implements ActionListener {  
  20.       
  21.     private static final long serialVersionUID = 1L;  
  22.     protected JButton b1, b2, b3;  
  23. /** 
  24.  *方法说明:构造器,初始图形界面构建 
  25.  */  
  26.     public ButtonDemo() {  
  27.         ImageIcon leftButtonIcon = createImageIcon("images/right.gif");  
  28.         ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");  
  29.         ImageIcon rightButtonIcon = createImageIcon("images/left.gif");  
  30.   
  31.         b1 = new JButton("失效中间按钮(D)", leftButtonIcon);  
  32.         b1.setVerticalTextPosition(AbstractButton.CENTER);//水平中间对齐  
  33.         b1.setHorizontalTextPosition(AbstractButton.LEADING);//相当于LEFT  
  34.         b1.setMnemonic(KeyEvent.VK_D);//将b1邦定alt+D键  
  35.         b1.setActionCommand("disable");  
  36.   
  37.         b2 = new JButton("M中间按钮", middleButtonIcon);  
  38.         b2.setVerticalTextPosition(AbstractButton.BOTTOM);  
  39.         b2.setHorizontalTextPosition(AbstractButton.CENTER);  
  40.         b2.setMnemonic(KeyEvent.VK_M);//将b2邦定alt+M键  
  41.   
  42.         b3 = new JButton("E激活中间按钮", rightButtonIcon);  
  43.         b3.setMnemonic(KeyEvent.VK_E);//将b3邦定alt+E键  
  44.         b3.setActionCommand("enable");  
  45.         b3.setEnabled(false);  
  46.   
  47.         //给1和3添加事件监听  
  48.         b1.addActionListener(this);  
  49.         b3.addActionListener(this);  
  50.         //设置按钮提示文本  
  51.         b1.setToolTipText("点击这个按钮,将使中间的按钮失效!");  
  52.         b2.setToolTipText("点击这个按钮,没有任何的事件发生!");  
  53.         b3.setToolTipText("点击这个按钮,将使中间的按钮有效");  
  54.   
  55.         //将按钮添加到JPanel中  
  56.         add(b1);  
  57.         add(b2);  
  58.         add(b3);  
  59.     }  
  60. /** 
  61.  *方法说明:事件处理 
  62.  */  
  63.     public void actionPerformed(ActionEvent e) {  
  64.         if ("disable".equals(e.getActionCommand())) {  
  65.             b2.setEnabled(false);  
  66.             b1.setEnabled(false);  
  67.             b3.setEnabled(true);  
  68.         } else {  
  69.             b2.setEnabled(true);  
  70.             b1.setEnabled(true);  
  71.             b3.setEnabled(false);  
  72.         }  
  73.     }  
  74. /** 
  75.  *方法说明:创建图标, 
  76.  *输入参数:String path 图标所在的路径 
  77.  *返回类型:ImageIcon 图标对象 
  78.  */  
  79.     protected static ImageIcon createImageIcon(String path) {  
  80.         java.net.URL imgURL = ButtonDemo.class.getResource(path);  
  81.         if (imgURL != null) {  
  82.             return new ImageIcon(imgURL);  
  83.         } else {  
  84.             System.err.println("Couldn't find file: " + path);  
  85.             return null;  
  86.         }  
  87.     }  
  88. /** 
  89.  *方法说明:主方法 
  90.  */  
  91.     public static void main(String[] args) {  
  92.         //设置使用新的swing界面  
  93.         JFrame.setDefaultLookAndFeelDecorated(true);  
  94.   
  95.         //创建一个窗体  
  96.         JFrame frame = new JFrame("ButtonDemo");  
  97.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  98.   
  99.         //创建一个面板  
  100.         ButtonDemo newContentPane = new ButtonDemo();  
  101.         newContentPane.setOpaque(true);   
  102.         frame.setContentPane(newContentPane);  
  103.   
  104.         //显示窗体  
  105.         frame.pack();  
  106.         frame.setVisible(true);  
  107.     }  
  108. }  
[java]  view plain copy
  1. package test12;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. /** 
  7.  * Title: 检查盒演示 
  8.  * Description: 选择不同的选择框显示不同的图片 
  9.  * Filename: CheckBoxDemo.java< 
  10.  */  
  11. public class CheckBoxDemo extends JPanel  
  12.                           implements ItemListener {  
  13.      
  14.     private static final long serialVersionUID = 1L;  
  15.     JCheckBox chinButton;  
  16.     JCheckBox glassesButton;  
  17.     JCheckBox hairButton;  
  18.     JCheckBox teethButton;  
  19.   
  20.     /* 
  21.      * 有四个检查盒,分别对应下巴、眼镜、头发和牙齿 
  22.      * 图片不是拼出来的,而是根据检查盒选择拼写图片文件名 
  23.      * 图片文件名的定义格式为"geek-XXXX.gif" 
  24.      * 其中 XXXX 根据检查盒的不同选择,而不同。它的格式如下: 
  25.  
  26.        ----             //没有选择 
  27.  
  28.        c---             //一个选择 
  29.        -g-- 
  30.        --h- 
  31.        ---t 
  32.  
  33.        cg--             //两个选择 
  34.        c-h- 
  35.        c--t 
  36.        -gh- 
  37.        -g-t 
  38.        --ht 
  39.  
  40.        -ght             //三个选择 
  41.        c-ht 
  42.        cg-t 
  43.        cgh- 
  44.  
  45.        cght             //所有都选 
  46.      */  
  47.   
  48.     StringBuffer choices;  
  49.     JLabel pictureLabel;  
  50.   
  51.     public CheckBoxDemo() {  
  52.         super(new BorderLayout());  
  53.   
  54.         //创建检查盒  
  55.         chinButton = new JCheckBox("下巴(c)");  
  56.         chinButton.setMnemonic(KeyEvent.VK_C);  
  57.         chinButton.setSelected(true);  
  58.   
  59.         glassesButton = new JCheckBox("眼镜(g)");  
  60.         glassesButton.setMnemonic(KeyEvent.VK_G);  
  61.         glassesButton.setSelected(true);  
  62.   
  63.         hairButton = new JCheckBox("头发(h)");  
  64.         hairButton.setMnemonic(KeyEvent.VK_H);  
  65.         hairButton.setSelected(true);  
  66.   
  67.         teethButton = new JCheckBox("牙齿(t)");  
  68.         teethButton.setMnemonic(KeyEvent.VK_T);  
  69.         teethButton.setSelected(true);  
  70.   
  71.         //给检查盒添加监听  
  72.         chinButton.addItemListener(this);  
  73.         glassesButton.addItemListener(this);  
  74.         hairButton.addItemListener(this);  
  75.         teethButton.addItemListener(this);  
  76.   
  77.         choices = new StringBuffer("cght");  
  78.   
  79.         //放置一个带图片的标签  
  80.         pictureLabel = new JLabel();  
  81.         pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));  
  82.         updatePicture();  
  83.   
  84.         //将检查盒放置到面版中  
  85.         JPanel checkPanel = new JPanel(new GridLayout(01));  
  86.         checkPanel.add(chinButton);  
  87.         checkPanel.add(glassesButton);  
  88.         checkPanel.add(hairButton);  
  89.         checkPanel.add(teethButton);  
  90.   
  91.         add(checkPanel, BorderLayout.LINE_START);  
  92.         add(pictureLabel, BorderLayout.CENTER);  
  93.         setBorder(BorderFactory.createEmptyBorder(20,20,20,20));  
  94.     }  
  95. /** 
  96.  *<br>方法说明:监听检查盒事件,拼凑图片的文件名XXXX部分 
  97.  *<br>输入参数: 
  98.  *<br>返回类型: 
  99.  */  
  100.     public void itemStateChanged(ItemEvent e) {  
  101.         int index = 0;  
  102.         char c = '-';  
  103.         Object source = e.getItemSelectable();  
  104.   
  105.         if (source == chinButton) {  
  106.             index = 0;  
  107.             c = 'c';  
  108.         } else if (source == glassesButton) {  
  109.             index = 1;  
  110.             c = 'g';  
  111.         } else if (source == hairButton) {  
  112.             index = 2;  
  113.             c = 'h';  
  114.         } else if (source == teethButton) {  
  115.             index = 3;  
  116.             c = 't';  
  117.         }  
  118.           
  119.         //取消选择事件  
  120.         if (e.getStateChange() == ItemEvent.DESELECTED) {  
  121.             c = '-';  
  122.         }  
  123.   
  124.         //改变文件名字XXXX  
  125.         choices.setCharAt(index, c);  
  126.   
  127.         updatePicture();  
  128.     }  
  129. /** 
  130.  *<br>方法说明:绘制图片 
  131.  *<br>输入参数: 
  132.  *<br>返回类型: 
  133.  */  
  134.     protected void updatePicture() {  
  135.         //将得到的图片制成图标  
  136.         ImageIcon icon = createImageIcon(  
  137.                                     "images/geek/geek-"  
  138.                                     + choices.toString()  
  139.                                     + ".gif");  
  140.         pictureLabel.setIcon(icon);  
  141.         pictureLabel.setToolTipText(choices.toString());  
  142.         if (icon == null) {  
  143.             pictureLabel.setText("没有发现图片");  
  144.         } else {  
  145.             pictureLabel.setText(null);  
  146.         }  
  147.     }  
  148. /** 
  149.  *<br>方法说明:获取图标 
  150.  *<br>输入参数:String path 图片路径 
  151.  *<br>返回类型:ImageIcon对象 
  152.  */  
  153.     protected static ImageIcon createImageIcon(String path) {  
  154.         java.net.URL imgURL = CheckBoxDemo.class.getResource(path);  
  155.         if (imgURL != null) {  
  156.             return new ImageIcon(imgURL);  
  157.         } else {  
  158.             System.err.println("Couldn't find file: " + path);  
  159.             return null;  
  160.         }  
  161.     }  
  162. /** 
  163.  *<br>方法说明:主方法 
  164.  *<br>输入参数: 
  165.  *<br>返回类型: 
  166.  */  
  167.     public static void main(String s[]) {  
  168.          JFrame.setDefaultLookAndFeelDecorated(true);  
  169.   
  170.         //创建一个窗体,  
  171.         JFrame frame = new JFrame("CheckBoxDemo");  
  172.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  173.   
  174.         //创建一个面板  
  175.         JComponent newContentPane = new CheckBoxDemo();  
  176.         newContentPane.setOpaque(true);  
  177.         frame.setContentPane(newContentPane);  
  178.   
  179.         //显示窗体  
  180.         frame.pack();  
  181.         frame.setVisible(true);  
  182.     }  
  183. }  

[java]  view plain copy
  1. package test13;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. import java.util.*;  
  7. import java.text.SimpleDateFormat;  
  8. /** 
  9.  * Title: ComboBox下拉域演示</p> 
  10.  * Description: 通过选择或这输入一种日期格式来格式化今天的日期 
  11.  * Filename: ComboBoxDemo.java 
  12.  */  
  13.   
  14. public class ComboBoxDemo extends JPanel  
  15.                            implements ActionListener {  
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.     static JFrame frame;  
  19.     JLabel result;  
  20.     String currentPattern;  
  21. /** 
  22.  *方法说明:构造器。初始化窗体构件 
  23.  */  
  24.     public ComboBoxDemo() {  
  25.         setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));  
  26.         String[] patternExamples = {  
  27.                  "dd MMMMM yyyy",  
  28.                  "dd.MM.yy",  
  29.                  "MM/dd/yy",  
  30.                  "yyyy.MM.dd G 'at' hh:mm:ss z",  
  31.                  "EEE, MMM d, ''yy",  
  32.                  "h:mm a",  
  33.                  "H:mm:ss:SSS",  
  34.                  "K:mm a,z",  
  35.                  "yyyy.MMMMM.dd GGG hh:mm aaa"  
  36.                  };  
  37.   
  38.         currentPattern = patternExamples[0];  
  39.   
  40.         //设置一个规范的用户界面  
  41.         JLabel patternLabel1 = new JLabel("输入一个字符格式或者");  
  42.         JLabel patternLabel2 = new JLabel("从下拉列表中选择一种:");  
  43.   
  44.         JComboBox patternList = new JComboBox(patternExamples);  
  45.         patternList.setEditable(true);//标注这里ComboBox可进行编辑  
  46.         patternList.addActionListener(this);  
  47.   
  48.         //创建一个显示结果用户界面  
  49.         JLabel resultLabel = new JLabel("当前 日期/时间",  
  50.                                         JLabel.LEADING);//相当于LEFT  
  51.         result = new JLabel(" ");  
  52.         result.setForeground(Color.black);  
  53.         result.setBorder(BorderFactory.createCompoundBorder(  
  54.              BorderFactory.createLineBorder(Color.black),  
  55.              BorderFactory.createEmptyBorder(5,5,5,5)  
  56.         ));  
  57.   
  58.         //布置构件  
  59.         JPanel patternPanel = new JPanel();  
  60.         patternPanel.setLayout(new BoxLayout(patternPanel,  
  61.                                BoxLayout.PAGE_AXIS));  
  62.         patternPanel.add(patternLabel1);  
  63.         patternPanel.add(patternLabel2);  
  64.         patternList.setAlignmentX(Component.LEFT_ALIGNMENT);  
  65.         patternPanel.add(patternList);  
  66.   
  67.         JPanel resultPanel = new JPanel(new GridLayout(01));  
  68.         resultPanel.add(resultLabel);  
  69.         resultPanel.add(result);  
  70.   
  71.         patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);  
  72.         resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);  
  73.   
  74.         add(patternPanel);  
  75.         add(Box.createRigidArea(new Dimension(010)));  
  76.         add(resultPanel);  
  77.   
  78.         setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  79.   
  80.         reformat();  
  81.     }   
  82. /** 
  83.  *方法说明:事件处理 
  84.  */  
  85.     public void actionPerformed(ActionEvent e) {  
  86.         JComboBox cb = (JComboBox)e.getSource();  
  87.         String newSelection = (String)cb.getSelectedItem();  
  88.         currentPattern = newSelection;  
  89.         reformat();  
  90.     }  
  91. /** 
  92.  *方法说明:格式和显示今天的日期 
  93.  */  
  94.     public void reformat() {  
  95.         Date today = new Date();  
  96.         SimpleDateFormat formatter =  
  97.            new SimpleDateFormat(currentPattern);  
  98.         try {  
  99.             String dateString = formatter.format(today);  
  100.             result.setForeground(Color.black);  
  101.             result.setText(dateString);  
  102.         } catch (IllegalArgumentException iae) {  
  103.             result.setForeground(Color.red);  
  104.             result.setText("Error: " + iae.getMessage());  
  105.         }  
  106.     }  
  107. /** 
  108.  *方法说明:主方法 
  109.  */  
  110.     public static void main(String[] args) {  
  111.         JFrame.setDefaultLookAndFeelDecorated(true);  
  112.   
  113.         //创建一个窗体  
  114.         frame = new JFrame("ComboBoxDemo");  
  115.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  116.   
  117.         //创建一个面版容器  
  118.         JComponent newContentPane = new ComboBoxDemo();  
  119.         newContentPane.setOpaque(true);  
  120.         frame.setContentPane(newContentPane);  
  121.   
  122.         //显示窗体  
  123.         frame.pack();  
  124.         frame.setVisible(true);  
  125.     }  
  126. }  

[java]  view plain copy
  1. package test14;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.*;  
  6. import javax.swing.event.*;  
  7. /** 
  8.  * Title: 列表框 
  9.  * Description: 通过输入框添加元素和点击“删除”按钮删除列表元素 
  10.  * Filename: ListDemo.java 
  11.  */  
  12. public class ListDemo extends JPanel  
  13.                       implements ListSelectionListener {  
  14.     private static final long serialVersionUID = 1L;  
  15.     private JList list;  
  16.     private DefaultListModel listModel;  
  17.   
  18.     private static final String hireString = "添加";  
  19.     private static final String fireString = "删除";  
  20.     private JButton fireButton;  
  21.     private JTextField employeeName;  
  22.   
  23.     public ListDemo() {  
  24.         super(new BorderLayout());  
  25.         //构建List的列表元素  
  26.         listModel = new DefaultListModel();  
  27.         listModel.addElement("Alan Sommerer");  
  28.         listModel.addElement("Alison Huml");  
  29.         listModel.addElement("Kathy Walrath");  
  30.         listModel.addElement("Lisa Friendly");  
  31.         listModel.addElement("Mary Campione");  
  32.         listModel.addElement("Sharon Zakhour");  
  33.   
  34.         //创建一个List构件,并将列表元素添加到列表中  
  35.         list = new JList(listModel);  
  36.         //设置选择模式为单选  
  37.         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  38.         //初始化选择索引在0的位置,即第一个元素  
  39.         list.setSelectedIndex(0);  
  40.         list.addListSelectionListener(this);  
  41.         //设置列表可以同时看5个元素  
  42.         list.setVisibleRowCount(5);  
  43.         //给列表添加一个滑动块  
  44.         JScrollPane listScrollPane = new JScrollPane(list);  
  45.   
  46.         JButton hireButton = new JButton(hireString);  
  47.         HireListener hireListener = new HireListener(hireButton);  
  48.         hireButton.setActionCommand(hireString);  
  49.         hireButton.addActionListener(hireListener);  
  50.         hireButton.setEnabled(false);  
  51.   
  52.         fireButton = new JButton(fireString);  
  53.         fireButton.setActionCommand(fireString);  
  54.         fireButton.addActionListener(new FireListener());  
  55.   
  56.         employeeName = new JTextField(10);  
  57.         employeeName.addActionListener(hireListener);  
  58.         employeeName.getDocument().addDocumentListener(hireListener);  
  59.         @SuppressWarnings("unused")  
  60.         String name = listModel.getElementAt(  
  61.                               list.getSelectedIndex()).toString();  
  62.   
  63.         //创建一个面板  
  64.         JPanel buttonPane = new JPanel();  
  65.         buttonPane.setLayout(new BoxLayout(buttonPane,  
  66.                                            BoxLayout.LINE_AXIS));  
  67.         buttonPane.add(fireButton);  
  68.         buttonPane.add(Box.createHorizontalStrut(5));  
  69.         buttonPane.add(new JSeparator(SwingConstants.VERTICAL));  
  70.         buttonPane.add(Box.createHorizontalStrut(5));  
  71.         buttonPane.add(employeeName);  
  72.         buttonPane.add(hireButton);  
  73.         buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));  
  74.   
  75.         add(listScrollPane, BorderLayout.CENTER);  
  76.         add(buttonPane, BorderLayout.PAGE_END);  
  77.     }  
  78. /** 
  79.  *类说明:“添加”按钮监听 
  80.  *类描述:当点击“添加”按钮后,实现将元素添加到列表框中 
  81.  */  
  82.     class FireListener implements ActionListener {  
  83.         public void actionPerformed(ActionEvent e) {  
  84.              
  85.             int index = list.getSelectedIndex();  
  86.             listModel.remove(index);  
  87.   
  88.             int size = listModel.getSize();  
  89.   
  90.             if (size == 0) { //如果没有了选择项,则是“删除”按钮实效  
  91.                 fireButton.setEnabled(false);  
  92.   
  93.             } else { //选择了一个  
  94.                 if (index == listModel.getSize()) {  
  95.                     //移除选项  
  96.                     index--;  
  97.                 }  
  98.   
  99.                 list.setSelectedIndex(index);  
  100.                 list.ensureIndexIsVisible(index);  
  101.             }  
  102.         }  
  103.     }  
  104.   
  105. /** 
  106.  *类说明:“删除”按钮监听事件 
  107.  *类描述:实现删除列表元素 
  108.  */  
  109.     class HireListener implements ActionListener, DocumentListener {  
  110.         private boolean alreadyEnabled = false;  
  111.         private JButton button;  
  112.   
  113.         public HireListener(JButton button) {  
  114.             this.button = button;  
  115.         }  
  116.   
  117.         //必须实现 ActionListener.  
  118.         public void actionPerformed(ActionEvent e) {  
  119.             String name = employeeName.getText();  
  120.   
  121.             //如果输入空或有同名  
  122.             if (name.equals("") || alreadyInList(name)) {  
  123.                 Toolkit.getDefaultToolkit().beep();  
  124.                 employeeName.requestFocusInWindow();  
  125.                 employeeName.selectAll();  
  126.                 return;  
  127.             }  
  128.   
  129.             int index = list.getSelectedIndex(); //获取选择项  
  130.             if (index == -1) { //如果没有选择,就插入到第一个  
  131.                 index = 0;  
  132.             } else {           //如果有选择,那么插入到选择项的后面  
  133.                 index++;  
  134.             }  
  135.   
  136.             listModel.insertElementAt(employeeName.getText(), index);  
  137.    
  138.             //重新设置文本  
  139.             employeeName.requestFocusInWindow();  
  140.             employeeName.setText("");  
  141.   
  142.             //选择新的元素,并显示出来  
  143.             list.setSelectedIndex(index);  
  144.             list.ensureIndexIsVisible(index);  
  145.         }  
  146. /** 
  147.  *方法说明:检测是否在LIST中有重名元素 
  148.  *输入参数:String name 检测的名字 
  149.  *返回类型:boolean 布尔值,如果存在返回true 
  150.  */  
  151.   
  152.         protected boolean alreadyInList(String name) {  
  153.             return listModel.contains(name);  
  154.         }  
  155.   
  156. /** 
  157.  *方法说明:实现DocumentListener接口,必需实现的方法: 
  158.  */  
  159.         public void insertUpdate(DocumentEvent e) {  
  160.             enableButton();  
  161.         }  
  162.   
  163. /** 
  164.  *方法说明:实现DocumentListener接口,必需实现的方法 
  165.  */  
  166.         public void removeUpdate(DocumentEvent e) {  
  167.             handleEmptyTextField(e);  
  168.         }  
  169.   
  170. /** 
  171.  *方法说明:实现DocumentListener接口,必需实现的方法 
  172.  */  
  173.         public void changedUpdate(DocumentEvent e) {  
  174.             if (!handleEmptyTextField(e)) {  
  175.                 enableButton();  
  176.             }  
  177.         }  
  178. /** 
  179.  *方法说明:按钮使能 
  180.  */  
  181.         private void enableButton() {  
  182.             if (!alreadyEnabled) {  
  183.                 button.setEnabled(true);  
  184.             }  
  185.         }  
  186. /** 
  187.  *方法说明:实现DocumentListener接口,必需实现的方法,修改按钮的状态 
  188.  */  
  189.         private boolean handleEmptyTextField(DocumentEvent e) {  
  190.             if (e.getDocument().getLength() <= 0) {  
  191.                 button.setEnabled(false);  
  192.                 alreadyEnabled = false;  
  193.                 return true;  
  194.             }  
  195.             return false;  
  196.         }  
  197.     }  
  198. /** 
  199.  *方法说明:实现ListSelectionListener接口,必需实现的方法: 
  200.  */  
  201.     public void valueChanged(ListSelectionEvent e) {  
  202.         if (e.getValueIsAdjusting() == false) {  
  203.   
  204.             if (list.getSelectedIndex() == -1) {  
  205.                 fireButton.setEnabled(false);  
  206.   
  207.             } else {  
  208.                 fireButton.setEnabled(true);  
  209.             }  
  210.         }  
  211.     }  
  212. /** 
  213.  *方法说明:主方法 
  214.  */  
  215.     public static void main(String[] args) {  
  216.   
  217.         JFrame.setDefaultLookAndFeelDecorated(true);  
  218.   
  219.         //创建一个窗体  
  220.         JFrame frame = new JFrame("ListDemo");  
  221.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  222.   
  223.         //创建一个面版  
  224.         JComponent newContentPane = new ListDemo();  
  225.         newContentPane.setOpaque(true);  
  226.         frame.setContentPane(newContentPane);  
  227.   
  228.         //显示窗体  
  229.         frame.pack();  
  230.         frame.setVisible(true);  
  231.     }  
  232. }  

[java]  view plain copy
  1. package test15;  
  2.   
  3. import javax.swing.JTabbedPane;  
  4. import javax.swing.ImageIcon;  
  5. import javax.swing.JLabel;  
  6. import javax.swing.JPanel;  
  7. import javax.swing.JFrame;  
  8. /** 
  9.  * Title: 选项卡演示 
  10.  * Description: 这里是一个选项卡演示,点击不同的卡片,显示的内容不同 
  11.  * Filename: TabbedPaneDemo.java 
  12.  */  
  13. import java.awt.*;  
  14.   
  15. public class TabbedPaneDemo extends JPanel {  
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     public TabbedPaneDemo() {  
  22.         super(new GridLayout(11));  
  23.   
  24.         ImageIcon icon = createImageIcon("images/middle.gif");  
  25.         JTabbedPane tabbedPane = new JTabbedPane();  
  26.   
  27.         Component panel1 = makeTextPanel("#第一个卡片#");  
  28.         tabbedPane.addTab("One", icon, panel1,  
  29.                           "第一个卡片提示信息!");  
  30.         tabbedPane.setSelectedIndex(0);  
  31.   
  32.         Component panel2 = makeTextPanel("##第二个卡片##");  
  33.         tabbedPane.addTab("Two", icon, panel2,  
  34.                           "第二个卡片提示信息!");  
  35.   
  36.         Component panel3 = makeTextPanel("###第三个卡片###");  
  37.         tabbedPane.addTab("Three", icon, panel3,  
  38.                           "第三个卡片提示信息!");  
  39.   
  40.         Component panel4 = makeTextPanel("####第四个卡片####");  
  41.         tabbedPane.addTab("Four", icon, panel4,  
  42.                           "第四个卡片提示信息!");  
  43.   
  44.         //将选项卡添加到panl中  
  45.         add(tabbedPane);  
  46.     }  
  47. /** 
  48.  *方法说明:添加信息到选项卡中 
  49.  *输入参数:String text 显示的信息内容 
  50.  *返回类型:Component 成员对象 
  51.  */  
  52.     protected Component makeTextPanel(String text) {  
  53.         JPanel panel = new JPanel(false);  
  54.         JLabel filler = new JLabel(text);  
  55.         filler.setHorizontalAlignment(JLabel.CENTER);  
  56.         panel.setLayout(new GridLayout(11));  
  57.         panel.add(filler);  
  58.         return panel;  
  59.     }  
  60. /** 
  61.  *方法说明:获得图片 
  62.  *输入参数:String path 图片的路径 
  63.  *返回类型:ImageIcon 图片对象 
  64.  */  
  65.     protected static ImageIcon createImageIcon(String path) {  
  66.         java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);  
  67.         if (imgURL != null) {  
  68.             return new ImageIcon(imgURL);  
  69.         } else {  
  70.             System.err.println("Couldn't find file: " + path);  
  71.             return null;  
  72.         }  
  73.     }  
  74.   
  75.     public static void main(String[] args) {  
  76.         //使用Swing窗体描述  
  77.         JFrame.setDefaultLookAndFeelDecorated(true);  
  78.   
  79.         //创建窗体  
  80.         JFrame frame = new JFrame("TabbedPaneDemo");  
  81.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  82.         frame.getContentPane().add(new TabbedPaneDemo(),  
  83.                                  BorderLayout.CENTER);  
  84.   
  85.         //显示窗体  
  86.         frame.setSize(400200);  
  87.         frame.setVisible(true);  
  88.     }  
  89. }  

[java]  view plain copy
  1. package test16;  
  2.   
  3. import javax.swing.JOptionPane;  
  4. import javax.swing.JDialog;  
  5. import javax.swing.JTextField;  
  6. import java.beans.*; //property change stuff  
  7. import java.awt.*;  
  8. import java.awt.event.*;  
  9. /** 
  10.  * Title: 用户自定义对话框 
  11.  * Description: 自己定义对话框的风格。这使得对话框的样式更加多样化 
  12.  * Filename: CustomDialog.java 
  13.  */  
  14. class CustomDialog extends JDialog  
  15.                    implements ActionListener,  
  16.                               PropertyChangeListener {  
  17.   
  18.     private static final long serialVersionUID = 1L;  
  19.     private String typedText = null;  
  20.     private JTextField textField;  
  21.     private DialogDemo dd;  
  22.   
  23.     private String magicWord;  
  24.     private JOptionPane optionPane;  
  25.   
  26.     private String btnString1 = "确定";  
  27.     private String btnString2 = "取消";  
  28. /** 
  29.  *方法说明:返回文本输入字符 
  30.  */  
  31.     public String getValidatedText() {  
  32.         return typedText;  
  33.     }  
  34. /** 
  35.  *方法说明:创建一个结果对话框 
  36.  */  
  37.     public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {  
  38.         super(aFrame, true);  
  39.         dd = parent;  
  40.           
  41.         magicWord = aWord.toUpperCase();  
  42.         setTitle("测试");  
  43.   
  44.         textField = new JTextField(10);  
  45.   
  46.         //定义显示信息  
  47.         String msgString1 = "李先生: jeck是你的英文名字吗?";  
  48.         String msgString2 = "(这个答案是: \"" + magicWord  
  49.                               + "\"。)";  
  50.         Object[] array = {msgString1, msgString2, textField};  
  51.   
  52.   
  53.         Object[] options = {btnString1, btnString2};  
  54.   
  55.         //创建对话框  
  56.         optionPane = new JOptionPane(array,  
  57.                                     JOptionPane.QUESTION_MESSAGE,  
  58.                                     JOptionPane.YES_NO_OPTION,  
  59.                                     null,  
  60.                                     options,  
  61.                                     options[0]);  
  62.   
  63.         //显示对话框  
  64.         setContentPane(optionPane);  
  65.   
  66.         //设置当关闭窗体动作模式  
  67.         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);  
  68.         addWindowListener(new WindowAdapter() {  
  69.                 public void windowClosing(WindowEvent we) {  
  70.                   
  71.                     optionPane.setValue(new Integer(  
  72.                                         JOptionPane.CLOSED_OPTION));  
  73.             }  
  74.         });  
  75.   
  76.         //使的文本输入域得到焦点  
  77.         addComponentListener(new ComponentAdapter() {  
  78.             public void componentShown(ComponentEvent ce) {  
  79.                 textField.requestFocusInWindow();  
  80.             }  
  81.         });  
  82.   
  83.         //给文本域添加监听事件  
  84.         textField.addActionListener(this);  
  85.   
  86.         //监听输入改变  
  87.         optionPane.addPropertyChangeListener(this);  
  88.     }  
  89.   
  90.     /** 文本域监听处理 */  
  91.     public void actionPerformed(ActionEvent e) {  
  92.         optionPane.setValue(btnString1);  
  93.     }  
  94.   
  95.     /** 监听输入的改变 */  
  96.     public void propertyChange(PropertyChangeEvent e) {  
  97.         String prop = e.getPropertyName();  
  98.   
  99.         if (isVisible()  
  100.          && (e.getSource() == optionPane)  
  101.          && (JOptionPane.VALUE_PROPERTY.equals(prop) ||  
  102.              JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {  
  103.             Object value = optionPane.getValue();  
  104.   
  105.             if (value == JOptionPane.UNINITIALIZED_VALUE) {  
  106.                  return;  
  107.             }  
  108.   
  109.             optionPane.setValue(  
  110.                     JOptionPane.UNINITIALIZED_VALUE);  
  111.   
  112.             if (btnString1.equals(value)) {  
  113.                     typedText = textField.getText();  
  114.                 String ucText = typedText.toUpperCase();  
  115.                 if (magicWord.equals(ucText)) {  
  116.                     //如果输入有效,则清楚文本域并隐藏对话框  
  117.                     clearAndHide();  
  118.                 } else {  
  119.                     //文本输入无效  
  120.                     textField.selectAll();  
  121.                     JOptionPane.showMessageDialog(  
  122.                                     CustomDialog.this,  
  123.                                     "对不起, \"" + typedText + "\" "  
  124.                                     + "是无效的输入。\n"  
  125.                                     + "请重新输入"  
  126.                                     + magicWord + ".",  
  127.                                     "再试一次",  
  128.                                     JOptionPane.ERROR_MESSAGE);  
  129.                     typedText = null;  
  130.                     textField.requestFocusInWindow();  
  131.                 }  
  132.             } else { //用户关闭了对话框或点击了“cancel”  
  133.                 dd.setLabel("好吧! "  
  134.                          + "我们不能影响你的决定输入"  
  135.                          + magicWord + "。");  
  136.                 typedText = null;  
  137.                 clearAndHide();  
  138.             }  
  139.         }  
  140.     }  
  141. /** 
  142.  *方法说明:清楚文本域并隐藏痘翱蝌 
  143.  
  144.  */  
  145.     public void clearAndHide() {  
  146.         textField.setText(null);  
  147.         setVisible(false);  
  148.     }  
  149. }  

[java]  view plain copy
  1. package test16;  
  2.   
  3. import javax.swing.JOptionPane;  
  4. import javax.swing.JDialog;  
  5. import javax.swing.JButton;  
  6. import javax.swing.JRadioButton;  
  7. import javax.swing.ButtonGroup;  
  8. import javax.swing.JLabel;  
  9. import javax.swing.ImageIcon;  
  10. import javax.swing.BoxLayout;  
  11. import javax.swing.Box;  
  12. import javax.swing.BorderFactory;  
  13. import javax.swing.border.Border;  
  14. import javax.swing.JTabbedPane;  
  15. import javax.swing.JPanel;  
  16. import javax.swing.JFrame;  
  17. import java.beans.*;   
  18. import java.awt.*;  
  19. import java.awt.event.*;  
  20.   
  21. /** 
  22.  *Title: 对话框演示 
  23.  *Description: 全面的演示各种类型的对话框的使用 
  24.  *Filename: DialogDemo.java 
  25.  */  
  26. public class DialogDemo extends JPanel {  
  27.   
  28.     private static final long serialVersionUID = 1L;  
  29.     JLabel label;  
  30.     ImageIcon icon = createImageIcon("images/middle.gif");  
  31.     JFrame frame;  
  32.     String simpleDialogDesc = "简单的信息提示对话窗";  
  33.     String iconDesc = "带有图标的对话窗";  
  34.     String moreDialogDesc = "复杂信息对话窗";  
  35.     CustomDialog customDialog;  
  36. /** 
  37.  *方法说明:构造器,生成一个面板添加到JFrame中 
  38.  *输入参数: 
  39.  *返回类型: 
  40.  */  
  41.     public DialogDemo(JFrame frame) {  
  42.         super(new BorderLayout());  
  43.         this.frame = frame;  
  44.         customDialog = new CustomDialog(frame, "tom"this);  
  45.         customDialog.pack();  
  46.   
  47.         //创建成员  
  48.         JPanel frequentPanel = createSimpleDialogBox();  
  49.         JPanel featurePanel = createFeatureDialogBox();  
  50.         JPanel iconPanel = createIconDialogBox();  
  51.         label = new JLabel("点击\"显示\" 按钮"  
  52.                            + " 显示一个选择的对话框",  
  53.                            JLabel.CENTER);  
  54.   
  55.         //放置对象  
  56.         Border padding = BorderFactory.createEmptyBorder(20,20,5,20);  
  57.         frequentPanel.setBorder(padding);  
  58.         featurePanel.setBorder(padding);  
  59.         iconPanel.setBorder(padding);  
  60.         //创建选项卡  
  61.         JTabbedPane tabbedPane = new JTabbedPane();  
  62.         tabbedPane.addTab("简单对话窗"null,  
  63.                           frequentPanel,  
  64.                           simpleDialogDesc);   
  65.         tabbedPane.addTab("复杂对话窗"null,  
  66.                           featurePanel,  
  67.                           moreDialogDesc);  
  68.         tabbedPane.addTab("图标对话窗"null,  
  69.                           iconPanel,  
  70.                           iconDesc);  
  71.   
  72.         add(tabbedPane, BorderLayout.CENTER);  
  73.         add(label, BorderLayout.PAGE_END);  
  74.         label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  75.     }  
  76. /** 
  77.  *方法说明:设置按钮上的文字 
  78.  *输入参数:String newText 添加的文字 
  79.  *返回类型: 
  80.  */  
  81.     void setLabel(String newText) {  
  82.         label.setText(newText);  
  83.     }  
  84. /** 
  85.  *方法说明:获取图片 
  86.  *输入参数:String path 图片完整路径和名字 
  87.  *返回类型:ImageIcon 图片对象 
  88.  */  
  89.     protected static ImageIcon createImageIcon(String path) {  
  90.         java.net.URL imgURL = DialogDemo.class.getResource(path);  
  91.         if (imgURL != null) {  
  92.             return new ImageIcon(imgURL);  
  93.         } else {  
  94.             System.err.println("Couldn't find file: " + path);  
  95.             return null;  
  96.         }  
  97.     }  
  98. /** 
  99.  *方法说明:创建一个JPanel,给第一个选项卡 
  100.  *输入参数: 
  101.  *返回类型: 
  102.  */  
  103.     private JPanel createSimpleDialogBox() {  
  104.         final int numButtons = 4;  
  105.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  106.         final ButtonGroup group = new ButtonGroup();  
  107.   
  108.         JButton showItButton = null;  
  109.   
  110.         final String defaultMessageCommand = "default";  
  111.         final String yesNoCommand = "yesno";  
  112.         final String yeahNahCommand = "yeahnah";  
  113.         final String yncCommand = "ync";  
  114.         //添加单选到数字  
  115.         radioButtons[0] = new JRadioButton("只有“OK”按钮");  
  116.         radioButtons[0].setActionCommand(defaultMessageCommand);  
  117.   
  118.         radioButtons[1] = new JRadioButton("有“Yes/No”二个按钮");  
  119.         radioButtons[1].setActionCommand(yesNoCommand);  
  120.   
  121.         radioButtons[2] = new JRadioButton("有“Yes/No”两个按钮 "  
  122.                       + "(程序添加文字)");  
  123.         radioButtons[2].setActionCommand(yeahNahCommand);  
  124.   
  125.         radioButtons[3] = new JRadioButton("有“Yes/No/Cancel”三个按钮 "  
  126.                            + "(程序添加文字)");  
  127.         radioButtons[3].setActionCommand(yncCommand);  
  128.         //将四个单选组成一个群  
  129.         for (int i = 0; i < numButtons; i++) {  
  130.             group.add(radioButtons[i]);  
  131.         }  
  132.         //设置第一个为默认选择  
  133.         radioButtons[0].setSelected(true);  
  134.         //定义“显示”按钮  
  135.         showItButton = new JButton("显示");  
  136.         //给“显示”按钮添加监听  
  137.         showItButton.addActionListener(new ActionListener() {  
  138.             public void actionPerformed(ActionEvent e) {  
  139.                 String command = group.getSelection().getActionCommand();  
  140.   
  141.                 //ok对话窗  
  142.                 if (command == defaultMessageCommand) {  
  143.                     JOptionPane.showMessageDialog(frame,  
  144.                                 "鸡蛋不可能是绿色的!");  
  145.   
  146.                 //yes/no 对话窗  
  147.                 } else if (command == yesNoCommand) {  
  148.                     int n = JOptionPane.showConfirmDialog(  
  149.                             frame, "你喜欢吃酸菜鱼吗?",  
  150.                             "一个很无聊的问题!!",  
  151.                             JOptionPane.YES_NO_OPTION);  
  152.                     if (n == JOptionPane.YES_OPTION) {//选择yes  
  153.                         setLabel("哇!我也是!");  
  154.                     } else if (n == JOptionPane.NO_OPTION) {//选择no  
  155.                         setLabel("唉!我喜欢吃!");  
  156.                     } else {  
  157.                         setLabel("快告诉我吧!");  
  158.                     }  
  159.   
  160.                 //yes/no (自己输入选项)  
  161.                 } else if (command == yeahNahCommand) {  
  162.                     Object[] options = {"是的""不喜欢"};  
  163.                     int n = JOptionPane.showOptionDialog(frame,  
  164.                                     "你喜欢酸菜鱼吗?",  
  165.                                     "又一个无聊的问题!",  
  166.                                     JOptionPane.YES_NO_OPTION,  
  167.                                     JOptionPane.QUESTION_MESSAGE,  
  168.                                     null,  
  169.                                     options,  
  170.                                     options[0]);  
  171.                     if (n == JOptionPane.YES_OPTION) {  
  172.                         setLabel("你哄人的吧,我也喜欢。");  
  173.                     } else if (n == JOptionPane.NO_OPTION) {  
  174.                         setLabel("其实我也不喜欢!");  
  175.                     } else {  
  176.                         setLabel("这都不肯告诉我,小气鬼!");  
  177.                     }  
  178.   
  179.                 //yes/no/cancel 对话框  
  180.                 } else if (command == yncCommand) {  
  181.                     Object[] options = {"是的,给我来一份。",  
  182.                                         "不,谢谢!",  
  183.                                         "不,我要水煮鱼!"};  
  184.                     //构造对话框  
  185.                     int n = JOptionPane.showOptionDialog(frame,  
  186.                                     "先生!我们这里有鲜美的酸菜鱼,您需要吗?",  
  187.                                     "服务生的问题。",  
  188.                                     JOptionPane.YES_NO_CANCEL_OPTION,  
  189.                                     JOptionPane.QUESTION_MESSAGE,  
  190.                                     null,  
  191.                                     options,  
  192.                                     options[2]);  
  193.                     if (n == JOptionPane.YES_OPTION) {  
  194.                         setLabel("你要的酸菜鱼来了!");  
  195.                     } else if (n == JOptionPane.NO_OPTION) {  
  196.                         setLabel("好的,你需要其它的。");  
  197.                     } else if (n == JOptionPane.CANCEL_OPTION) {  
  198.                         setLabel("好的,我们给你做水煮鱼!");  
  199.                     } else {  
  200.                         setLabel("对不起!你还没有点菜呢!");  
  201.                     }  
  202.                 }  
  203.                 return;  
  204.             }  
  205.         });  
  206.   
  207.         return createPane(simpleDialogDesc + ":",  
  208.                           radioButtons,  
  209.                           showItButton);  
  210.     }  
  211. /** 
  212.  *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法 
  213.  *方法说明:创建带提示信息、一列单选框和“显示”按钮 
  214.  *输入参数:String description 提示帮助信息 
  215.  *输入参数:JRadioButton[] radioButtons 单选框组 
  216.  *输入参数:JButton showButton “显示”按钮 
  217.  *返回类型:JPanel 添加好的面板 
  218.  */  
  219.     private JPanel createPane(String description,  
  220.                               JRadioButton[] radioButtons,  
  221.                               JButton showButton) {  
  222.   
  223.         int numChoices = radioButtons.length;  
  224.         JPanel box = new JPanel();  
  225.         JLabel label = new JLabel(description);  
  226.   
  227.         box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));  
  228.         box.add(label);  
  229.         //添加radio  
  230.         for (int i = 0; i < numChoices; i++) {  
  231.             box.add(radioButtons[i]);  
  232.         }  
  233.   
  234.         JPanel pane = new JPanel(new BorderLayout());  
  235.         pane.add(box, BorderLayout.PAGE_START);  
  236.         pane.add(showButton, BorderLayout.PAGE_END);  
  237.         return pane;  
  238.     }  
  239. /** 
  240.  *方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法 
  241.  *方法说明:创建带提示信息、二列单选框和“显示”按钮 
  242.  *输入参数:String description 提示帮助信息 
  243.  *输入参数:JRadioButton[] radioButtons 单选框组 
  244.  *输入参数:JButton showButton “显示”按钮 
  245.  *返回类型:JPanel 添加好的面板 
  246.  */  
  247.      private JPanel create2ColPane(String description,  
  248.                                   JRadioButton[] radioButtons,  
  249.                                   JButton showButton) {  
  250.         JLabel label = new JLabel(description);  
  251.         int numPerColumn = radioButtons.length/2;  
  252.   
  253.         JPanel grid = new JPanel(new GridLayout(02));  
  254.         for (int i = 0; i < numPerColumn; i++) {  
  255.             grid.add(radioButtons[i]);  
  256.             grid.add(radioButtons[i + numPerColumn]);  
  257.         }  
  258.   
  259.         JPanel box = new JPanel();  
  260.         box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));  
  261.         box.add(label);  
  262.         grid.setAlignmentX(0.0f);  
  263.         box.add(grid);  
  264.   
  265.         JPanel pane = new JPanel(new BorderLayout());  
  266.         pane.add(box, BorderLayout.PAGE_START);  
  267.         pane.add(showButton, BorderLayout.PAGE_END);  
  268.   
  269.         return pane;  
  270.     }  
  271. /** 
  272.  *方法说明:创建第三个选项卡的面板 
  273.  *方法说明:这里都是实现showMessageDialog类,但是也可以指定图标 
  274.  *输入参数: 
  275.  *返回类型:JPanel 构造好的面板 
  276.  */  
  277.   
  278.     private JPanel createIconDialogBox() {  
  279.         JButton showItButton = null;  
  280.   
  281.         final int numButtons = 6;  
  282.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  283.         final ButtonGroup group = new ButtonGroup();  
  284.   
  285.         final String plainCommand = "plain";  
  286.         final String infoCommand = "info";  
  287.         final String questionCommand = "question";  
  288.         final String errorCommand = "error";  
  289.         final String warningCommand = "warning";  
  290.         final String customCommand = "custom";  
  291.   
  292.         radioButtons[0] = new JRadioButton("普通(没有图标)");  
  293.         radioButtons[0].setActionCommand(plainCommand);  
  294.   
  295.         radioButtons[1] = new JRadioButton("信息图标");  
  296.         radioButtons[1].setActionCommand(infoCommand);  
  297.   
  298.         radioButtons[2] = new JRadioButton("问题图标");  
  299.         radioButtons[2].setActionCommand(questionCommand);  
  300.   
  301.         radioButtons[3] = new JRadioButton("错误图标");  
  302.         radioButtons[3].setActionCommand(errorCommand);  
  303.   
  304.         radioButtons[4] = new JRadioButton("警告图标");  
  305.         radioButtons[4].setActionCommand(warningCommand);  
  306.   
  307.         radioButtons[5] = new JRadioButton("自定义图标");  
  308.         radioButtons[5].setActionCommand(customCommand);  
  309.   
  310.         for (int i = 0; i < numButtons; i++) {  
  311.             group.add(radioButtons[i]);  
  312.         }  
  313.         radioButtons[0].setSelected(true);  
  314.   
  315.         showItButton = new JButton("显示");  
  316.         showItButton.addActionListener(new ActionListener() {  
  317.             public void actionPerformed(ActionEvent e) {  
  318.                 String command = group.getSelection().getActionCommand();  
  319.   
  320.                 //没有图标  
  321.                 if (command == plainCommand) {  
  322.                     JOptionPane.showMessageDialog(frame,  
  323.                                     "水煮鱼里不要放酸菜!",  
  324.                                     "无图标",  
  325.                                     JOptionPane.PLAIN_MESSAGE);  
  326.                 //信息图标  
  327.                 } else if (command == infoCommand) {  
  328.                     JOptionPane.showMessageDialog(frame,  
  329.                                     "水煮鱼里不要放酸菜!",  
  330.                                     "信息图标",  
  331.                                     JOptionPane.INFORMATION_MESSAGE);  
  332.   
  333.                 //问题图标  
  334.                 } else if (command == questionCommand) {  
  335.                     JOptionPane.showMessageDialog(frame,  
  336.                                     "请你吃饭前洗手,好吗?",  
  337.                                     "问题",  
  338.                                     JOptionPane.QUESTION_MESSAGE);  
  339.                 //错误图标  
  340.                 } else if (command == errorCommand) {  
  341.                     JOptionPane.showMessageDialog(frame,  
  342.                                     "对不起,你的信用卡没有资金了!",  
  343.                                     "错误信息",  
  344.                                     JOptionPane.ERROR_MESSAGE);  
  345.                 //警告图标  
  346.                 } else if (command == warningCommand) {  
  347.                     JOptionPane.showMessageDialog(frame,  
  348.                                     "警告!你严重透支信用卡,请尽快补齐金额!",  
  349.                                     "警告信息",  
  350.                                     JOptionPane.WARNING_MESSAGE);  
  351.                 //自定义图标  
  352.                 } else if (command == customCommand) {  
  353.                     JOptionPane.showMessageDialog(frame,  
  354.                                     "哈哈。我想用什么图标都可以!",  
  355.                                     "自定义对话窗",  
  356.                                     JOptionPane.INFORMATION_MESSAGE,  
  357.                                     icon);  
  358.                 }  
  359.             }  
  360.         });  
  361.   
  362.         return create2ColPane(iconDesc + ":",  
  363.                               radioButtons,  
  364.                               showItButton);  
  365.     }  
  366. /** 
  367.  *方法说明:创建一个JPanel,放在第二个选项卡上 
  368.  *输入参数: 
  369.  *返回类型: 
  370.  */  
  371.     private JPanel createFeatureDialogBox() {  
  372.         final int numButtons = 5;  
  373.         JRadioButton[] radioButtons = new JRadioButton[numButtons];  
  374.         final ButtonGroup group = new ButtonGroup();  
  375.   
  376.         JButton showItButton = null;  
  377.         //定义操作命令  
  378.         final String pickOneCommand = "pickone";  
  379.         final String textEnteredCommand = "textfield";  
  380.         final String nonAutoCommand = "nonautooption";  
  381.         final String customOptionCommand = "customoption";  
  382.         final String nonModalCommand = "nonmodal";  
  383.         //定义radio数组  
  384.         radioButtons[0] = new JRadioButton("选择一个");  
  385.         radioButtons[0].setActionCommand(pickOneCommand);  
  386.   
  387.         radioButtons[1] = new JRadioButton("输入信息");  
  388.         radioButtons[1].setActionCommand(textEnteredCommand);  
  389.   
  390.         radioButtons[2] = new JRadioButton("关闭按钮无效");  
  391.         radioButtons[2].setActionCommand(nonAutoCommand);  
  392.   
  393.         radioButtons[3] = new JRadioButton("输入校验"  
  394.                                            + "(用户输入信息)");  
  395.         radioButtons[3].setActionCommand(customOptionCommand);  
  396.   
  397.         radioButtons[4] = new JRadioButton("没有模式");  
  398.         radioButtons[4].setActionCommand(nonModalCommand);  
  399.         //合成一个组群  
  400.         for (int i = 0; i < numButtons; i++) {  
  401.             group.add(radioButtons[i]);  
  402.         }  
  403.         //设置第一个为默认选择  
  404.         radioButtons[0].setSelected(true);  
  405.   
  406.         showItButton = new JButton("显示");  
  407.         showItButton.addActionListener(new ActionListener() {  
  408.             @SuppressWarnings("static-access")  
  409.             public void actionPerformed(ActionEvent e) {  
  410.                 String command = group.getSelection().getActionCommand();  
  411.   
  412.                 //选择一个  
  413.                 if (command == pickOneCommand) {  
  414.                     Object[] possibilities = {"辣椒""西红柿""洋葱"};  
  415.                     //设置对话框  
  416.                     String s = (String)JOptionPane.showInputDialog(  
  417.                                         frame,    //所属窗体  
  418.                                         "请选择项目:\n"  
  419.                                         + "\"鸡蛋炒\"",  //输出信息  
  420.                                         "客户选择",  
  421.                                         JOptionPane.PLAIN_MESSAGE,  //对话框模式  
  422.                                         icon,           //显示图标  
  423.                                         possibilities,   //选项内容  
  424.                                         "辣椒");    //默认选项  
  425.   
  426.                     //如果有选择  
  427.                     if ((s != null) && (s.length() > 0)) {  
  428.                         setLabel("鸡蛋炒" + s + "!");  
  429.                         return;  
  430.                     }  
  431.   
  432.                     //如果客户没有选择  
  433.                     setLabel("快点!");  
  434.   
  435.                 //文本输入  
  436.                 } else if (command == textEnteredCommand) {  
  437.                     String s = (String)JOptionPane.showInputDialog(  
  438.                                         frame,  
  439.                                         "选择一个配料\n"  
  440.                                         + "\"鸡蛋炒\"",  
  441.                                         "客户输入",  
  442.                                         JOptionPane.PLAIN_MESSAGE,  
  443.                                         icon,  
  444.                                         null,  
  445.                                         "辣椒");  
  446.   
  447.                     //如果用户有输入  
  448.                     if ((s != null) && (s.length() > 0)) {  
  449.                         setLabel("你要的是鸡蛋炒" + s + "!");  
  450.                         return;  
  451.                     }  
  452.   
  453.                     //如果返回的是空或者是null。  
  454.                     setLabel("快些选择!");  
  455.   
  456.                 //关闭按钮无效  
  457.                 } else if (command == nonAutoCommand) {  
  458.                     //构造一个对话框面板  
  459.                     final JOptionPane optionPane = new JOptionPane(  
  460.                                     "关闭这个对话框\n"  
  461.                                     + "请点击下面的按钮\n"  
  462.                                     + "明白吗?",  
  463.                                     JOptionPane.QUESTION_MESSAGE,  
  464.                                     JOptionPane.YES_NO_OPTION);  
  465.   
  466.                     JDialog.setDefaultLookAndFeelDecorated(false);  
  467.                     //构造一个对话框  
  468.                     final JDialog dialog = new JDialog(frame,  
  469.                                                  "点击一个按钮",  
  470.                                                  true);  
  471.                     //将对话框面板添加到对话框中  
  472.                     dialog.setContentPane(optionPane);  
  473.                     //设置对话框关闭时的操作模式  
  474.                     dialog.setDefaultCloseOperation(  
  475.                         JDialog.DO_NOTHING_ON_CLOSE);  
  476.                     dialog.addWindowListener(new WindowAdapter() {  
  477.                         public void windowClosing(WindowEvent we) { //当点击关闭按钮  
  478.                             setLabel("阻碍用户视图关闭窗体!");  
  479.                         }  
  480.                     });  
  481.                       
  482.                     JDialog.setDefaultLookAndFeelDecorated(true);  
  483.                       
  484.                     optionPane.addPropertyChangeListener(  
  485.                         new PropertyChangeListener() {  
  486.                             public void propertyChange(PropertyChangeEvent e) {  
  487.                                 String prop = e.getPropertyName();  
  488.   
  489.                                 if (dialog.isVisible()  
  490.                                  && (e.getSource() == optionPane)  
  491.                                  && (JOptionPane.VALUE_PROPERTY.equals(prop))) {  
  492.                                     //如果你要阻止关闭按钮,可以在这里进行处理。  
  493.                                       
  494.                                     dialog.setVisible(false);  
  495.                                 }  
  496.                             }  
  497.                         });  
  498.                     dialog.pack();  
  499.                     dialog.setLocationRelativeTo(frame);  
  500.                     dialog.setVisible(true);  
  501.                       
  502.                     int value = ((Integer)optionPane.getValue()).intValue();  
  503.                     if (value == JOptionPane.YES_OPTION) {  
  504.                         setLabel("好的");  
  505.                     } else if (value == JOptionPane.NO_OPTION) {  
  506.                         setLabel("试图点击关闭按钮来关闭一个不能关闭的对话框!"  
  507.                                  + "你不能!");  
  508.                     } else {  
  509.                         setLabel("窗体可以使用ESC键关闭。");  
  510.                     }  
  511.   
  512.                  //自己定义版面  
  513.                 } else if (command == customOptionCommand) {  
  514.                     customDialog.setLocationRelativeTo(frame);  
  515.                     customDialog.setVisible(true);  
  516.   
  517.                     String s = customDialog.getValidatedText();  
  518.                     if (s != null) {  
  519.                         //The text is valid.  
  520.                         setLabel("欢迎你!"  
  521.                                  + "你已经进入了\""  
  522.                                  + s  
  523.                                  + "\"。");  
  524.                     }  
  525.   
  526.                 //没有模式  
  527.                 } else if (command == nonModalCommand) {  
  528.                     //创建一个对话框  
  529.                     final JDialog dialog = new JDialog(frame,  
  530.                                                        "一个没有模式的对话框");  
  531.                     //使用html语言来显示信息  
  532.                     JLabel label = new JLabel("<html><p align=center>"  
  533.                         + "这是一个没有模式的对话框"  
  534.                         + "你可以使用更多的格式"  
  535.                         + "甚至可以使用主窗体!");  
  536.                     label.setHorizontalAlignment(JLabel.CENTER);  
  537.                     Font font = label.getFont();  
  538.                       
  539.                     label.setFont(label.getFont().deriveFont(font.PLAIN,  
  540.                                                              14.0f));  
  541.   
  542.                     JButton closeButton = new JButton("关闭");  
  543.                     closeButton.addActionListener(new ActionListener() {  
  544.                         public void actionPerformed(ActionEvent e) {  
  545.                             dialog.setVisible(false);  
  546.                             dialog.dispose();  
  547.                         }  
  548.                     });  
  549.                     JPanel closePanel = new JPanel();  
  550.                     closePanel.setLayout(new BoxLayout(closePanel,  
  551.                                                        BoxLayout.LINE_AXIS));  
  552.                     closePanel.add(Box.createHorizontalGlue());  
  553.                     closePanel.add(closeButton);  
  554.                     closePanel.setBorder(BorderFactory.  
  555.                         createEmptyBorder(0,0,5,5));  
  556.   
  557.                     JPanel contentPane = new JPanel(new BorderLayout());  
  558.                     contentPane.add(label, BorderLayout.CENTER);  
  559.                     contentPane.add(closePanel, BorderLayout.PAGE_END);  
  560.                     contentPane.setOpaque(true);  
  561.                     dialog.setContentPane(contentPane);  
  562.   
  563.                     //显示窗体  
  564.                     dialog.setSize(new Dimension(300150));  
  565.                     dialog.setLocationRelativeTo(frame);  
  566.                     dialog.setVisible(true);  
  567.                 }  
  568.             }  
  569.         });  
  570.   
  571.         return createPane(moreDialogDesc + ":",  
  572.                           radioButtons,  
  573.                           showItButton);  
  574.     }  
  575.   
  576.     public static void main(String[] args) {  
  577.   
  578.         JFrame.setDefaultLookAndFeelDecorated(true);  
  579.         JDialog.setDefaultLookAndFeelDecorated(true);  
  580.   
  581.         //创建和设置一个窗体  
  582.         JFrame frame = new JFrame("DialogDemo");  
  583.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  584.   
  585.         //设置一个面板  
  586.         Container contentPane = frame.getContentPane();  
  587.         contentPane.setLayout(new GridLayout(1,1));  
  588.         contentPane.add(new DialogDemo(frame));  
  589.   
  590.         //显示窗体  
  591.         frame.pack();  
  592.         frame.setVisible(true);  
  593.     }  
  594. }  

[java]  view plain copy
  1. package test17;  
  2.   
  3. import java.io.*;  
  4. import java.awt.*;  
  5. import java.awt.event.*;  
  6. import javax.swing.*;  
  7. /** 
  8.  * Title: 文件对话框演示 
  9.  * Description: 演示打开文件对话框和保存文件对话框,使用了文件过滤。 
  10.  * Filename: FileChooserDemo.java 
  11.  */  
  12.   
  13. public class FileChooserDemo extends JPanel  
  14.                              implements ActionListener {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.     static private final String newline = "\n";  
  18.     JButton openButton, saveButton;  
  19.     JTextArea log;  
  20.     JFileChooser fc;  
  21.   
  22.     public FileChooserDemo() {  
  23.         super(new BorderLayout());  
  24.   
  25.         log = new JTextArea(15,40);  
  26.         log.setMargin(new Insets(10,10,10,10));  
  27.         log.setEditable(false);  
  28.         JScrollPane logScrollPane = new JScrollPane(log);  
  29.   
  30.         //创建一个文件过滤,使用当前目录  
  31.         fc = new JFileChooser(".");  
  32.         //过滤条件在MyFilter类中定义  
  33.         fc.addChoosableFileFilter(new MyFilter());  
  34.   
  35.         openButton = new JButton("打开文件",  
  36.                                  createImageIcon("images/Open16.gif"));  
  37.         openButton.addActionListener(this);  
  38.   
  39.         saveButton = new JButton("保存文件",  
  40.                                  createImageIcon("images/Save16.gif"));  
  41.         saveButton.addActionListener(this);  
  42.   
  43.         //构建一个面板,添加“打开文件”和“保存文件”  
  44.         JPanel buttonPanel = new JPanel();   
  45.         buttonPanel.add(openButton);  
  46.         buttonPanel.add(saveButton);  
  47.   
  48.         add(buttonPanel, BorderLayout.PAGE_START);  
  49.         add(logScrollPane, BorderLayout.CENTER);  
  50.     }  
  51. /** 
  52.  *方法说明:事件处理 
  53.  *输入参数: 
  54.  *返回类型: 
  55.  */  
  56.     public void actionPerformed(ActionEvent e) {  
  57.   
  58.         //当点击“打开文件”按钮  
  59.         if (e.getSource() == openButton) {  
  60.             int returnVal = fc.showOpenDialog(FileChooserDemo.this);  
  61.   
  62.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  63.                 File file = fc.getSelectedFile();  
  64.                 //在这里添加一些对文件的处理  
  65.                 log.append("打开文件: " + file.getName() + newline);  
  66.             } else {  
  67.                 log.append("打开文件被用户取消!" + newline);  
  68.             }  
  69.   
  70.         //点击“保存文件”按钮  
  71.         } else if (e.getSource() == saveButton) {  
  72.             int returnVal = fc.showSaveDialog(FileChooserDemo.this);  
  73.             if (returnVal == JFileChooser.APPROVE_OPTION) {  
  74.                 File file = fc.getSelectedFile();  
  75.                 //在这里添加一些对文件的处理  
  76.                 log.append("保存文件: " + file.getName()  + newline);  
  77.             } else {  
  78.                 log.append("保存文件被用户取消!" + newline);  
  79.             }  
  80.         }  
  81.     }  
  82. /** 
  83.  *方法说明:获取图像对象 
  84.  *输入参数:String path 图片路径 
  85.  *返回类型:ImageIcon 图片对象 
  86.  */  
  87.     protected static ImageIcon createImageIcon(String path) {  
  88.         java.net.URL imgURL = FileChooserDemo.class.getResource(path);  
  89.         if (imgURL != null) {  
  90.             return new ImageIcon(imgURL);  
  91.         } else {  
  92.             System.err.println("Couldn't find file: " + path);  
  93.             return null;  
  94.         }  
  95.     }  
  96.   
  97.     public static void main(String[] args) {  
  98.         JFrame.setDefaultLookAndFeelDecorated(true);  
  99.         JDialog.setDefaultLookAndFeelDecorated(true);  
  100.   
  101.         //创建窗体  
  102.         JFrame frame = new JFrame("FileChooserDemo");  
  103.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  104.   
  105.         //创建一个面板  
  106.         JComponent newContentPane = new FileChooserDemo();  
  107.         newContentPane.setOpaque(true);  
  108.         frame.setContentPane(newContentPane);  
  109.   
  110.         //显示窗体  
  111.         frame.pack();  
  112.         frame.setVisible(true);  
  113.     }  
  114. }  

[java]  view plain copy
  1. package test17;  
  2.   
  3. import java.io.File;  
  4. import javax.swing.filechooser.*;  
  5. /** 
  6.  * Title: 文件过滤器演示 
  7.  * Description: FileChooserDemo文件使用的文件过滤器 
  8.  * Filename: MyFilter.java 
  9.  */  
  10.   
  11. public class MyFilter extends FileFilter {  
  12.    @SuppressWarnings("unused")  
  13. private String files;  
  14.    public boolean accept(File f) {  
  15.         if (f.isDirectory()) {  
  16.             return true;  
  17.         }  
  18.   
  19.         String extension = getExtension(f);  
  20.         if (extension != null) {  
  21.               
  22.             if (extension.equals("java")) {//定义过滤Java文件  
  23.                     return true;  
  24.             } else {  
  25.                 return false;  
  26.             }  
  27.   
  28.         }  
  29.   
  30.         return false;  
  31.     }  
  32.   
  33.     //过滤器描述  
  34.     public String getDescription() {  
  35.         return "Java";  
  36.     }  
  37. /** 
  38.  *方法说明:获取文件扩展名 
  39.  */  
  40.     public static String getExtension(File f) {  
  41.         String ext = null;  
  42.         String s = f.getName();  
  43.         int i = s.lastIndexOf('.');  
  44.   
  45.         if (i > 0 &&  i < s.length() - 1) {  
  46.             ext = s.substring(i+1).toLowerCase();  
  47.         }  
  48.         return ext;  
  49.     }  
  50. }  

[java]  view plain copy
  1. package test18;  
  2.   
  3. import javax.swing.*;  
  4. import java.awt.*;  
  5. import java.awt.event.*;  
  6. /** 
  7.  * Description: 这里演示使用html语言在swing面板上构造显示信息 
  8.  * Filename: HtmlDemo.java 
  9.  */  
  10.   
  11. public class HtmlDemo extends JPanel  
  12.                       implements ActionListener {  
  13.   
  14.     private static final long serialVersionUID = 1L;  
  15.     JLabel theLabel;  
  16.     JTextArea htmlTextArea;  
  17. /** 
  18.  *方法说明:构造器,描述窗体中的成员 
  19.  *输入参数: 
  20.  *返回类型: 
  21.  */  
  22.     public HtmlDemo() {  
  23.         setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));  
  24.   
  25.         String initialText = "<html>\n" +  
  26.                 "颜色和字体测试:\n" +  
  27.                 "<ul>\n" +  
  28.                 "<li><font color=red>red</font>\n" +  
  29.                 "<li><font color=blue>blue</font>\n" +  
  30.                 "<li><font color=green>green</font>\n" +  
  31.                 "<li><font size=-2>small</font>\n" +  
  32.                 "<li><font size=+2>large</font>\n" +  
  33.                 "<li><i>italic</i>\n" +  
  34.                 "<li><b>bold</b>\n" +  
  35.                 "</ul>\n";  
  36.         //定义一个文本框  
  37.         htmlTextArea = new JTextArea(1020);  
  38.         htmlTextArea.setText(initialText);  
  39.         JScrollPane scrollPane = new JScrollPane(htmlTextArea);  
  40.         //定义按钮  
  41.         JButton changeTheLabel = new JButton("改变显示");  
  42.         changeTheLabel.setMnemonic(KeyEvent.VK_C);  
  43.         changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);  
  44.         changeTheLabel.addActionListener(this);  
  45.         //定义标签  
  46.         theLabel = new JLabel(initialText) {  
  47.            
  48.             private static final long serialVersionUID = 1L;  
  49.             public Dimension getPreferredSize() {  
  50.                 return new Dimension(200200);  
  51.             }  
  52.             public Dimension getMinimumSize() {  
  53.                 return new Dimension(200200);  
  54.             }  
  55.             public Dimension getMaximumSize() {  
  56.                 return new Dimension(200200);  
  57.             }  
  58.         };  
  59.         //设置标签的对齐方式  
  60.         theLabel.setVerticalAlignment(SwingConstants.CENTER);  
  61.         theLabel.setHorizontalAlignment(SwingConstants.CENTER);  
  62.         //构造一个带边框的左边的编辑面板  
  63.         JPanel leftPanel = new JPanel();  
  64.         leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));  
  65.         leftPanel.setBorder(BorderFactory.createCompoundBorder(  
  66.                 BorderFactory.createTitledBorder(  
  67.                     "编辑HTML,点击按钮显示结果。"),  
  68.                 BorderFactory.createEmptyBorder(10,10,10,10)));  
  69.         leftPanel.add(scrollPane);  
  70.         leftPanel.add(Box.createRigidArea(new Dimension(0,10)));  
  71.         leftPanel.add(changeTheLabel);  
  72.          //构造一个带边框的右边显示的面板  
  73.         JPanel rightPanel = new JPanel();  
  74.         rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));  
  75.         rightPanel.setBorder(BorderFactory.createCompoundBorder(  
  76.                         BorderFactory.createTitledBorder("这里使用标签显示HTML结果"),  
  77.                         BorderFactory.createEmptyBorder(10,10,10,10)));  
  78.         rightPanel.add(theLabel);  
  79.           
  80.         setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  
  81.         add(leftPanel);  
  82.         add(Box.createRigidArea(new Dimension(10,0)));  
  83.         add(rightPanel);  
  84.     }  
  85. /** 
  86.  *方法说明:事件监听,当用户点击按钮触发 
  87.  *输入参数: 
  88.  *返回类型: 
  89.  */  
  90.     public void actionPerformed(ActionEvent e) {  
  91.         theLabel.setText(htmlTextArea.getText());  
  92.     }  
  93. /** 
  94.  *方法说明:主方法 
  95.  *输入参数: 
  96.  *返回类型: 
  97.  */  
  98.     public static void main(String[] args) {  
  99.   
  100.         JFrame.setDefaultLookAndFeelDecorated(true);  
  101.   
  102.         //创建窗体  
  103.         JFrame frame = new JFrame("HtmlDemo");  
  104.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  105.   
  106.         //创建面板  
  107.         JComponent newContentPane = new HtmlDemo();  
  108.         newContentPane.setOpaque(true);  
  109.         frame.setContentPane(newContentPane);  
  110.   
  111.         //显示窗体  
  112.         frame.pack();  
  113.         frame.setVisible(true);  
  114.     }  
  115. }  

[java]  view plain copy
  1. package test19;  
  2.   
  3. import java.awt.*;  
  4. import java.awt.event.*;  
  5. import javax.swing.JPopupMenu;  
  6. import javax.swing.JMenu;  
  7. import javax.swing.JMenuItem;  
  8. import javax.swing.JCheckBoxMenuItem;  
  9. import javax.swing.JRadioButtonMenuItem;  
  10. import javax.swing.ButtonGroup;  
  11. import javax.swing.JMenuBar;  
  12. import javax.swing.KeyStroke;  
  13. import javax.swing.ImageIcon;  
  14.   
  15. import javax.swing.JPanel;  
  16. import javax.swing.JTextArea;  
  17. import javax.swing.JScrollPane;  
  18. import javax.swing.JFrame;  
  19. /** 
  20.  * Title: 菜单演示 
  21.  * Description: 演示菜单的建立和快捷键的使用。 
  22.  * Filename: MenuDemo.java 
  23.  */  
  24.   
  25. public class MenuDemo implements ActionListener, ItemListener {  
  26.     JTextArea output;  
  27.     JScrollPane scrollPane;  
  28.     String newline = "\n";  
  29. /** 
  30.  *方法说明:组建菜单栏 
  31.  *输入参数: 
  32.  *返回类型: 
  33.  */  
  34.     public JMenuBar createMenuBar() {  
  35.         JMenuBar menuBar;  
  36.         JMenu menu, submenu;  
  37.         JMenuItem menuItem;  
  38.         JRadioButtonMenuItem rbMenuItem;  
  39.         JCheckBoxMenuItem cbMenuItem;  
  40.   
  41.         //定义菜单条  
  42.         menuBar = new JMenuBar();  
  43.   
  44.         //定义第一个菜单  
  45.         menu = new JMenu("(A)菜单");  
  46.         menu.setMnemonic(KeyEvent.VK_A);  
  47.         menuBar.add(menu);  
  48.   
  49.         //下面开始定义菜单项  
  50.           
  51.         //只有文字  
  52.         menuItem = new JMenuItem("(O)只有文本的菜单",  
  53.                                  KeyEvent.VK_O);  
  54.         //设置快捷键  
  55.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  56.                 KeyEvent.VK_1, ActionEvent.ALT_MASK));  
  57.         //添加监听  
  58.         menuItem.addActionListener(this);  
  59.         menu.add(menuItem);  
  60.         //有图标还有文字  
  61.         ImageIcon icon = createImageIcon("images/middle.gif");  
  62.         menuItem = new JMenuItem("(B)有图标和文字的菜单", icon);  
  63.         menuItem.setMnemonic(KeyEvent.VK_B);  
  64.         menuItem.addActionListener(this);  
  65.         menu.add(menuItem);  
  66.         //只有图标  
  67.         menuItem = new JMenuItem(icon);  
  68.         menuItem.setMnemonic(KeyEvent.VK_D);  
  69.         menuItem.addActionListener(this);  
  70.         menu.add(menuItem);  
  71.   
  72.         //定义一组radio button(单选按钮)菜单  
  73.         menu.addSeparator();  
  74.         ButtonGroup group = new ButtonGroup();  
  75.   
  76.         rbMenuItem = new JRadioButtonMenuItem("(R)使用radio的菜单");  
  77.         rbMenuItem.setSelected(true);  
  78.         rbMenuItem.setMnemonic(KeyEvent.VK_R);  
  79.         group.add(rbMenuItem);  
  80.         rbMenuItem.addActionListener(this);  
  81.         menu.add(rbMenuItem);  
  82.   
  83.         rbMenuItem = new JRadioButtonMenuItem("(d)另外一个radio菜单");  
  84.         rbMenuItem.setMnemonic(KeyEvent.VK_D);  
  85.         group.add(rbMenuItem);  
  86.         rbMenuItem.addActionListener(this);  
  87.         menu.add(rbMenuItem);  
  88.   
  89.         //定义一组check box(检查盒)菜单  
  90.         menu.addSeparator();  
  91.         cbMenuItem = new JCheckBoxMenuItem("(C)使用检查盒的菜单");  
  92.         cbMenuItem.setMnemonic(KeyEvent.VK_C);  
  93.         cbMenuItem.addItemListener(this);  
  94.         menu.add(cbMenuItem);  
  95.   
  96.         cbMenuItem = new JCheckBoxMenuItem("(H)另外一个检查盒");  
  97.         cbMenuItem.setMnemonic(KeyEvent.VK_H);  
  98.         cbMenuItem.addItemListener(this);  
  99.         menu.add(cbMenuItem);  
  100.   
  101.         //定义一个带子菜单  
  102.         menu.addSeparator();  
  103.         submenu = new JMenu("(S)带有子菜单");  
  104.         submenu.setMnemonic(KeyEvent.VK_S);  
  105.         //定义子菜单  
  106.         menuItem = new JMenuItem("这是子菜单");  
  107.         //定义快捷键  
  108.         menuItem.setAccelerator(KeyStroke.getKeyStroke(  
  109.                 KeyEvent.VK_2, ActionEvent.ALT_MASK));  
  110.         menuItem.addActionListener(this);  
  111.         submenu.add(menuItem);  
  112.   
  113.         menuItem = new JMenuItem("子菜单项");  
  114.         menuItem.addActionListener(this);  
  115.         submenu.add(menuItem);  
  116.         menu.add(submenu);  
  117.   
  118.         //定义第二个菜单  
  119.         menu = new JMenu("(N)第二个菜单");  
  120.         menu.setMnemonic(KeyEvent.VK_N);  
  121.         menuBar.add(menu);  
  122.   
  123.         return menuBar;  
  124.     }  
  125. /** 
  126.  *方法说明:构建面板 
  127.  *输入参数: 
  128.  *返回类型: 
  129.  */  
  130.     public Container createContentPane() {  
  131.         //构造一个面板  
  132.         JPanel contentPane = new JPanel(new BorderLayout());  
  133.         contentPane.setOpaque(true);  
  134.   
  135.         //定义一个文本域  
  136.         output = new JTextArea(530);  
  137.         output.setEditable(false);  
  138.         scrollPane = new JScrollPane(output);  
  139.   
  140.         //将文本域添加到面板中  
  141.         contentPane.add(scrollPane, BorderLayout.CENTER);  
  142.   
  143.         return contentPane;  
  144.     }  
  145. /** 
  146.  *方法说明:构建弹出菜单 
  147.  *输入参数: 
  148.  *返回类型: 
  149.  */  
  150.     public void createPopupMenu() {  
  151.         JMenuItem menuItem;  
  152.   
  153.         //构件弹出菜单  
  154.         JPopupMenu popup = new JPopupMenu();  
  155.         ImageIcon openicon = createImageIcon("images/Open16.gif");  
  156.         menuItem = new JMenuItem("打开文件",openicon);  
  157.         menuItem.addActionListener(this);  
  158.         popup.add(menuItem);  
  159.         ImageIcon saveicon = createImageIcon("images/Save16.gif");  
  160.         menuItem = new JMenuItem("保存文件",saveicon);  
  161.         menuItem.addActionListener(this);  
  162.         popup.add(menuItem);  
  163.   
  164.         //添加一个监听给文本域,以便点击右键时响应  
  165.         MouseListener popupListener = new PopupListener(popup);  
  166.         output.addMouseListener(popupListener);  
  167.     }  
  168. /** 
  169.  *方法说明:监听普通的菜单选择 
  170.  *输入参数:ActionEvent e 事件 
  171.  *返回类型: 
  172.  */  
  173.     public void actionPerformed(ActionEvent e) {  
  174.         JMenuItem source = (JMenuItem)(e.getSource());  
  175.         String s = "监测事件。"  
  176.                    + newline  
  177.                    + "    事件源: " + source.getText()  
  178.                    + " (选择对象" + getClassName(source) + ")";  
  179.         output.append(s + newline);  
  180.     }  
  181. /** 
  182.  *方法说明:监听检查盒菜单选择项 
  183.  *输入参数:ItemEvent e 检查盒触发的事件 
  184.  *返回类型: 
  185.  */  
  186.     public void itemStateChanged(ItemEvent e) {  
  187.         JMenuItem source = (JMenuItem)(e.getSource());  
  188.         String s = "菜单项监听"  
  189.                    + newline  
  190.                    + "    事件源: " + source.getText()  
  191.                    + " (选择对象 " + getClassName(source) + ")"  
  192.                    + newline  
  193.                    + "    新的状态: "  
  194.                    + ((e.getStateChange() == ItemEvent.SELECTED) ?  
  195.                      "选择":"不选择");  
  196.         output.append(s + newline);  
  197.     }  
  198. /** 
  199.  *方法说明:获得类的名字 
  200.  *输入参数: 
  201.  *返回类型: 
  202.  */  
  203.     protected String getClassName(Object o) {  
  204.         String classString = o.getClass().getName();  
  205.         int dotIndex = classString.lastIndexOf(".");  
  206.         return classString.substring(dotIndex+1);  
  207.     }  
  208. /** 
  209.  *方法说明:根据路径查找图片 
  210.  *输入参数:String path 图片的路径 
  211.  *返回类型:ImageIcon 图片对象 
  212.  */  
  213.     protected static ImageIcon createImageIcon(String path) {  
  214.         java.net.URL imgURL = MenuDemo.class.getResource(path);  
  215.         if (imgURL != null) {  
  216.             return new ImageIcon(imgURL);  
  217.         } else {  
  218.             System.err.println("Couldn't find file: " + path);  
  219.             return null;  
  220.         }  
  221.     }  
  222.   
  223.     public static void main(String[] args) {  
  224.         JFrame.setDefaultLookAndFeelDecorated(true);  
  225.   
  226.         //创建一个窗体  
  227.         JFrame frame = new JFrame("MenuDemo");  
  228.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  229.   
  230.         //创建菜单,并添加到面板中  
  231.         MenuDemo demo = new MenuDemo();  
  232.         frame.setJMenuBar(demo.createMenuBar());  
  233.         frame.setContentPane(demo.createContentPane());  
  234.   
  235.         //生成弹出菜单  
  236.         demo.createPopupMenu();  
  237.   
  238.         //显示窗体  
  239.         frame.setSize(450260);  
  240.         frame.setVisible(true);  
  241.     }  
  242. //弹出菜单监听类  
  243.     class PopupListener extends MouseAdapter {  
  244.         JPopupMenu popup;  
  245.   
  246.         PopupListener(JPopupMenu popupMenu) {  
  247.             popup = popupMenu;  
  248.         }  
  249.           
  250.         public void mousePressed(MouseEvent e) {  
  251.             maybeShowPopup(e);  
  252.         }  
  253.   
  254.         public void mouseReleased(MouseEvent e) {  
  255.             maybeShowPopup(e);  
  256.         }  
  257.   
  258.         private void maybeShowPopup(MouseEvent e) {  
  259.             if (e.isPopupTrigger()) {  
  260.                 popup.show(e.getComponent(),  
  261.                            e.getX(), e.getY());  
  262.             }  
  263.         }  
  264.     }  
  265. }  

[java]  view plain copy
  1. package test20;  
  2.   
  3. import javax.swing.JToolBar;  
  4. import javax.swing.JButton;  
  5. import javax.swing.ImageIcon;  
  6.   
  7. import javax.swing.JFrame;  
  8. import javax.swing.JTextArea;  
  9. import javax.swing.JScrollPane;  
  10. import javax.swing.JPanel;  
  11.   
  12. import java.net.URL;  
  13.   
  14. import java.awt.*;  
  15. import java.awt.event.*;  
  16. /** 
  17.  * Title: 工具栏演示 
  18.  * Description: 提供一个工具栏,包括“打开”、“保存”、“搜索”工具按钮 
  19.  * Filename: ToolBarDemo.java 
  20.  */  
  21. public class ToolBarDemo extends JPanel  
  22.                          implements ActionListener {  
  23.   
  24.     private static final long serialVersionUID = 1L;  
  25.     protected JTextArea textArea;  
  26.     protected String newline = "\n";  
  27.     static final private String OPEN = "OPEN";  
  28.     static final private String SAVE = "SAVE";  
  29.     static final private String SEARCH = "SEARCH";  
  30. /** 
  31.  *方法说明:构造器 
  32.  *输入参数: 
  33.  *返回类型: 
  34.  */  
  35.     public ToolBarDemo() {  
  36.         super(new BorderLayout());  
  37.   
  38.         //创建工具栏  
  39.         JToolBar toolBar = new JToolBar();  
  40.         addButtons(toolBar);  
  41.   
  42.         //创建一个文本域,用来输出一些信息  
  43.         textArea = new JTextArea(1530);  
  44.         textArea.setEditable(false);  
  45.         JScrollPane scrollPane = new JScrollPane(textArea);  
  46.   
  47.         //安放成员  
  48.         setPreferredSize(new Dimension(450110));  
  49.         add(toolBar, BorderLayout.PAGE_START);  
  50.         add(scrollPane, BorderLayout.CENTER);  
  51.     }  
  52. /** 
  53.  *方法说明:构建工具栏 
  54.  *输入参数:JToolBar toolBar 工具条 
  55.  *返回类型: 
  56.  */  
  57.     protected void addButtons(JToolBar toolBar) {  
  58.         JButton button = null;  
  59.   
  60.         //第一个按钮,“打开”  
  61.         button = makeNavigationButton("Open16", OPEN,  
  62.                                       "打开一个文件!",  
  63.                                       "打开");  
  64.         toolBar.add(button);  
  65.   
  66.         //第二个按钮,“保存”  
  67.         button = makeNavigationButton("Save16", SAVE,  
  68.                                       "保存当前文件!",  
  69.                                       "保存");  
  70.         toolBar.add(button);  
  71.   
  72.         //第三个按钮,“搜索”  
  73.         button = makeNavigationButton("Search16", SEARCH,  
  74.                                       "搜索文件中的字符!",  
  75.                                       "搜索");  
  76.         toolBar.add(button);  
  77.     }  
  78. /** 
  79.  *方法说明:构造工具栏上的按钮 
  80.  *输入参数: 
  81.  *返回类型: 
  82.  */  
  83.     protected JButton makeNavigationButton(String imageName,  
  84.                                            String actionCommand,  
  85.                                            String toolTipText,  
  86.                                            String altText) {  
  87.         //搜索图片  
  88.         String imgLocation = "images/"  
  89.                              + imageName  
  90.                              + ".gif";  
  91.         URL imageURL = ToolBarDemo.class.getResource(imgLocation);  
  92.   
  93.         //初始化工具按钮  
  94.         JButton button = new JButton();  
  95.         //设置按钮的命令  
  96.         button.setActionCommand(actionCommand);  
  97.         //设置提示信息  
  98.         button.setToolTipText(toolTipText);  
  99.         button.addActionListener(this);  
  100.           
  101.         if (imageURL != null) {                      //找到图像  
  102.             button.setIcon(new ImageIcon(imageURL));  
  103.         } else {                                     //没有图像  
  104.             button.setText(altText);  
  105.             System.err.println("Resource not found: "  
  106.                                + imgLocation);  
  107.         }  
  108.   
  109.         return button;  
  110.     }  
  111. /** 
  112.  *方法说明:事件监听 
  113.  *输入参数: 
  114.  *返回类型: 
  115.  */  
  116.     public void actionPerformed(ActionEvent e) {  
  117.         String cmd = e.getActionCommand();  
  118.         String description = null;  
  119.   
  120.         if (OPEN.equals(cmd)) { //点击第一个按钮  
  121.             description = "打开一个文件操作!";  
  122.         } else if (SAVE.equals(cmd)) { //点击第二个按钮  
  123.             description = "保存文件操作";  
  124.         } else if (SEARCH.equals(cmd)) { //点击第三个按钮  
  125.             description = "搜索字符操作";  
  126.         }  
  127.   
  128.         displayResult("如果这里是真正的程序,你将进入: "  
  129.                         + description);  
  130.     }  
  131.   
  132.     protected void displayResult(String actionDescription) {  
  133.         textArea.append(actionDescription + newline);  
  134.     }  
  135.   
  136.     public static void main(String[] args) {  
  137.         JFrame.setDefaultLookAndFeelDecorated(true);  
  138.   
  139.         //定义窗体  
  140.         JFrame frame = new JFrame("ToolBarDemo");  
  141.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  142.   
  143.         //定义面板  
  144.         ToolBarDemo newContentPane = new ToolBarDemo();  
  145.         newContentPane.setOpaque(true);  
  146.         frame.setContentPane(newContentPane);  
  147.   
  148.         //显示窗体  
  149.         frame.pack();  
  150.         frame.setVisible(true);  
  151.     }  
  152. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值