(总结)Swing组件的使用---按钮(JButton),组合框(JComboBox),下拉列表(JList)和颜色选择器(JColorChooser)

 

(总结)Swing组件的使用---按钮(JButton),组合框(JComboBox),下拉列表(JList)和颜色选择器(JColorChooser)

分类: Java学习笔记总结   610人阅读  评论(1)  收藏  举报

        

    Swing 的组件与AWT 组件相似,但又为每一个组件增添了新的方法,并提供了更多的高级组件.


Swing 的基本组件:


1.按钮(JButton):

    Swing 中的按钮可以显示图像,并且可以将按钮设置为窗口的默认图标,而且还可以将多个图像指定给一个按钮。

 (1).JButton 常用的构造方法

   JButton(String text):按钮上显示字符。

   JButton(Icon icon) :按钮上显示图标。

   JButton(String text, Icon icon):按钮上既显示图标又显示字符。

  (2).常用方法:

  b1.setEnabled(false);  //使按钮当前不可用

   b1.setToolTipText("..."): //设置按钮提示文本

   b1.setMnemonic(KeyEvent.VK_D);// 将b1邦定alt+D键

 (3).案例代码:

[java]  view plain copy print ?
  1. public class JButtonExample3 extends JPanel implements ActionListener {  
  2.   
  3.     protected JButton b1, b2, b3;  
  4.   
  5.     public JButtonExample3() {  
  6.           
  7.         ImageIcon leftButtonIcon = createImageIcon("right.gif");  
  8.         ImageIcon middleButtonIcon = createImageIcon("middle.gif");  
  9.         ImageIcon rightButtonIcon = createImageIcon("left.gif");  
  10.           
  11.         b1 = new JButton("失效中间按钮(D)", leftButtonIcon);  
  12.         b1.setVerticalTextPosition(AbstractButton.CENTER);// 水平中间对齐  
  13.         b1.setHorizontalTextPosition(AbstractButton.LEADING);// 相当于LEFT  
  14.         b1.setMnemonic(KeyEvent.VK_D);// 将b1邦定alt+D键  
  15.         b1.setActionCommand("disable");  
  16.           
  17.         b2 = new JButton("M中间按钮", middleButtonIcon);  
  18.         b2.setVerticalTextPosition(AbstractButton.BOTTOM);  
  19.         b2.setHorizontalTextPosition(AbstractButton.CENTER);  
  20.         b2.setMnemonic(KeyEvent.VK_M);// 将b2邦定alt+M键  
  21.           
  22.         b3 = new JButton("E激活中间按钮", rightButtonIcon);  
  23.         b3.setMnemonic(KeyEvent.VK_E);// 将b3邦定alt+E键  
  24.         b3.setActionCommand("enable");  
  25.         b3.setEnabled(false);  
  26.           
  27.         // 给1和3添加事件监听  
  28.         b1.addActionListener(this);  
  29.         b3.addActionListener(this);  
  30.           
  31.         // 设置按钮提示文本  
  32.         b1.setToolTipText("点击这个按钮,将使中间的按钮失效!");  
  33.         b2.setToolTipText("点击这个按钮,没有任何的事件发生!");  
  34.         b3.setToolTipText("点击这个按钮,将使中间的按钮有效");  
  35.           
  36.         // 将按钮添加到JPanel中  
  37.         add(b1);  
  38.         add(b2);  
  39.         add(b3);  
  40.     }  
  41.   
  42.     public void actionPerformed(ActionEvent e) {  
  43.         if ("disable".equals(e.getActionCommand())) {  
  44.             b2.setEnabled(false);  
  45.             b1.setEnabled(false);  
  46.             b3.setEnabled(true);  
  47.         } else {  
  48.             b2.setEnabled(true);  
  49.             b1.setEnabled(true);  
  50.             b3.setEnabled(false);  
  51.         }  
  52.     }  
  53.   
  54.     protected static ImageIcon createImageIcon(String path) {  
  55.         java.net.URL imgURL = JButtonExample3.class.getResource(path);  
  56.         if (imgURL != null) {  
  57.             return new ImageIcon(imgURL);  
  58.         } else {  
  59.             System.err.println("Couldn′t find file: " + path);  
  60.             return null;  
  61.         }  
  62.     }  
  63.   
  64.     public static void main(String[] args) {  
  65.         // 设置使用新的swing界面  
  66.         //提供一个关于新创建的 JFrame 是否应该具有当前外观为其提供的 Window 装饰(如边框、关闭窗口的小部件、标题等等)的提示。  
  67.         JFrame.setDefaultLookAndFeelDecorated(true);  
  68.         // 创建一个窗体  
  69.         JFrame frame = new JFrame("小龙按钮");  
  70.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  71.         // 创建一个面板  
  72.         JButtonExample3 newContentPane = new JButtonExample3();  
  73.         newContentPane.setOpaque(true);  
  74.         frame.setContentPane(newContentPane);  
  75.         // 显示窗体  
  76.         frame.pack();  
  77.         frame.setLocation(300200);  
  78.         frame.setVisible(true);  
  79.     }  
  80. }  

  运行截图:



(说明:以下关于列表框内容部分出自此处:点击打开链接,特此声明!

2.组合框(JComboBox):

  组合框(下拉列表JComboBox)使用方法及示例详解:

构造方法:
* JComboBox() 建立一个JComboBox组件.
* JComboBox(ComboBoxModel model) 根据model建立一个JComboBox组件.
* JComboBox(Objext[] items) 利用数组对象建立一个JComboBox组件.
* JComboBox(Vector items) 利用Vector对象建立一个JComboBox组件.

常用方法:

....

综合示例:

[java]  view plain copy print ?
  1. <span style="background-color: rgb(255, 255, 255);">import java.awt.*; /* 包含用于创建用户界面和绘制图形图像的所有类。 */  
  2. import javax.swing.*; /* 提供一组"轻量级"组件,尽量让这些组件在所有平台上的工作方式都相同 */  
  3.   
  4.   
  5. public class JComboBoxDemo extends JFrame {  
  6.       
  7.     public JComboBoxDemo() {  
  8.         /* 
  9.          * Container是所有容器的父类,又是Java语言的组件类Component的子类. 容器是一种具有容纳其他组件和容器的功能的组件 
  10.          * 一个Java的图形用户界面的最基本元素是组件,组件是可以以图形化的方式显示在屏幕上并能与用户进行交互的对象,如一个按钮,一个文本框等. 
  11.          * 在Java中,通常将组件放在一定的容器内使用 this.getContentPane()方法返回此窗体的 contentPane 对象 
  12.          */  
  13.         Container contentPane = this.getContentPane();  
  14.           
  15.         /* 创建一个面板对象,指定布局管理器为GridLayout,1行2列.Jpanel的默认版面管理为FlowLayout */  
  16.         JPanel jPanel1 = new JPanel(new GridLayout(12));  
  17.           
  18.         // 利用String数组建立JComboBox  
  19.         String[] fruit = { "苹果""香蕉""桔子""梨""芒果" };  
  20.         JComboBox jComboBox1 = new JComboBox(fruit);  
  21.         jComboBox1.addItem("其他"); // 在列表框选项的最后再添加一个"其他"选项  
  22.           
  23.         // 设置jList1对象的带标题边框  
  24.         jComboBox1.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果:"));  
  25.         // 添加列表框jComboBox1至面板  
  26.         jPanel1.add(jComboBox1);  
  27.           
  28.         // 利用ComboBoxModel建立JComboBox  
  29.         ComboBoxModel myModel = new MyModel();  
  30.         JComboBox jComboBox2 = new JComboBox(myModel);  
  31.         // 设置jList1对象的带标题边框  
  32.         jComboBox2.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果:"));  
  33.         // 添加列表框jComboBox2至面板  
  34.         jPanel1.add(jComboBox2);  
  35.           
  36.         // 添加面板至父容器  
  37.         contentPane.add(jPanel1);  
  38.         // 设置本窗体的标题  
  39.         this.setTitle("JComboBoxDemo");  
  40.         // 设置本窗体显示的初始大小  
  41.         this.setSize(35090);  
  42.         this.setLocation(300200);  
  43.         // 设置本窗体初始可见  
  44.         this.setVisible(true);  
  45.     }  
  46.   
  47.     class MyModel extends DefaultComboBoxModel {  
  48.         String[] fruit = { "苹果""香蕉""桔子""梨""芒果" };  
  49.   
  50.         MyModel() {  
  51.             for (int i = 0; i < fruit.length; i++) {  
  52.                 /* addElement()方法用于向列表框添加选项元素 */  
  53.                 this.addElement(fruit[i]);  
  54.             }  
  55.         }  
  56.     }  
  57.   
  58.     public static void main(String args[]) {  
  59.         JComboBoxDemo test = new JComboBoxDemo();  
  60.     }  
  61. }</span>  
截图:



3.列表框(JList):

   列表框的功能与下拉列表框相似,也是让用户在几个条目中做出选择,但又有一些区别,它提供给用户的选择模式更为多样,分别是单一选择、连续选择、多项选择,对应于 ListSelectionModel 中的3个常量:

  (1) static int SINGLE_SELECTION 只能选择一条。

  (2) static int SINGLE_INTERVAL_SELECTION 按住[Shift]键可选择联系的区间。

  (3) static int MULTIPLE_INTERVAL_SELECTION 按住[Ctrl]键可选择多条。


构造函数如下:

  (1) JList() 建立一个 JList 组件。

  (2) JList(ListModel model) 根据 model 建立一个 JList 组件。

  (3) JList(Object[] items) 利用数组对象建立一个 JList 组件。

  (4) JList(Vector items) 利用 Vector 对象建立一个 JList 组件。

  

将列表框JList添加到JScrollPane中可以实现列表框的滚动.


列表(JList)组件使用示例1如下:

[java]  view plain copy print ?
  1. <span style="background-color: rgb(255, 255, 255);">public class JListDemo1 extends JFrame{  
  2.       
  3.     Container contentPane;  
  4.     JPanel jp;  
  5.     JList jList1,jList2,jList3;  
  6.       
  7.    public JListDemo1(){  
  8.          
  9.       contentPane = this.getContentPane();  
  10.         
  11.       jp = new JPanel(new GridLayout(1,3));  
  12.   
  13.       //利用String数组建立JList对象  
  14.       String[] fruit={"苹果","香蕉","桔子","梨","芒果"};  
  15.       jList1=new JList(fruit);  
  16.       //设置jList1对象的带标题边框  
  17.       jList1.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果: "));  
  18.       //设置jList1对象的选择模式为单一选择  
  19.       jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  20.       jp.add(jList1);  
  21.   
  22.       //利用ListModel建立JList对象,可实现列表内容的动态  
  23.       ListModel myModel=new MyModel(); //创建一个列表模型对象        
  24.       jList2=new JList(myModel); //根据列表模型对象创建列表  
  25.       jList2.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果: "));  
  26.   
  27.       //设置jList2对象的选择模式为按住[Ctrl]可多项选择  
  28.       jList2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);  
  29.       jp.add(jList2);  
  30.         
  31.       jList3=new JList(fruit);  
  32.       jList3.setBorder(BorderFactory.createTitledBorder("您最喜欢的水果: "));  
  33.       jList3.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);  
  34.       jList3.setVisibleRowCount(3);  
  35.       jList3.setFixedCellWidth(120);  
  36.       jList3.setFixedCellHeight(30);  
  37.       JScrollPane jScrollPane = new JScrollPane(jList3);  
  38.       jp.add(jScrollPane);  
  39.         
  40.       contentPane.add(jp);  
  41.         
  42.       this.setTitle("JListDemo");  
  43.       this.setSize(340,200);  
  44.       //pack();  
  45.       this.setLocation(400300);  
  46.       this.setVisible(true);  
  47.    }  
  48.   
  49.    //通过继承DefaultListModel类可实现动态内容的列表选择  
  50.    class MyModel extends DefaultListModel{  
  51.          
  52.       String[] fruit={"苹果","香蕉","桔子","梨","芒果"};  
  53.         
  54.       MyModel(){  
  55.          for(int i=0;i<fruit.length;i++){  
  56.             /* void addElement(Object obj)  
  57.              * 将指定组件添加到此类表的末尾。*/  
  58.             this.addElement(fruit[i]);  
  59.          }  
  60.       }  
  61.    }  
  62.   
  63.    public static void main(String[] args){  
  64.       JListDemo1 test=new JListDemo1();  
  65.    }  
  66. }  
  67. </span>  

运行结果如下图所示:


列表框示例2代码:

[java]  view plain copy print ?
  1. <span style="background-color: rgb(255, 255, 255);">public class JListDemo2 extends JFrame {  
  2.   
  3.     Container contentPane;  
  4.     JPanel jp;  
  5.     JList jListFont, jListSize;  
  6.   
  7.     // 构造函数  
  8.     public JListDemo2() {  
  9.   
  10.         contentPane = this.getContentPane();  
  11.         jp = new JPanel(new GridLayout());  
  12.   
  13.         setJListFont();  
  14.         setJListFontSize();  
  15.   
  16.         contentPane.add(jp);  
  17.   
  18.         this.setTitle("JListDemo");  
  19.         this.setSize(240200);  
  20.         this.setLocation(400300);  
  21.         this.setVisible(true);  
  22.   
  23.     } // End of JListDemo2  
  24.   
  25.     public void setJListFont() {  
  26.         GraphicsEnvironment ge = GraphicsEnvironment  
  27.                 .getLocalGraphicsEnvironment();  
  28.         final String fontName[] = ge.getAvailableFontFamilyNames(); // 获取系统的本地字体  
  29.   
  30.         jListFont = new JList(fontName);  
  31.   
  32.         // 设置jList1对象的带标题边框  
  33.         jListFont.setBorder(BorderFactory.createTitledBorder("系统字体: "));  
  34.         // 设置jList1对象的选择模式为单一选择  
  35.         jListFont.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  36.         jListFont.setVisibleRowCount(3);  
  37.         jListFont.setFixedCellWidth(120);  
  38.         jListFont.setFixedCellHeight(20);  
  39.   
  40.         JScrollPane jScrollPane1 = new JScrollPane(jListFont);  
  41.         jp.add(jScrollPane1);  
  42.     }  
  43.     public void setJListFontSize() {  
  44.         final String fontSize[] = { "8""9""10""12""14""15""16",  
  45.                 "18""20""21""22""24""26""28""30""36""48",  
  46.                 "54""72""89" };  
  47.         // 创建字号的列表框listSize  
  48.         jListSize = new JList(fontSize);  
  49.         jListSize.setBorder(BorderFactory.createTitledBorder("字体大小: "));  
  50.         // 设置jList2对象的选择模式为按住[Ctrl]可多项选择  
  51.         jListSize  
  52.                 .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);  
  53.         jListSize.setVisibleRowCount(3);  
  54.         jListSize.setFixedCellWidth(120);  
  55.         jListSize.setFixedCellHeight(20);  
  56.   
  57.         JScrollPane jScrollPane2 = new JScrollPane(jListSize);  
  58.         jp.add(jScrollPane2);  
  59.     }  
  60.   
  61.     public static void main(String[] args) {  
  62.         JListDemo2 test = new JListDemo2();  
  63.     }  
  64. }  
  65. </span>  

程序运行示意图:



4.javax.swing 
       类 JColorChooser:
        JColorChooser (颜色选择对话框)提供一个用于允许用户操作和选择颜色的控制器窗格

       JColorChooser构造函数:
   JColorChooser():建立一个JColorChooer对象,默认颜色为白色.
   JColorChooser(Color initialColor):建立一个JColorChooer对象,并设置初始颜色.
   JColorChooser(ColorSelectionModel modal):以ColorSelectionModel构造JColorChooser对象.
  

    最常使用JColorChooser的方式是使用JColorChooser的静态方法showDialog().也就是说在大部份的情况下,我们不会new一个JColorChooser对象,而是直接使用JColorChooser的静态方法(showDialog())来输出颜色选择对话框.利用这个方法我们亦可以得到用户所选择的颜色,若用户没有选择则返回null值.


颜色选择对话框的简单案例1代码:

[java]  view plain copy print ?
  1. <span style="background-color: rgb(255, 255, 255);">public class JColorChooserDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         JFrame frame = new JFrame("JColorChooserDemo");  
  6.           
  7.         MyPanel panel = new MyPanel();  
  8.         frame.getContentPane().add(panel);  
  9.           
  10.         frame.pack();  
  11.         frame.setLocation(300200);  
  12.         frame.setVisible(true);  
  13.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  14.     }  
  15. }  
  16.   
  17. class MyPanel extends JPanel implements ActionListener {  
  18.   
  19.     private static final long serialVersionUID = 1L;  
  20.     private JButton button,rgb,red,green,blue;  
  21.     private Color color = new Color(25551150);  
  22.   
  23.     public MyPanel() {  
  24.   
  25.         button = new JButton("Get Color");  
  26.         rgb = new JButton("RGB: ");  
  27.         red = new JButton("Red: ");  
  28.         green = new JButton("Green: ");  
  29.         blue = new JButton("Blue: ");  
  30.         button.addActionListener(this);  
  31.   
  32.         setPreferredSize(new Dimension(550250));  
  33.         setLayout(new FlowLayout(FlowLayout.CENTER, 55));  
  34.         setBackground(color);  
  35.         add(button);  
  36.         add(rgb);  
  37.         add(red);  
  38.         add(green);  
  39.         add(blue);  
  40.     }  
  41.   
  42.     public void actionPerformed(ActionEvent e) {  
  43.   
  44.         color = JColorChooser.showDialog(this"Choose Color", color);  
  45.   
  46.         if (color != null) {  
  47.             setBackground(color);  
  48.             button.setText("Get again");  
  49.             rgb.setText("RGB: " + color.getRGB());  
  50.             red.setText("Red: " + color.getRed());  
  51.             green.setText("Green: " + color.getGreen());  
  52.             blue.setText("Blue: " + color.getBlue());  
  53.         }  
  54.     }  
  55. }</span>  
运行结果示意图如下:





    另外还有一个使用JColorChooser常用的方式,那就是使用createDialog()静态方法.使用这个静态方法后会得到一个JDialog对象,我们可以利用这个JDialog对象对颜色选择对话框做更多的设置.不过利用这个方法必须配合JColorChooser对象才行,也就是必须new出一个JColorChooser对象来.下面范例介绍最简单的也是最实用JColorChooser,选择颜色完毕后就能更改JLabel上的背景颜色.


颜色选择对话框的简单案例2代码:

[java]  view plain copy print ?
  1. <span style="background-color: rgb(255, 255, 255);">import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.   
  5. public class ColorChooserDemo1 extends MouseAdapter {  
  6.       
  7.     JFrame f = null;  
  8.     JLabel label = null;  
  9.     JLabel label1 = null;  
  10.     JLabel label2 = null;  
  11.     Rectangle rec1 = null;  
  12.     Rectangle rec2 = null;  
  13.   
  14.     public ColorChooserDemo1() {  
  15.       
  16.         f = new JFrame("ColorChooser Example");  
  17.         Container contentPane = f.getContentPane();  
  18.         contentPane.addMouseListener(this);  
  19.   
  20.         label = new JLabel(" ", JLabel.CENTER);  
  21.         label.setPreferredSize(new Dimension(30020));  
  22.   
  23.         JPanel panel = new JPanel();  
  24.         panel.setLayout(new GridLayout(12));  
  25.   
  26.         label1 = new JLabel("左Label", JLabel.CENTER);  
  27.         label1.setBackground(Color.red);  
  28.         label1.setForeground(Color.black);  
  29.         label1.setOpaque(true);  
  30.         label1.setBounds(00150150);  
  31.         panel.add(label1);  
  32.   
  33.         label2 = new JLabel("右Label", JLabel.CENTER);  
  34.         label2.setBackground(Color.green);  
  35.         label2.setForeground(Color.black);  
  36.         label2.setOpaque(true);  
  37.         label2.setBounds(1500150150);  
  38.         panel.add(label2);  
  39.   
  40.         rec1 = label1.getBounds();  
  41.         rec2 = label2.getBounds();  
  42.   
  43.         contentPane.add(panel, BorderLayout.CENTER);  
  44.         contentPane.add(label, BorderLayout.SOUTH);  
  45.   
  46.         f.setSize(new Dimension(300150));  
  47.         f.setVisible(true);  
  48.   
  49.         f.addWindowListener(new WindowAdapter() {  
  50.             public void windowClosing(WindowEvent e) {  
  51.                 System.exit(0);  
  52.             }  
  53.         });  
  54.     }  
  55.   
  56.     // 实现MouseAdapter中的mousePressed()与mouseClicked()方法.当按下鼠标时,就能知道鼠标光标目前的位置.当连续键击鼠标  
  57.     // 两次时,若光标所在位置在label中,就会出现颜色选择对话框,用户可选择任一颜色更改label的颜色.  
  58.     public void mousePressed(MouseEvent e) {  
  59.         label.setText("目前鼠标坐标(X,Y)为:(" + e.getX() + "," + e.getY() + ")");  
  60.     }  
  61.   
  62.     public void mouseClicked(MouseEvent e) {  
  63.         Point point = e.getPoint();  
  64.   
  65.         if (e.getClickCount() == 2) {  
  66.             if (rec1.contains(point)) {  
  67.                 /* 
  68.                  * 利用JColorChooser的showDialog()静态方法输出颜色选择对话框 
  69.                  * ,showDialog()中的3个参数依次是: 对话框的父组件,颜色选择对话框标题 
  70.                  * ,与对话框默认颜色.当用户选择完颜色之后,按下"OK"按钮则返回 
  71.                  * Color对象,若按下"Cancel"按钮则返回null值. 
  72.                  */  
  73.                 Color color = JColorChooser.showDialog(f,  
  74.                         "Change label1 Color", Color.white);  
  75.                 if (color != null// 若为null值表示用户按下Cancel按钮  
  76.                     label1.setBackground(color);  
  77.             }  
  78.             if (rec2.contains(point)) {  
  79.                 Color color = JColorChooser.showDialog(f,  
  80.                         "Change label2 Color", Color.yellow);  
  81.                 if (color != null// 若为null值表示用户按下Cancel按钮  
  82.                     label2.setBackground(color);  
  83.             }  
  84.         }  
  85.     }  
  86.       
  87.     public static void main(String[] arg) {  
  88.         new ColorChooserDemo1();  
  89.     }  
  90. }</span>  
程序运行示意图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值