【问题标题】:Second press of a GUI button第二次按下 GUI 按钮
【发布时间】:2020-01-23 04:43:48
【问题描述】:

在计算并显示用户掷出的骰子后,我试图让我的按钮在我的 GUI 中被第二次按下。到目前为止,我想出的唯一解决方案是放置一个 .setSource(false);在我的按钮的 actionListener 中声明。我在哪里放置我的代码(我假设可能有更有效的语句来重置我的按钮)?

button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == button){
            /* my output when button is pressed
            .
            .
            . */
            e.setSource(false);
          }
    }); 

【问题讨论】:

  • 您想重置按钮 GUI,因为每次单击按钮时都需要按钮更改按钮内的文本显示?
  • 为什么要重置它?
  • @user3437460 帖子已编辑。我希望允许在我的程序中按下第二个按钮,这将在单击按钮后替换相应的输出。
  • @DevilsHnd ^ 在上面的评论中回答

标签: java user-interface button uibutton actionlistener


【解决方案1】:

也许利用类全局布尔变量用作切换标志:

public class MyClass {

    boolean toggle = false;
    /*
      other relative class code
    */


    button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        // If button is selected the first time.
        if (e.getSource() == button && !toggle){
            toggle = true;
            /* my output when button is pressed the first time.
            .
            .
            . */

            e.setSource(false);
        }
        // If button is selected the second time.
        if (e.getSource() == button && toggle){
            toggle = false;
            /* my output when button is pressed the second time.
            .
            .
            . */
            e.setSource(false);
        }
    }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多