切換按鈕是一個雙狀態按鈕。它的狀態是按下或者不按下。 下面的範例展示了如何在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切換按鈕(tw511.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);
}
}
執行上面範例程式碼,得到以下結果: