切换按钮是一个双状态按钮。它的状态是按下或者不按下。 下面的示例展示了如何在Java Swing应用程序中创建和使用切换按钮。
使用以下API。
JToggleButton()
- 创建切换按钮。JToggleButton.isSelected()
- 检查切换按钮当前是否处于按下状态。
示例
package com.yiibai.swingdemo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing切换按钮(yiibai.com)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
final JToggleButton toggleButton = new JToggleButton("点击我!");
toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, ((JToggleButton)e.getSource()).isSelected());
}
});
panel.add(toggleButton);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
执行上面示例代码,得到以下结果: