且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java-更新在Swing中制作的GUI

更新时间:2023-12-04 16:21:46

只需使用 ActionListener 为您执行此操作.给我十分钟的工作代码示例:-)

Simply use a javax.swing.Timer, and make one ActionListener, to do this thing for you . Give me ten mins for a working code example :-)

这是一个示例程序,可提供进一步的帮助:

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

如果您希望计数器再次恢复为0,则在停止计时器时,只需添加

If you want the counter to again revert back to 0, on Stopping the Timer, simply add

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

这是buttonActionactionPerformed(...)方法的一部分.