JMenuBar to JFrame



我在单击Menubar项目时在Jframe JF中有一个菜单栏,创建了新的JFRAME JF1并显示,但是当我单击JF1的关闭按钮时,这两个Jframe均为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。请参阅:使用多个Jframes:好还是坏习惯?有关更多信息。

另外,您也不会使用add(...)方法将Jmenubar添加到Jframe。请参阅如何使用菜单栏以进行更好的方法。

我推荐您使用desktoppane和jinternalframe。

在您进行更改的主框架上:contentpane(jpanel)将是jdesktoppane。

显示的jframe whit键是jinternalframe。

在Jmenuitem的动作位置中,您将执行此操作:

MyInternalFrame internalFrame = new MyInternalFrame();
internalFrame.show();
contentPane.add(internalFrame);

MyInternalFrame是显示的框架的类(扩展了JinternalFrame的类)。

要关闭" internalframe",只需在布局上添加一个按钮,然后将文本"退出"和您放置的" 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);
}
}

关于class(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);
}
}

最新更新