使用JButton将变量切换为true / false

时间:2012-10-03 12:39:02

标签: java swing jbutton

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

这样的变量
private boolean value1, value2;

之类的按钮
private JButton toggle1, toggle2;

//见下面的代码

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

编辑:这是相关代码。 (我的ActionListener)

    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 个答案:

答案 0 :(得分:2)

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

value1 = !value1;

value1 ^= true;

然后打印您的变量:

System.out.println(value1);

答案 1 :(得分:2)

根据How to Use Buttons的建议,JToggleButton可能是一个很好的选择,因为isSelected()谓词反映了按钮的状态。

state = button.isSelected()

可以找到示例hereherehere

答案 2 :(得分:1)

这样做?:

value1 != value1;

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

编辑: 应该是:

value = !value;

答案 3 :(得分:0)

如果要在按下按钮时切换布尔变量,则应使用JCheckBox而不是JButton来实现具有内部布尔状态的JCheckBox.isSelected(),并且它自己更新此变量。该复选框还使用户可以看到此布尔状态。

当您需要布尔变量时,可以使用{{1}}方法询问它。

相关问题