如果语句未在ActionPerformed事件期间执行

时间:2017-11-17 15:23:36

标签: java swing actionlistener

尝试编写Swing GUI。单击按钮时,我想测试是否已单击其他按钮。如果有,则执行“if”语句中的语句。但看起来“if”语句永远不会执行?

private void radSingleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
    if(radDoubleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= doublePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += singlePrice));
}                                               

private void radDoubleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
     if(radSingleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= singlePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += doublePrice));
}

1 个答案:

答案 0 :(得分:1)

单击JButton不会(永久)选中它。单击只是一个临时操作。

也许你想使用JToggleButton。这允许您单击按钮使其选中,然后再次单击它以使其不被选中。

阅读How to Use Buttons上的Swing教程中的部分以获取更多信息。

或者,如果您只是想知道用户是否点击了常规JButton,那么您需要自己维护一个布尔变量,并在按钮的ActionListener中进行更新。