Bogdan Bogdan - 10 months ago 78
Java Question

Jlabel Clock java swing

I am making a program that displays the clock and zime zones for a country selected.
The time is displayed into a jLabel when the button is clicked.
The problem is that when I click once the time is displayed in the label ,but when I click second the time is rewritten to the existent jlabel date (text).

How can I display the date without to be rewritten.
If click more times, the time won't be readable.

Here Is my code:

public class Window extends JFrame {

JLabel title, text,date1,label1;
JTextField country;
JButton search;

private static final String DATE_FORMAT = "dd-M-yyyy hh:mm:ss a";

public Window(){


title = new JLabel ("Genesys Time");
add (title);

text = new JLabel("Continent/Country:");


country = new JTextField();
add (country);


search = new JButton("Cauta");
add (search);


search.addActionListener(new csearch());


class csearch implements ActionListener{
public void actionPerformed(ActionEvent event){
//WindowTime wt = new WindowTime(null);

date1 = new JLabel();

SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// String dateInString = "02-11-2016 12:06:55 AM";
// Date date = formatter.parse(dateInString);
TimeZone tz = TimeZone.getDefault();

// From TimeZone Asia/Singapore
System.out.println("TimeZone : " + tz.getID() + " - " + tz.getDisplayName());
System.out.println("TimeZone : " + tz);
System.out.println("Date (Ro - UTC+02:00) : " + formatter.format(date));

// To TimeZone America/New_York
SimpleDateFormat sdfAmerica = new SimpleDateFormat(DATE_FORMAT);
SimpleDateFormat sdfParis = new SimpleDateFormat(DATE_FORMAT);
DateTime dt = new DateTime(date);
DateTimeZone dtZone = DateTimeZone.forID(country.getText());
DateTime dtus = dt.withZone(dtZone);
TimeZone tzInAmerica = dtZone.toTimeZone();
Date dateInAmerica = dtus.toLocalDateTime().toDate(); //Convert to LocalDateTime first




} }


Could anyone help me?

Answer Source

If click more times, the time won't be readable

The problem is that you keep creating new JLabels and add them to the frame so the text of each label paints over top of one another. Don't create a new JLabel every time you click the button.

Instead create the label and add it to the frame when you create the frame.

Then you just use:


to change the text of the label.

Also, you should NOT be using a null layout. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.