三.
按钮、切换按钮、复选按钮和单选按钮 按钮,就是按钮,不会连按钮都不知道吧?
切换按钮,有两种状态的按钮,即按下状态和弹起状态,若称为选择状态或未选择状态。
复选按钮,又叫复选框,用一个小方框中是否打勾来表示两种状态。
单选按钮,又叫收音机按钮,以小圆框打点表示被选中。常成组出现,一组单选按钮中只有一个能被选中。
发现什么了吗?——对了,这一部分是在讲各种各样的按钮,而且后三种按钮都有两种状态。先看看这些按钮都长成什么样:
上图中,从上到下,依次就是按钮、切换按钮、复选按钮和单选按钮。图示的窗口,就是下面这个例子的运行结果:
/**
* TestButtons.java
* @author Fancy
*/
import javax.swing.*;
import java.awt.event.*;
public class TestButtons {
JFrame frame = new JFrame("Test Buttons");
JButton jButton = new JButton("JButton"); //按钮
JToggleButton toggle = new JToggleButton("Toggle Button");
//切换按钮
JCheckBox checkBox = new JCheckBox("Check Box"); //复选按钮
JRadioButton radio1 = new JRadioButton("Radio Button 1");
//单选按钮
JRadioButton radio2 = new JRadioButton("Radio Button 2");
JRadioButton radio3 = new JRadioButton("Radio Button 3");
JLabel label = new JLabel("Here is Status, look here.");
//不是按钮,是静态文本
public TestButtons() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new
java.awt.FlowLayout());
/* 为一般按钮添加动作监听器 */
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
label.setText("You clicked jButton");
}
});
/* 为切换按钮添加动作监听器 */
toggle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JToggleButton toggle = (JToggleButton) ae.getSource();
if (toggle.isSelected()) {
label.setText("You selected Toggle Button");
} else {
label.setText("You deselected Toggle Button");
}
}
});
/* 为复选按钮添加条目监听器 */
checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox c