What the program is supposed to do: Has a OK BUTTON: outputs the users time every 1000ms Has a CLOSE button: stops the OK BUTTON and have no outputs
Is it possible to make my actionlistener for my button "Ok" to keep on going without a while loop? I'm trying to make it so u can click once, and every other button can still work in my JFrame.
What i mean by this is, whenever you place the while loop inside the action listener, it ignores all inputs to a different button, and i can't stop it unless i completely delete the program. So, is it possible just to make my program keep running as if it was a while loop but can be stopped with the "Close" button i had made in the program?
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();
}
}