JFrame (swing) switching repeating actions with buttons

前端 未结 1 992
自闭症患者
自闭症患者 2021-01-23 19:21

I want a JFrame application with 2 buttons (eventually more) that I can use to switch between multiple repeating actions, ofr simplicity I\'m just using a console print for now,

相关标签:
1条回答
  • 2021-01-23 20:03

    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.

    0 讨论(0)
提交回复
热议问题