简体   繁体   English

Java - 更新在Swing中创建的GUI

[英]Java - Updating a GUI made in Swing

I am trying to create a simple GUI form which has only 2 elements - a simple label and a button. 我正在尝试创建一个只有2个元素的简单GUI表单 - 一个简单的标签和一个按钮。 The text displayed on button is 'Start'. 按钮上显示的文字是“开始”。 The label is displaying 0 by default. 标签默认显示为0。

When I click Start button following actions shall take place: 当我单击“开始”按钮时,将执行以下操作:

  1. Counter shall start incrementing by 1 from 0 at every 1 second. 计数器应每1秒从0开始递增1。
  2. Text displayed on the Start button shall change to Stop. “开始”按钮上显示的文本将更改为“停止”。
  3. When again I click on the same button (now showing caption as Stop), increment shall stop. 当我再次点击相同的按钮(现在显示标题为停止)时,增量将停止。
  4. Text on the button shall change to Start. 按钮上的文本将更改为“开始”。 And so on... 等等...

I am developing my application in Netbeans. 我正在Netbeans中开发我的应用程序。

As shown in the above diagram, there are 2 .java files 如上图所示,有2个.java文件

Contents of AGC.java are: AGC.java的内容是:

public class AGC extends javax.swing.JFrame 
{
    public AGC()
    {    
        initComponents();
    }

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() 
            {
                new AGC().setVisible(true);
            }
        });
    }

    private javax.swing.JButton btnStartStop;  // name of start stop button
    private javax.swing.JLabel lblCounter;   // name of the label

}

Contents of Main.java are: Main.java的内容是:

public class Main 
{
    public static int count = 0;
    public static boolean started = false;
}

I want to implement following logic: 我想实现以下逻辑:

private void btnStartStopMouseClicked(java.awt.event.MouseEvent evt) 
{
    if (Main.stared == true)
    {
        // logic to start counting
    }
    else
    {
        // logic to stop counting
    }
}

My problem is this: 我的问题是:

  1. How to update lblCounter at every 1 second? 如何每1秒更新一次lblCounter?
  2. What logic shall I implement to start the timer of 1 second and how to access lblCounter in that method ? 我应该实现什么逻辑来启动1秒的计时器以及如何在该方法中访问lblCounter?

Kindly help. 请帮助。 A working code would be very highly appreciated. 非常感谢工作代码。 Thanks in advance. 提前致谢。

Jay 松鸦

Simply use a javax.swing.Timer , and make one ActionListener , to do this thing for you . 只需使用javax.swing.Timer ,并制作一个ActionListener ,即可为您完成此任务。 Give me ten mins for a working code example :-) 给我一个工作代码示例10分钟:-)

Here is a sample program for further help : 这是一个示例程序以获得进一步的帮助:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class UpdateWithTimer extends JFrame
{
    private Timer timer;
    private JButton startStopButton;
    private JLabel changingLabel;
    private int counter = 0;
    private boolean flag = false;
    private ActionListener timerAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            counter++;
            changingLabel.setText("" + counter);
        }
    };

    private ActionListener buttonAction = new ActionListener()  
    {
        public void actionPerformed(ActionEvent ae)
        {
            if (!flag)
            {
                startStopButton.setText("STOP TIMER");
                timer.start();
                flag = true;
            }
            else if (flag)
            {
                startStopButton.setText("START TIMER");
                timer.stop();
                flag = false;
            }
        }
    };

    private void createAndDisplayGUI()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        JPanel contentPane = new JPanel();
        changingLabel = new JLabel("" + counter);
        contentPane.add(changingLabel);

        startStopButton = new JButton("START TIMER");
        startStopButton.addActionListener(buttonAction);

        add(contentPane, BorderLayout.CENTER);
        add(startStopButton, BorderLayout.PAGE_END);

        timer = new Timer(1000, timerAction);

        setSize(300, 300);
        setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new UpdateWithTimer().createAndDisplayGUI();
            }
        });
    }
}

If you want the counter to again revert back to 0, on Stopping the Timer, simply add 如果您希望计数器再次恢复为0,则在停止计时器时,只需添加即可

else if (flag)
{
    startStopButton.setText("START TIMER");
    timer.stop();
    flag = false;
    counter = 0;
    changingLabel.setText("" + counter);
}

this part to the buttonAction 's actionPerformed(...) method. 这部分是buttonActionactionPerformed(...)方法。

Ok, so what I would suggest is to have a look at SwingWorker . 好的,我建议看一下SwingWorker You can extend SwingWorker and in the doBackground() execute a while(!isCancelled()) loop with a Thread.sleep(1000); 你可以扩展SwingWorker并在doBackground()中使用Thread.sleep(1000);执行a while(!isCancelled())循环Thread.sleep(1000); After the sleep execution, you can simply fire a property change that increments the value of your label. 执行睡眠后,您只需触发一个属性更改,该属性更改会增加标签的值。

Whenever you press the stop button, just cancel the current swing worker. 每当您按下停止按钮时,只需取消当前的挥杆工作人员即可。 When you press the start button, just execute() the swing worker 当您按下开始按钮时,只需execute() swing工作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM