我正在使用Swing与
Eclipse和Window Builder Pro创建一个Java GUI.我正在使用JButtons和JToggleButtons.我想从另一个按钮更改切换按钮的状态.
例如,当我单击清除网格时,所有切换按钮将被“未选择”.
我该怎么做?什么方法我必须用于切换按钮和按钮?
toggleButton.setSelected(boolean b)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonAction {
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Toggle Button");
final JToggleButton toggleButton1 = new JToggleButton("Another Toggle Button");
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\n");
toggleButton1.setSelected(selected);
}
};
toggleButton.addActionListener(actionListener);
frame.add(toggleButton,BorderLayout.NORTH);
frame.add(toggleButton1,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}