Hello i have problem on how to convert my time into currency when i logout a customer in a computer timer server. commonly seen on internet café which they time the customer's pc and when the customer will logout the client server will display the amount of time he/she consumed and display how much would he/she be pay off.
public ZipTimer() {
lblTimer1 = new JLabel("New label");
lblTimer1.setFont(new Font("Segoe UI Light", Font.PLAIN, 18));
lblTimer1.setBounds(103, 208, 190, 50);
contentPane.add(lblTimer1);
timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTimer();
seconds++;
}
});
btnStart1 = new JButton("Start");
btnStart1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(timer.isRunning()) {
timer.stop();
btnStart1.setText("Start");
}else {
timer.start();
btnStart1.setText("Stop");
}
}
});
private void setTimer() {
Date d = new Date(seconds * 1000L);
String time = df.format(d);
lblTimer1.setText(time);
Here you are an approach, obviously it has a lot of things to improve (Validation of the events, set the results in only one label, etc) but for studying purposes I think it's ok.
package com.stackoverflow.time;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private long startTime = 0;
private long stopTime = 0;
private static double factor = .01;
public SwingControlDemo() {
prepareGUI();
}
public static void main(String[] args) {
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showButtonDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Time is money");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.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());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showButtonDemo() {
headerLabel.setText("Click the button to start monetizing your time");
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start();
statusLabel.setText("Started");
}
});
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stop();
long elapsed = getElapsedSeconds();
double debt = convertToMoney(elapsed);
statusLabel.setText("Finished. Elapsed " + elapsed + " seconds. You owe us: " + debt + " dollars");
}
});
controlPanel.add(startButton);
controlPanel.add(stopButton);
mainFrame.setVisible(true);
}
public void start() {
this.startTime = System.currentTimeMillis();
}
public void stop() {
this.stopTime = System.currentTimeMillis();
}
public long getElapsedSeconds() {
long elapsed;
elapsed = (stopTime - startTime);
return (elapsed / 1000) % 60;
}
//Here you apply your conversion, you must change the factor
public double convertToMoney(long elapsedTime) {
return elapsedTime * factor;
}
}
Related
I'm trying to make a timer that will count up from 00h:00m:00s, with the ability to pause and restart the count from its current time.
Heres the solution I currently have: It will always restart the timer from 0 instead of continuing where it left off. Also, for another inexplicable reason, the hours always display as 07 instead of 00. Does anyone know how I could fix these issues, to have it start counting up from its previous value, and display the correct amount of hours elapsed?
private final SimpleDateFormat date = new SimpleDateFormat("KK:mm:ss");
private long startTime = 0;
private final ClockListener clock = new ClockListener();
private final Timer normalTimer = new Timer(53, clock);
startTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(startTime == 0) {
startTime = System.currentTimeMillis();
}
else {
startTime += (System.currentTimeMillis() - startTime);
}
normalTimer.start();
}
});
stopTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalTimer.stop();
}
});
private void updateClock(){
Date elapsed = new Date(System.currentTimeMillis() - startTime);
timerText.setText(date.format(elapsed));
}
private class ClockListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
updateClock();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Your code wasn't runnable, so I created the following GUI.
When you press the "Start" button, the timer starts counting. 37 seconds.
2 minutes, 7 seconds.
1 hour, 6 minutes, 11 seconds.
Pressing the "Pause button pauses the count. Pressing the "Restart" button resumes the count. You can pause and resume the count as many times as you want.
Pressing the "Stop" button stops the counter. You can press the "Reset" button to reset the counter before starting again.
Explanation
When creating a Swing application, using the model-view-controller (MVC) pattern helps to separate your concerns and allows you to focus on one part of the application at a time.
Creating the application model made creating the GUI much easier. The application model is made up of one or more plain Java getter/setter classes.
The CountupTimerModel class keeps long fields to hold the duration in milliseconds and the previous duration. This way, I don't have to pause and restart the Swing Timer.
The duration is the difference between the current time and the start time. I use the System.currentTimeMillis() method to calculate the duration.
The GUI is fairly straightforward.
I made the JButton ActionListeners lambdas. I made the TimerListener a separate class to move the code out of that particular lambda.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CountupTimerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CountupTimerGUI());
}
private final CountupTimerModel model;
private JButton resetButton, pauseButton, stopButton;
private JLabel timerLabel;
public CountupTimerGUI() {
this.model = new CountupTimerModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Countup Timer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createDisplayPanel(), BorderLayout.NORTH);
frame.add(createButtonPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.BOLD, 48f);
timerLabel = new JLabel(model.getFormattedDuration());
timerLabel.setFont(font);
panel.add(timerLabel);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.PLAIN, 16f);
resetButton = new JButton("Reset");
resetButton.setFont(font);
panel.add(resetButton);
resetButton.addActionListener(event -> {
model.resetDuration();
timerLabel.setText(model.getFormattedDuration());
});
pauseButton = new JButton("Restart");
pauseButton.setFont(font);
panel.add(pauseButton);
pauseButton.addActionListener(event -> {
String text = pauseButton.getText();
if (text.equals("Pause")) {
model.pauseTimer();
pauseButton.setText("Restart");
} else {
model.startTimer();
pauseButton.setText("Pause");
}
});
Timer timer = new Timer(200,
new CountupListener(CountupTimerGUI.this, model));
stopButton = new JButton("Start");
stopButton.setFont(font);
panel.add(stopButton);
stopButton.addActionListener(event -> {
String text = stopButton.getText();
if (text.equals("Start")) {
model.resetDuration();
model.startTimer();
timer.start();
resetButton.setEnabled(false);
stopButton.setText("Stop");
} else {
model.stopTimer();
timer.stop();
resetButton.setEnabled(true);
stopButton.setText("Start");
}
});
Dimension d = getLargestJButton(resetButton, pauseButton, stopButton);
resetButton.setPreferredSize(d);
pauseButton.setPreferredSize(d);
stopButton.setPreferredSize(d);
pauseButton.setText("Pause");
return panel;
}
private Dimension getLargestJButton(JButton... buttons) {
Dimension largestDimension = new Dimension(0, 0);
for (JButton button : buttons) {
Dimension d = button.getPreferredSize();
largestDimension.width = Math.max(largestDimension.width, d.width);
largestDimension.height = Math.max(largestDimension.height,
d.height);
}
largestDimension.width += 10;
return largestDimension;
}
public JButton getResetButton() {
return resetButton;
}
public JButton getPauseButton() {
return pauseButton;
}
public JButton getStopButton() {
return stopButton;
}
public JLabel getTimerLabel() {
return timerLabel;
}
public class CountupListener implements ActionListener {
private final CountupTimerGUI view;
private final CountupTimerModel model;
public CountupListener(CountupTimerGUI view, CountupTimerModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
model.setDuration();
view.getTimerLabel().setText(model.getFormattedDuration());
}
}
public class CountupTimerModel {
private boolean isRunning;
private long duration, previousDuration, startTime;
public CountupTimerModel() {
resetDuration();
}
public void resetDuration() {
this.duration = 0L;
this.previousDuration = 0L;
this.isRunning = true;
}
public void startTimer() {
this.startTime = System.currentTimeMillis();
this.isRunning = true;
}
public void pauseTimer() {
setDuration();
this.previousDuration = duration;
this.isRunning = false;
}
public void stopTimer() {
setDuration();
this.isRunning = false;
}
public void setDuration() {
if (isRunning) {
this.duration = System.currentTimeMillis() - startTime
+ previousDuration;
}
}
public String getFormattedDuration() {
int seconds = (int) ((duration + 500L) / 1000L);
int minutes = seconds / 60;
int hours = minutes / 60;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours);
builder.append(":");
}
minutes %= 60;
if (hours > 0) {
builder.append(String.format("%02d", minutes));
builder.append(":");
} else if (minutes > 0) {
builder.append(minutes);
builder.append(":");
}
seconds %= 60;
if (hours > 0 || minutes > 0) {
builder.append(String.format("%02d", seconds));
} else {
builder.append(seconds);
}
return builder.toString();
}
}
}
I have programmed a simple stopwatch with three functionalities. First, I have a start button to begin the stopwatch , a pause button to pause the stopwatch and finally a reset button to reset the entire stopwatch.
When I hit the pause button, the stopwatch pauses, say at 10.0 seconds. When I resume the stopwatch (pressing the Start button again), the stopwatch doesn't resume from 10.0 seconds onwards. It resumes from the amount of time I paused and the current time. For example, if I paused for 5 seconds and hit resume, the stopwatch goes from 15.0 seconds onwards.
I am aware there isn't a actual pause function in Swing.Timer. Would there be a way to tackle this so the stopwatch resumes normally?
Any suggestion would be appreciated.
Code:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.Instant;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiStopwatch {
public static void main(String[] args) {
JFrame frame = new JFrame("Stopwatch");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setLayout(null);
JButton startbtn = new JButton("START");
JButton pausebtn = new JButton("PAUSE");
JButton reset = new JButton("RESET");
JLabel time = new JLabel("Time shows here");
panel.add(startbtn);
panel.add(pausebtn);
panel.add(reset);
panel.add(time);
startbtn.setBounds(50, 150, 100, 35);
pausebtn.setBounds(50, 200, 100, 35);
reset.setBounds(50, 250, 100, 35);
time.setBounds(50, 350, 100, 35);
time.setBackground(Color.black);
time.setForeground(Color.red);
frame.add(panel);
Timer timer = new Timer(1,new ActionListener() {
Instant start = Instant.now();
#Override
public void actionPerformed(ActionEvent e) {
time.setText( Duration.between(start, Instant.now()).getSeconds() + ":" + Duration.between(start, Instant.now()).getNano() );
}
});
startbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
pausebtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
}
});
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
time.setText("0:0");
}
});
Conceptually, the idea is, you want to keep track of the "total running" of the stop watch, this is, all the total duration it has been active.
There's a number of ways you might achieve this, one might be to simply keep a running total which is only updated when the stop watch is stopped or paused. The "duration" of the stop watch is then a sum of the "current duration" of the "current" cycle and the "total previous" duration
Something like...
public class StopWatch {
private LocalDateTime startTime;
private Duration totalRunTime = Duration.ZERO;
public void start() {
startTime = LocalDateTime.now();
}
public void stop() {
Duration runTime = Duration.between(startTime, LocalDateTime.now());
totalRunTime = totalRunTime.plus(runTime);
startTime = null;
}
public void pause() {
stop();
}
public void resume() {
start();
}
public void reset() {
stop();
totalRunTime = Duration.ZERO;
}
public boolean isRunning() {
return startTime != null;
}
public Duration getDuration() {
Duration currentDuration = Duration.ZERO;
currentDuration = currentDuration.plus(totalRunTime);
if (isRunning()) {
Duration runTime = Duration.between(startTime, LocalDateTime.now());
currentDuration = currentDuration.plus(runTime);
}
return currentDuration;
}
}
Okay, so start and stop are essentially the same as pause and resume, but you get the point.
And, a runnable example...
Now, this example runs a Swing Timer constantly, but the StopWatch can paused and resumed at any time, the point is to demonstrate that the StopWatch is actually working correctly ;)
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalDateTime;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) throws InterruptedException {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JButton btn;
private StopWatch stopWatch = new StopWatch();
private Timer timer;
public TestPane() {
label = new JLabel("...");
btn = new JButton("Start");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
add(btn, gbc);
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(Long.toString(stopWatch.getDuration().getSeconds()));
}
});
timer.start();
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (stopWatch.isRunning()) {
stopWatch.pause();
btn.setText("Start");
} else {
stopWatch.resume();
btn.setText("Pause");
}
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class StopWatch {
private LocalDateTime startTime;
private Duration totalRunTime = Duration.ZERO;
public void start() {
startTime = LocalDateTime.now();
}
public void stop() {
Duration runTime = Duration.between(startTime, LocalDateTime.now());
totalRunTime = totalRunTime.plus(runTime);
startTime = null;
}
public void pause() {
stop();
}
public void resume() {
start();
}
public void reset() {
stop();
totalRunTime = Duration.ZERO;
}
public boolean isRunning() {
return startTime != null;
}
public Duration getDuration() {
Duration currentDuration = Duration.ZERO;
currentDuration = currentDuration.plus(totalRunTime);
if (isRunning()) {
Duration runTime = Duration.between(startTime, LocalDateTime.now());
currentDuration = currentDuration.plus(runTime);
}
return currentDuration;
}
}
}
So, if I click the button exists in First Frame, then the number would increase in JTextField exists in another Second Frame.
The First Frame contains the JButton and the Second Frame contains the JTextField.
Please Help.
Try below source code:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class FirstFrame extends JFrame {
private static final long serialVersionUID = 1L;
private SecondFrame secondFrame;
private boolean flag = new Boolean(false);
private volatile Integer number;
#SuppressWarnings("unused")
private SwingWorker<Void, Void> swingWorker;
public FirstFrame() {
init();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FirstFrame();
}
});
}
private void init() {
setTitle("First Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(2, 1));
setBounds(500, 300, 250, 110);
final JButton increaseBtn = new JButton("Increase Number");
final JButton start = new JButton("Start");
final JButton stop = new JButton("Stop");
stop.setEnabled(false);
JPanel panel = new JPanel();
increaseBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
if (!flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = true;
startContinuousIncreasing();
start.setEnabled(false);
stop.setEnabled(true);
increaseBtn.setEnabled(false);
}
});
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
flag = false;
stop.setEnabled(false);
start.setEnabled(true);
increaseBtn.setEnabled(true);
}
});
getContentPane().add(increaseBtn);
getContentPane().add(panel);
panel.add(start);
panel.add(stop);
setVisible(true);
secondFrame = SecondFrame.getSecondFrame();
increaseBtn.requestFocus();
}
private void startContinuousIncreasing() {
swingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
while (flag) {
number = secondFrame.getNumber();
secondFrame.setNumber(number + 1);
}
return null;
}
};
swingWorker.execute();
}
}
class SecondFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static Integer number;
private JTextField textField;
private static SecondFrame secondFrame;
private SecondFrame() {
init();
}
public synchronized static SecondFrame getSecondFrame() {
if (secondFrame == null)
secondFrame = new SecondFrame();
return secondFrame;
}
private void init() {
setTitle("Second Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1, 1));
setBounds(500, 412, 250, 70);
number = new Integer(0);
textField = new JTextField(String.valueOf(number));
textField.setFont(new Font("Dialog", Font.BOLD + Font.ITALIC, 22));
getContentPane().add(textField);
setVisible(true);
}
public synchronized Integer getNumber() {
return number;
}
public synchronized void setNumber(Integer num) {
try {
number = num;
this.textField.setText(String.valueOf(number));
} catch (NumberFormatException nfe) {
number = 0;
this.textField.setText(String.valueOf(number));
}
}
}
I guess you have created a Static variable. Static variables share the value across all instances of a class. That might be one of the answer.
Hopes it answered your questions. Let me know if it's not the answer. Yippee!!
I'm trying to make a GUI timer without using javax.swing.Timer(kind of a strange task), but I am having trouble making it work. It's supposed to sleep the thread for 1 second, add 1 to seconds, and repeat(infinitely). When I run my program, the icon shows up, but the window does not appear. I'm guessing my error is in the Thread.sleep(1000); line or in that area, but I'm not sure why it doesn't work. Is Thread.sleep(millis)not compatible with swing applications? Do I have to multithread? Here's my program:
import java.awt.*;
import javax.swing.*;
public class GUITimer extends JFrame {
private static final long serialVersionUID = 1L;
private int seconds = 0;
public GUITimer() {
initGUI();
pack();
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initGUI(){
JLabel title = new JLabel("Timer");
Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
title.setFont(titleFont);
title.setHorizontalAlignment(JLabel.CENTER);
title.setBackground(Color.BLACK);
title.setForeground(Color.WHITE);
title.setOpaque(true);
add(title, BorderLayout.NORTH);
JLabel timeDisplay = new JLabel(Integer.toString(seconds));//this label shows seconds
add(timeDisplay, BorderLayout.CENTER);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
seconds++;
initGUI();
}
public static void main(String[] args) {
try {
String className = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
}
catch (Exception e) {}
EventQueue.invokeLater(new Runnable() {
public void run() {
new GUITimer();
}
});
}
}
EDIT:
I noticed when I print seconds in my method initGUI() to console, it prints them incrementally by one second correctly. So when it looks like:
private void initGUI() {
System.out.println(seconds);
//...
it prints the value of seconds after every second(How the JLabel should). This shows that my loop is working fine, and my Thread.sleep(1000) is OK also. My only problem now, is that the frame is not showing up.
Your main window does not appear, because you called infinite recursion inside constructor. GUITimer will not be created and this lock main thread.
You need use multithreading for this aim. Main thread for drawing time, second thread increment and put value to label
For example:
import javax.swing.*;
import java.awt.*;
public class GUITimer extends JFrame
{
private static final long serialVersionUID = 1L;
private int seconds = 0;
private Thread timerThread;
private JLabel timeDisplay;
public GUITimer()
{
initGUI();
pack();
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initGUI()
{
JLabel title = new JLabel("Timer");
Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
title.setFont(titleFont);
title.setHorizontalAlignment(JLabel.CENTER);
title.setBackground(Color.BLACK);
title.setForeground(Color.WHITE);
title.setOpaque(true);
add(title, BorderLayout.NORTH);
timeDisplay = new JLabel(Integer.toString(seconds));//this label shows seconds
add(timeDisplay, BorderLayout.CENTER);
}
public void start()
{
seconds = 0;
timerThread = new Thread(new Runnable()
{
#Override
public void run()
{
while(true)
{
timeDisplay.setText(Integer.toString(seconds++));
try
{
Thread.sleep(1000L);
}
catch(InterruptedException e) {}
}
}
});
timerThread.start();
}
public void stop()
{
timerThread.interrupt();
}
public static void main(String[] args)
{
try
{
GUITimer timer = new GUITimer();
timer.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The core issue is, you're blocking the UI by continuously calling initGUI, which will eventually fail with a StackOverFlowException, as the method calls never end
The preference would be to use a Swing Timer, but since you've stated you don't want to do that, a better solution would be to use a SwingWorker, the reason for this - Swing is NOT thread safe and SwingWorker provides a convenient mechanism for allowing us to update the UI safely.
Because both Swing Timer and Thead.sleep only guarantee a minimum delay, they are not a reliable means for measuring the passage of time, it would be better to make use of Java 8's Date/Time API instead
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label = new JLabel("00:00:00");
private TimeWorker timeWorker;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
JButton button = new JButton("Start");
add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timeWorker == null) {
timeWorker = new TimeWorker(label);
timeWorker.execute();
button.setText("Stop");
} else {
timeWorker.cancel(true);
timeWorker = null;
button.setText("Start");
}
}
});
}
}
public class TimeWorker extends SwingWorker<Void, Duration> {
private JLabel label;
public TimeWorker(JLabel label) {
this.label = label;
}
#Override
protected Void doInBackground() throws Exception {
LocalDateTime startTime = LocalDateTime.now();
Duration totalDuration = Duration.ZERO;
while (!isCancelled()) {
LocalDateTime now = LocalDateTime.now();
Duration tickDuration = Duration.between(startTime, now);
publish(tickDuration);
Thread.sleep(500);
}
return null;
}
#Override
protected void process(List<Duration> chunks) {
Duration duration = chunks.get(chunks.size() - 1);
String text = format(duration);
label.setText(text);
}
public String format(Duration duration) {
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long millis = duration.toMillis();
long seconds = (long)(millis / 1000.0);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
}
}
Here is my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class wind extends JFrame implements ComponentListener, MouseListener
{
JButton button;
JLabel label;
public wind()
{
// initialise instance variables
setTitle("My First Window!");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.addComponentListener(this);
content.addMouseListener(this);
label = new JLabel("My First Window");
content.add(label);
label.addComponentListener(this);
button = new JButton("Click If You Wish To Live!");
button.addMouseListener(this);
content.add(button)
setContentPane(content);
}
public void componentHidden(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Hidden!");
}
public void componentShown(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Shown!");
}
public void componentResized(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Resized!");
}
public void componentMoved(ComponentEvent e){
try{wait(100);}
catch(InterruptedException error){}
button.setText("Moved!");
}
public void mouseExited(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Exited!");
}
public void mouseEntered(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Entered!");
}
public void mousePressed(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("pressed at: "+e.getX()+" "+e.getY());
}
public void mouseReleased(MouseEvent e){
try{wait(100);}
catch(InterruptedException error){}
label.setText("Released!");
label.setLocation(e.getX(), e.getY());
}
public void mouseClicked(MouseEvent e){}
}
It won't respond to the mouse or window re-sizing, hiding, or moving. Furthermore the button is not being displayed. fixed! I am just starting to learn about Java's JFrame and other graphics so I have no idea what's wrong with my code, although I suspect it has something to do with the way I made the button and added the listeners to the objects. Could someone please explain why it does this, and how to fix it. Thank you in advance!
Your problem is that you are using the wait function not correctly. Try to use the class javax.swing.Timer also known as a Swing Timer for delays in Swing programs, for simple animations and for repetitive actions. For more information see this example on stackoverflow: Java Wait Function
One possible way to add a ActionListener to a JButton:
// You are adding an ActionListener to the button
//Using the method addActionListener and a anonymous inner class
button.addActionListener(new ActionListener() {//anonymous inner class
#Override
public void actionPerformed(ActionEvent arg0)
{
button.setText("Text modified by an event called ActionEvent!");
}
});
I decided to play with similar code and came up with this bit of code that tries to show the state of things in a status bar at the bottom:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
#SuppressWarnings({ "serial"})
// so the compiler won't complain
public class MyWindPanel extends JPanel {
private static final int PREF_W = 1200;
private static final int PREF_H = 600;
private static final String MOUSE_LOCATION = "Mouse Location [%04d, %04d]";
private static final String COMPONENT_STATE = "Component: %-15s";
private static final String TIMER_LABEL = "Elapsed Time: %02d:%02d:%02d:%03d";
private static final int TIMER_DELAY = 20;
private static final String MOUSE_STATE = "Mouse State: %-15s";
public static final String BUTTON_TEXT = "Set MyWindPanel %s";
private JLabel mouseLocation = new JLabel(
String.format(MOUSE_LOCATION, 0, 0));
private JLabel mouseState = new JLabel(String.format(MOUSE_STATE, ""));
private JLabel componentState = new JLabel(
String.format(COMPONENT_STATE, ""));
private JLabel timerLabel = new JLabel(
String.format(TIMER_LABEL, 0, 0, 0, 0));
private long startTime = System.currentTimeMillis();
private Action buttonAction = new MyButtonAction(String.format(BUTTON_TEXT, "Invisible"));
private JPanel statusPanel;
public MyWindPanel() {
setBackground(Color.pink);
Font font = new Font(Font.MONOSPACED, Font.BOLD, 14);
mouseLocation.setFont(font);
mouseState.setFont(font);
componentState.setFont(font);
timerLabel.setFont(font);
statusPanel = new JPanel();
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.LINE_AXIS));
statusPanel.add(mouseLocation);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(mouseState);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(componentState);
statusPanel.add(Box.createHorizontalStrut(25));
statusPanel.add(timerLabel);
new Timer(TIMER_DELAY, new TimerListener()).start();
MouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseMotionListener(myMouseAdapter);
addMouseListener(myMouseAdapter);
addComponentListener(new MyComponentListener());
setLayout(new BorderLayout());
// add(statusPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public Action getButtonAction() {
return buttonAction;
}
public JComponent getStatusPanel() {
return statusPanel;
}
private class TimerListener implements ActionListener {
private static final int SECONDS_PER_MIN = 60;
private static final int MSEC_PER_SEC = 1000;
private static final int MIN_PER_HOUR = 60;
#Override
public void actionPerformed(ActionEvent evt) {
if (!MyWindPanel.this.isDisplayable()) {
((Timer) evt.getSource()).stop(); // so timer will stop when program
// over
}
long currentTime = System.currentTimeMillis();
long diff = currentTime - startTime;
int hours = (int) (diff / (MIN_PER_HOUR * SECONDS_PER_MIN * MSEC_PER_SEC));
int minutes = (int) (diff / (SECONDS_PER_MIN * MSEC_PER_SEC))
% MIN_PER_HOUR;
int seconds = (int) ((diff / MSEC_PER_SEC) % SECONDS_PER_MIN);
int mSec = (int) diff % MSEC_PER_SEC;
timerLabel.setText(String.format(TIMER_LABEL, hours, minutes, seconds,
mSec));
}
}
private class MyComponentListener extends ComponentAdapter {
#Override
public void componentHidden(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Hidden"));
}
#Override
public void componentMoved(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Moved"));
}
#Override
public void componentResized(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Resized"));
}
#Override
public void componentShown(ComponentEvent e) {
componentState.setText(String.format(COMPONENT_STATE, "Shown"));
}
}
private class MyButtonAction extends AbstractAction {
public MyButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
boolean visible = MyWindPanel.this.isVisible();
String text = visible ? "Visible" : "Invisible";
((AbstractButton) e.getSource()).setText(String.format(BUTTON_TEXT, text));
MyWindPanel.this.setVisible(!MyWindPanel.this.isVisible());
Window win = SwingUtilities.getWindowAncestor(MyWindPanel.this);
win.revalidate();
win.repaint();
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
}
#Override
public void mouseDragged(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Dragged"));
mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
}
public void mousePressed(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Pressed"));
};
public void mouseReleased(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Released"));
};
public void mouseEntered(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Entered"));
};
public void mouseExited(MouseEvent e) {
mouseState.setText(String.format(MOUSE_STATE, "Exited"));
};
}
private static void createAndShowGui() {
MyWindPanel mainPanel = new MyWindPanel();
JPanel topPanel = new JPanel();
topPanel.add(new JButton(mainPanel.getButtonAction()));
JFrame frame = new JFrame("MyWind");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.getContentPane().add(topPanel, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel.getStatusPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}