我有一个JTogglebuttons和一个JButton数组,当按下JButton时它启动一个循环,循环遍历所有JTogglebuttons以查看它是否被按下,如果是,它应该使它禁用/不可点击
以下是代码片段
Public void actionPerformed(ActionEvent e){
Object pressed = e.getSource();
if (pressed == btnPurchase) {
for(int row = 0; row<8 ; row++){
for(int column = 0; column < 4; column++) {
if (seat[row][column].isPressed()) {
seat[row][column].setEnabled(false);
}
}
}
}
我收到此错误
cannot find symbol
symbol : method isPressed()
location: class javax.swing.JToggleButton
if (seat[row][column].isPressed()) {
如果我使用.isSelected
我得到了
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at cinemaManager.actionPerformed(cinemaManager.java:174)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375)
答案 0 :(得分:2)
查找ButtonModel,即返回预期方法,包括isSelected
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JToggleButtonChangeListener {
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JToggleButton toggleButton = new JToggleButton("Selecting Toggle / Deselacting Toggle");
toggleButton.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
ButtonModel buttonModel = toggleButton.getModel();
boolean armed = buttonModel.isArmed();
boolean pressed = buttonModel.isPressed();
boolean selected = buttonModel.isSelected();
System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
}
});
frame.add(toggleButton);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
}
注意:Backgroung的更改不适用于所有外观和感觉
答案 1 :(得分:0)
我发现我将数组重新定义在错误的位置,使其丢失现有元素。现在修复,谢谢