从其他类更改JFrame的标题

ObA*_*bAt 4 java swing titlebar jpanel jframe

我有两个类,一个AnalogClock类和一个MainInterface类.

timeChanged在AnalogClock类中创建了一个方法,只要时间发生变化就会调用它.我的AnalogClock基本上是一个带绘图的JPanel.在MainInterface中,我设置了一个JFrame并添加了一个我的AnalogClock的Object.

每当调用'timeChanged'时,是否可以更改我的窗口的标题?我试图使用getParent()getRootParent()但他们不认识setTitle().

lcg*_*ida 5

使用 getWindowAncestor 方法来自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");
Run Code Online (Sandbox Code Playgroud)