Search code examples
javaswingjframejfilechoosertitlebar

JFrame setTitle not working


Not sure why this is occurring, but when I try to change the title on my JFrame it's not updating. The JFrame is static, and I call it by saying:

Assets.frame.setTitle("test");

I have one block of code in which I pass in a file's name, and it seems to work, as when I print out Assets.frame.getTitle(), it prints out what I want the title to be. But on the actual JFrame it doesn't change the title. I call the method in other parts of my program too, and it seems to work there. Is there some special character that could cause the method to not update the actual frame that I don't know about?

Edit:

What I'm trying to do (open a file)

public static void open() {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    int result = chooser.showOpenDialog(Assets.frame);
    if (result == JFileChooser.APPROVE_OPTION) {
        MyFile myFile = new MyFile(chooser.getSelectedFile().getPath());
        Main.setTitle(Constants.current_file.getName().substring(0, mapFile.getName().indexOf('.')));
    }
}

and the Main.setTitle() method is:

public static void setTitle(String title) {
    Assets.frame.setTitle(title + " - " + "My Program");
}

The frame is defined and instantiated near program execution, and the open method is called when a JButton is pressed. This is the only JFrame I have in the project, and it is in use until the program is exited.

I don't know how reproducible it is, as it works when I run another similar method that has a call to Main.setTitle() too. It's just this one instance where it doesn't work.


Solution

  • What I'm trying to do (open a file)

    Then maybe take a look at the section from the Swing tutorial on How to Use File Choosers as a starting point. It will show you how to better structure your program so you don't need static variables and methods everywhere. You can download the demo code and play with it and then modify it for your needs.

    Then in your logic if you want to update the title of your frame then you can use the SwingUtilities.windowForComponent(...) method to get the frame your components are added to.

    The code you posted still doesn't help us understand the design of your code or the context of how the method is invoked, so why can't give you a specific answer to your problem. That is why you were asked to provide a "runnable example". But I suggest you restructure you program first.