【发布时间】:2020-06-27 20:11:18
【问题描述】:
程序应该做什么: 有一个 OK BUTTON:每 1000 毫秒输出一次用户时间 有一个 CLOSE 按钮:停止 OK BUTTON 并且没有输出
是否可以让我的按钮“确定”的动作侦听器在没有 while 循环的情况下继续运行?我正在努力做到这一点,这样你就可以点击一次,而其他所有按钮仍然可以在我的 JFrame 中工作。
我的意思是,每当您将 while 循环放在动作侦听器中时,它都会忽略对不同按钮的所有输入,除非我完全删除程序,否则我无法停止它。那么,是否可以让我的程序像一个while循环一样继续运行,但可以通过我在程序中制作的“关闭”按钮来停止?
package com.mc.main;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GetTime {
private JFrame frame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
static String usersTimeNow;
public GetTime() {
prepareGUI();
}
private void prepareGUI(){
frame = new JFrame("Java Swing");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 1));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
frame.add(headerLabel);
frame.add(controlPanel);
frame.add(statusLabel);
frame.setVisible(true);
}
private void showButtonDemo(){
boolean isStopped = false;
headerLabel.setText("Button Demo");
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getUsersTime();
sleepDelay();
}
});
controlPanel.add(okButton);
frame.setVisible(true);
JButton closeButton = new JButton("CLOSE");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
});
controlPanel.add(closeButton);
frame.setVisible(true);
}
public void getUsersTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
usersTimeNow = dtf.format(now);
statusLabel.setText(usersTimeNow);
}
public void sleepDelay() {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
GetTime test = new GetTime();
test.showButtonDemo();
}
}
【问题讨论】:
标签: java swing debugging concurrency jframe