[英]JMenuBar to JFrame
当我单击菜单栏项时,在JFrame JF中有一个菜单栏,创建并显示一个新的JFrame JF1,但是当我单击JF1的关闭按钮时,两个JFrame都关闭了。 当我单击JF1的关闭按钮时,我只希望关闭JF1,而不要关闭JF
JMenuBar menubar;
JMenu help;
JMenuItem about;
public GUI() {
setLayout(new FlowLayout());
menubar = new JMenuBar();
add(menubar);
help = new JMenu("Help");
menubar.add(help);
}`
创建并显示一个新的JFrame JF1
不要创建新的JFrame,应用程序应该只有一个JFrame。
而是创建一个JDialog
。 请参阅: 使用多个JFrame:良好还是不良做法? 欲获得更多信息。
同样,您也不会使用add(...)方法将JMenuBar添加到JFrame。 请参阅“ 如何使用菜单栏”以获得更好的方法。
我建议您使用DesktopPane和JInternalFrame。
对主框架进行更改:contentPane(JPanel)将为JDesktopPane。
单击显示的JFrame是JInternalFrame。
在JMenuItem的actionListener中,您将执行以下操作:
MyInternalFrame internalFrame = new MyInternalFrame();
internalFrame.show();
contentPane.add(internalFrame);
MyInternalFrame是显示的Frame的类(扩展JInternalFrame的类)。
要关闭“ internalFrame”,只需在布局中添加一个按钮,然后输入文本“ Quit”,然后在其actionListener中放置“ dispose()”即可。
试试看,告诉它是否有效;)
-编辑-主要类别(JFRAME)
public class Main extends JFrame {
private JDesktopPane contentPane;
private JMenuBar menuBar;
private JMenu mnExample;
private JMenuItem mntmAbout;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(20, 20, 800, 800);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnExample = new JMenu("Help");
menuBar.add(mnExample);
mntmAbout = new JMenuItem("About");
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
About frame = new About();
frame.show();
contentPane.add(frame);
}
});
mnExample.add(mntmAbout);
contentPane = new JDesktopPane();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}
}
关于类(JINTERNALFRAME)
public class About extends JInternalFrame {
public About() {
setBounds(100, 100, 544, 372);
JLabel lblSomeText = new JLabel("Some Text");
getContentPane().add(lblSomeText, BorderLayout.CENTER);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
getContentPane().add(btnClose, BorderLayout.SOUTH);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.