我试图从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;
}发布于 2009-05-12 04:34:55
您可以通过获取包含JPanel的窗口
Window window = SwingUtilities.getWindowAncestor(popupMenu);然后,您可以使用window.setSize()最大化它--或者,因为您似乎知道它是一个JFrame,所以将它强制转换为Frame并使用凯文提到的setExtendedState方法。来自Java开发人员年鉴的Example code:
// 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);
}发布于 2009-05-12 04:21:15
当然,您可以将有问题的框架存储在某个局部变量中?
至于一旦你掌握了框架就将其最大化,Frame.setExtendedState(MAXIMIZED_BOTH)可能就是你想要的。Javadoc
虽然还不够优雅,但还是可以在现有代码基础上快速入门:
public Frame getApplicationFrame(ActionEvent event){
if(event.getSource() == null) return null;
Window topLevel = SwingUtilities.getWindowAncestor(event.getSource());
if(!(topLevel instanceof Frame)) return null;
return (Frame)topLevel;
}
...
//Somewhere in your code
Frame appFrame = getApplicationFrame(myEvent);
appFrame.setExtendedState(appFrame.getExtendedState() | Frame.MAXIMIZED_BOTH);
...最低Java版本为1.4.2。请注意,我还没有测试过上面的代码,但您应该明白这一点。
发布于 2009-05-12 04:28:28
创建框架和菜单栏的类也可以充当菜单项的ActionListener,因为它可以访问框架和菜单栏。
https://stackoverflow.com/questions/851096
复制相似问题