Search code examples
javaswingjframejpaneltitlebar

Change Title of JFrame from other Class


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

I've created a timeChanged method in the AnalogClock class and it gets called whenever the time has changed. My AnalogClock is basically a JPanel with a drawing. In MainInterface I setup a JFrame and add an Object of 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 don't recognise setTitle().


Solution

  • Use 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");