Change JFrame name from another class

I have two classes: one class AnalogClock and one class MainInterface.

I created the timeChanged method in the AnalogClock class, and it is called every time the time has changed. My AnalogClock is basically a patterned JPanel. In MainInterface, I set up a JFrame and add an object to my AnalogClock.

Is it possible to change the title of my window whenever "timeChanged" is called? I tried to use getParent() or getRootParent() , but they do not recognize setTitle() .

+4
source share
3 answers

Use the getWindowAncestor method from SwingUtilities .

 //This gives you the first Window Object that contains the panel component Window window = SwingUtilities.getWindowAncestor(panel); //Cast it to JFrame JFrame frame = (JFrame) window; //Now, change the title frame.setTitle("New Title"); 
+5
source

The easiest way is to pass the JFrame link to the JPanel and call setTitle() . Using getParent() , you specify the correct type of the returned Container , and then as soon as you find your JFrame reference, say it and call setTitle .

I usually do this according to the first sentence.

+1
source

It looks like timeChanged should be in your MainInterface class, because timeChanged should refer to both AnalogClock and JFrame . The reason is because your AnalogClock probably should not be associated with your JFrame .

0
source

All Articles