我试图从 JMenuBar 中最大化 JFrame,但我无法传递对框架的引用。是否可以获得对使用它的框架的引用?
我可以到达顶层组件,但它无法最大化和最小化框架。
public Container getApplicationFrame(ActionEvent event){
JMenuItem menuItem = (JMenuItem) event.getSource();
JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent();
Component invoker = popupMenu.getInvoker();
JComponent invokerAsJComponent = (JComponent) invoker;
Container topLevel = invokerAsJComponent.getTopLevelAncestor();
return topLevel;
}
最佳答案
可以通过
获取包含JPanel的WindowWindow window = SwingUtilities.getWindowAncestor(popupMenu);
然后您可以使用 window.setSize()
最大化它——或者,因为您似乎知道它是一个 JFrame,将它转换为 Frame 并使用 setExtendedState
凯文提到的方法。 Example code来自 Java 开发人员年鉴:
// This method minimizes a frame; the iconified bit is not affected
public void maximize(Frame frame) {
int state = frame.getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
frame.setExtendedState(state);
}
关于java - 从 JMenuBar 控制 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/851096/