0

你好我想知道。如何使用 JButton 将变量设置为 true 或 false,反之亦然?我的第一个想法是创建变量,例如

private boolean value1, value2;

和像这样的按钮

private JButton toggle1, toggle2;

// 见下面的代码

问题是它不会以某种方式对按钮做出反应。有可能这样还是我必须使用其他东西?

编辑:这是相关代码。(我的动作监听器)

    public void actionPerformed(ActionEvent e) {

    if( e.getSource() == toggle1 ) {

        if(aan1 == false) {

            aan1 ^= true;
            System.out.println(aan1);

        }
        else if(aan1 == true) {

            aan1 ^= false;
        }

    }

    try {
        // controleer of de ingevulde waarde tussen de 0 en de 15 is
        if( e.getSource() == burn && Integer.parseInt(textfield.getText()) < 16 && Integer.parseInt(textfield.getText()) > 0) {
            // brand kaars
            if( height > 15 && aan1 == true) {

                int aantal = Integer.parseInt(textfield.getText());
                height -= aantal;
            }


            if( height2 > 15 && aan2 == true) {
                int aantal = Integer.parseInt(textfield.getText());
                height2 -= aantal;
            }

            // opnieuw tekenen
            repaint();

        }
        else {

            JOptionPane.showMessageDialog(null, "error: vul een getal tussen de 0 en 15 in!"); // alertbox melding

        }
    }
    catch(NumberFormatException error) {

        JOptionPane.showMessageDialog(null, "error: een van de velden bevat geen cijfer of is niet ingevuld!"); // alertbox melding

    }

}
4

4 回答 4

2

正如如何使用按钮中所建议的,JToggleButton这可能是一个不错的选择,因为isSelected()谓词反映了按钮的状态。

state = button.isSelected()

可以在此处此处此处找到示例。

于 2012-10-03T15:26:19.040 回答
2

不确定您到底要问什么,但要切换可以使用的布尔值:

value1 = !value1;

或者

value1 ^= true;

然后打印你的变量:

System.out.println(value1);
于 2012-10-03T12:45:24.263 回答
1

就这样做?:

value1 != value1;

这反转当前值:所以如果为假,它将变为真,反之亦然。

编辑:应该是:

value = !value;
于 2012-10-03T12:47:02.883 回答
0

如果您想在按下按钮时切换布尔变量,您应该使用 aJCheckBox而不是JButton用于该目的,它具有内部布尔状态并且它会自行更新此变量。该复选框还使该布尔状态对用户可见。

当你需要布尔变量时,你可以用JCheckBox.isSelected()方法来询问它。

于 2012-10-03T12:49:30.273 回答