JFrame(swing)用按钮切换重复动作

JFrame (swing) switching repeating actions with buttons(JFrame(swing)用按钮切换重复动作)

本文介绍了JFrame(swing)用按钮切换重复动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有 2 个按钮(最终更多)的 JFrame 应用程序,我可以使用它们在多个重复动作之间切换,出于简单性,我现在只是使用控制台打印,尽管稍后它可能会调用一个方法.这是 JFrame 的框架:

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, though it will probably be calling a method instead later. Here is the framework for the JFrame:

public class DayNight extends JFrame implements ActionListener{

    //JFrame entities
    private JPanel animationPanel;
    private JButton button;
    private JButton button2;


    public static void main(String[] args) {
        DayNight frame = new DayNight();
        frame.setSize(2000, 1300);
        frame.setLocation(1000,350);
        frame.createGUI();
        frame.setVisible(true);
        frame.setTitle("Day/Night Cycle, Rogier");
    }

   private void createGUI() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new FlowLayout() );
    animationPanel = new JPanel();
    animationPanel.setPreferredSize(new Dimension(2000, 900));
    animationPanel.setBackground(Color.black);
    window.add(animationPanel);

    button = new JButton("choice1");
    button.setFont(new Font("Arial", Font.PLAIN, 50));
    window.add(button);
    button.setActionCommand("choice1");
    button.addActionListener(this);

    button2 = new JButton("choice2");
    button2.setFont(new Font("Arial", Font.PLAIN, 50));
    window.add(button2);
    button2.setActionCommand("choice2");
    button2.addActionListener(this);
   }
}

我尝试了以下方法:

public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    while ("Stop"!=(command)){
        command = event.getActionCommand();
        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();
        }

    }
}

但是在我单击一个按钮后,它一直停留在该打印件上,我什至无法再与这些按钮进行交互.我错过了什么还是我需要一个完全不同的结构?我检查了很多不同的程序,但它们对我来说太复杂了,我无法理解,阅读 Swing 中的并发也没有让我明白.

But after I click a button it keeps stuck on that print and I can't even interact with the buttons anymore. Am I missing something or do I need a completely different structure? I've examined a lot of different programs but they are too complicated for me to understand, reading the concurrency in swing also didn't clear it up for me.

还没有停止"命令,因为我现在不需要它.

There is no "stop" command yet because I don't need it for now.

推荐答案

你的代码有很多错误.

它以 错误 字符串比较开始(请参阅 这里).

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

但您的实际问题是:您正在 sleeping 事件调度程序线程(请参阅 那里)

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.

真正的答案是:你缺乏Java的基本知识.在使用 Swing UI 编码时,请考虑首先学习这些基本知识,然后再让自己负担过重.

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();
}

以上:

  • 创建一个 Runnable,它只是等待然后打印一些东西
  • 使用一个新线程(不是事件调度线程)来做到这一点
  • 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.

但进一步思考 - 我认为这是朝着错误的方向发展.当您开发一个合理的 UI 应用程序时,您不希望 任何东西等待.

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.

换句话说:你认为:

  • 按钮 A 被点击 - 一些代码开始循环"
  • 当用户做出另一个选择时,循环"代码会注意到这一点并执行一些操作

错误的方法.而是按照以下思路工作:

Wrong approach. Instead work along these lines:

  • 用户点击一个按钮,可能会启用其他 UI 组件
  • 用户对那些其他 UI 组件执行某些操作 - 触发 其他 操作
  • 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.

这篇关于JFrame(swing)用按钮切换重复动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JFrame(swing)用按钮切换重复动作

基础教程推荐