java核心技术卷 之复选框

来源:互联网 发布:区域分割算法优缺点 编辑:程序博客网 时间:2024/06/05 12:08

        如果想要接收的输入只是‘是’或‘非’,就可以使用复选框组件。复选框自动地带有标识标签。用户通过点击某个复选框来选择相成的选项,再点击则取消选取。当复选框获得焦点时,用户也可以通过按空格键来切换。

        复选框需要一个紧邻它的标签来说明其用途在构造器中指定标签文本。

bold = new JCheckBox(“Bo1d”);

        可以使用setSelected方法来选定或取消选定复选框。例如: 

bold. setSelected (true); 

         isSelected方法将返回每个复选框的当前状态。如果没有选取则为false,否则为true。 

         当用户点击复选框时将触发一个动作事件。通常,可以为复选框设置一个动作监听器。 在下面程序中,两个复选框使用了同一个动作监听器。 

ActionListener listener =... 

bold.addActionlistener (listener); 

italic.addActionlistener (listener); 

         actionPerformed方法查询bold和italic两个复选框的状态,并且把面板中的字体设置为常规、加粗、倾斜或者粗斜体。

public void actionPerformed(ActionEvent event)

int mode = 0; 

if (bold.isSelectedQ) mode += Font.BOLD; 

if (italic.isSelectedQ) mode += Font.ITALIC; 

label.setFont (new Font(“Serir”, mode, FONTSIZE));

}

示例代码:

import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;/** * Created by IBM on 2017/9/18. */public class CheckBoxTest {    public static void main(String[] args) {        EventQueue.invokeLater(new Runnable() {            public void run() {                CheckBoxFrame frame = new CheckBoxFrame();                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                frame.setVisible(true);            }        });    }}class CheckBoxFrame extends JFrame {    public CheckBoxFrame() {        setTitle("CheckBoxTest");        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);        // add the sample text label        label = new JLabel("The quick brown fox jumps over the lazy dog.");        label.setFont(new Font("Serif", Font.PLAIN, FONTSIZE));        add(label, BorderLayout.CENTER);        // this listener sets the font attribute of        // the label to the check box state        ActionListener listener = new ActionListener() {            public void actionPerformed(ActionEvent event) {                int mode = 0;                if (bold.isSelected()) mode += Font.BOLD;                if (italic.isSelected()) mode += Font.ITALIC;                label.setFont(new Font("Serif", mode, FONTSIZE));            }        };        // add the check boxes        JPanel buttonPanel = new JPanel();        bold = new JCheckBox("Bold");        bold.addActionListener(listener);        buttonPanel.add(bold);        italic = new JCheckBox("Italic");        italic.addActionListener(listener);        buttonPanel.add(italic);        add(buttonPanel, BorderLayout.SOUTH);    }    public static final int DEFAULT_WIDTH = 300;    public static final int DEFAULT_HEIGHT = 200;    private JLabel label;    private JCheckBox bold;    private JCheckBox italic;    private static final int FONTSIZE = 12;}

运行结果: