JFrame (swing) switching repeating actions with buttons

岁酱吖の 提交于 2019-12-02 05:48:39

There are many things wrong with your code.

It starts with wrong comparison of strings ( see here ).

But your actual problem: you are sleeping the event dispatcher thread ( see there )

So your idea of sleeping with an event listener is simply the wrong approach. You can't do it this way. You have to re-think your approach there.

And the real answer here is: you are lacking basic knowledge of Java. Consider learning such basic things first before further overburdening yourself if Swing UI coding.

Your requirement seems to be: after that button was hit - and a certain amount of time passed you want to print something on the console. You can do that like:

public void actionPerformed(ActionEvent event) {
   String command = event.getActionCommand();
   command = event.getActionCommand();
   Runnable printChoice = new Runnable() {
     @Override
     public void run() {
      try{
        Thread.sleep(500);
        if ("choice1".equals(command)){
            System.out.println("choice1");
        }
        else if("choice2".equals(command)){
            System.out.println("choice2");
        }
        else{
            System.out.println("no choice");
        }
      }   
      catch(InterruptedException ex){
        Thread.currentThread().interrupt();
      }
    });
    new Thread(printChoice).start();
}

The above:

  • creates a Runnable that simply waits to then print something
  • uses a new Thread (not the event dispatcher thread) to do that

I didn't run this through the compiler - it is meant as "pseudo code" to give you some ideas how to solve your problem.

But further thinking about this - I think this is going in the wrong direction. You don't want that anything is waiting when you develop a reasonable UI application.

In other words: you think of:

  • button A is clicked - some code starts "looping"
  • when the user makes another choice, that "looping" code notices that and does something

Wrong approach. Instead work along these lines:

  • user clicks a button, and maybe that enables other UI components
  • user does something with those other UI components - triggering other actions

Example: changing radiobuttons causes events to be fired. You should not have a loop that regularly keeps checking those buttons. Instead you define a clear flow of actions/events the user has to follow in order to trigger a certain action.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!