当我单击menubar项时,我在JFrame JF中有一个菜单栏,一个新的JFrame JF1被创建并显示,但当我单击JF1的close按钮时,两个JFrame都被关闭。当我点击JF1的close按钮时,我只想关闭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);
}`发布于 2014-03-07 01:48:09
将创建并显示一个新的JFrame JF1
不要创建新的JFrame应用程序应该只有一个JFrame。
而是创建一个JDialog。有关详情,请参阅:The Use of Multiple JFrames: Good or Bad Practice?。
此外,您不能使用add(...)将JMenuBar添加到JFrame方法。有关更好的实现方法,请参阅How to Use Menu Bars。
发布于 2014-03-07 01:48:48
我推荐你使用DesktopPane和JInternalFrame。
对主框架进行更改: contentPane (JPanel)将为JDesktopPane。
单击时显示的JFrame将是一个JInternalFrame。
在JMenuItem的actionListener中,您将执行以下操作:
MyInternalFrame internalFrame = new MyInternalFrame();
internalFrame.show();
contentPane.add(internalFrame);MyInternalFrame是所显示的帧的类(扩展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);
}
}https://stackoverflow.com/questions/22232020
复制相似问题