I want to create a system that has a time in/time out feature.
I tried this code as a trial before including the the feature to my system:
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Time extends JFrame implements ActionListener {
Date now = new Date();
private JLabel time;
private JButton getTime;
private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss");
public Time()
{
setLayout(null);
setSize(500,300);
JLabel time = new JLabel("00:00:00");
time.setSize(100,100);
time.setLocation(40,40);
JButton getTime = new JButton("GET TIME");
getTime.addActionListener(this);
getTime.setSize(90,30);
getTime.setLocation(90,70);
Container pane = getContentPane();
pane.add(time);
pane.add(getTime);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "GET TIME")
{
JOptionPane.showMessageDialog(null, "Time "+dateFormatter.format(now),
"Time.",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
new Time();
}
}
It gets the current time, but it still gives the same time when I click again the button. It only changes when I close the UI.
Canned answer:
Don’t compare Strings using
==. Use theequals(...)or theequalsIgnoreCase(...)method instead. Understand that == checks if the two objects are the same which is not what you’re interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that’s what matters here. So instead ofdo,
or,
Uncanned answer:
So in other words, change this:
to this:
or better still, use String constants.
Also, you’ll want to avoid using null layout in your Swing GUI’s as you’ll find out that that is the hard way to lay things out. Much easier and more robust is to use layout managers.
Edit
You need to get the time from within your actionPerformed method. In other words,
nowshould be created in the actionPerformed method before calling the JOptionPane.