I was thinking if it would be possible to create a JFrame, and make the title of it to change, such as make the title work as a counter that will display some text like:

The window was opened for 1 second.
The window was opened for 2 second.
The window was opened for 3 second.
The window was opened for 4 second.
The window was opened for 5 second.
The window was opened for 6 second.
The window was opened for 7 second.

Here is the code I have so far:

import javax.swing.JFrame;

class WindowFrame {

    public static void main (String args[]){
    JFrame myWindow = new JFrame();

    // 1.  declare and initialise variables
        int counter = 1;

        // 2.  now do the while loop
        while(counter < 5000 )
        {
            System.out.println("counter  is equal to " + counter);
            // 3.  add 1 to the value of counter
        counter = counter + 1 ;
        }

        // 4.  the while loop has finished,
        //so program continues on to here
        System.out.println("Goodbye");


    String myTitle = (counter);

    myWindow.setTitle( myTitle);
    myWindow.setSize(777, 333);
    myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myWindow.setVisible(true);
    }
}

But when I compile there is an error:

WindowFrame.java:24: error: incompatible types
    String myTitle = (counter);
                      ^
  required: String
  found:    int
1 error

Is it possible for the requirement of String not to be fulfilled? Instead use an int?

Dani AI

Generated

The compile error is just a type mismatch (setTitle needs a String), but the real problem here is the tight loop and threading. built the counter in a blocking loop so the frame either only gets the final title or never gets a chance to paint. moved setTitle into the loop, which compiles, but that still blocks or races with Swing. was right to point at using a Swing timer and creating the GUI on the Event Dispatch Thread (EDT).

Use EventQueue.invokeLater to create the frame and a javax.swing.Timer to tick every 1000 ms; the Timer runs on the EDT so updating the title is safe. Example:

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.atomic.AtomicInteger;

public class WindowFrame {
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        final JFrame frame = new JFrame("Starting");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(777, 333);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        final AtomicInteger seconds = new AtomicInteger(1);
        Timer timer = new Timer(1000, new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            frame.setTitle("The window was opened for " + seconds.getAndIncrement() + " second(s).");
          }
        });
        timer.setInitialDelay(0);
        timer.start();
      }
    });
  }
}

Troubleshooting notes: if the window never appears, check package declarations (file location and how you run the class), ensure setVisible is called on the EDT, and avoid Thread.sleep or long loops on the EDT. For heavy background work use SwingWorker and publish progress to the EDT.

Recommended Answers

All 5 Replies

Hi you've almost had it correct. :)
I modified your code a little bit and think I made it work.
Here is the bad boy:

package test;

import javax.swing.JFrame;
public class WindowFrame {
    public static void main (String args[]){
    JFrame myWindow = new JFrame();
    // 1.  declare and initialise variables
        int counter = 1;
        // 2.  now do the while loop
        myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myWindow.setVisible(true);
        myWindow.setSize(777, 333);
        while(counter < 5001 )
        {
            String myTitle = ""+counter;
            myWindow.setTitle( myTitle);
            System.out.println("counter  is equal to " + counter);
            // 3.  add 1 to the value of counter
            counter++;
        }
        // 4.  the while loop has finished,
        //so program continues on to here
        System.out.println("Goodbye");



    }
}
commented: No explanation, just code to copy. -3

You can convert an int to String with the String.valueOf(int i) method, but you will often see people using string concatenation because Java will find a way to convert any non-string values to string in order to perform the concatenation. That's the method Seldar hid carefully in his undocumented code (line 15) - concatenating the int with a string value of "" to force conversion of the int to string.

More seriously, when you change the title of a JFrame 5000 times in some tiny fraction of a second, what exactly do you expect to see on the screen when Swing finally gets its slice of CPU time?
...and before someone with limited Java knowledge suggests wait(1000) or sleep(1000), have a look at javax.swing.Timer.

Appologies for the poor quality of my previous post, I had the best of intentions.

Seldar, how come when I replaced my old code with the new one you provided, the proogram indeed compiles, but when I try to run it, no window shows up? How can this issue be resolved?

Hmm, I honestly don't know. The code works just fine for me.
If I were you, I would remove the package declaration at the very top of the file. Then create a new java file called WindowFrame and paste the code in.
Hope this helps and sorry for the delayed reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.