JMenuItem按钮打开新窗口关闭旧窗口
时间: 2023-08-23 08:06:06 浏览: 58
可以通过在 JMenuItem 上添加 ActionListener 监听器,在监听器中创建新的 JFrame 对象,并在关闭旧窗口前先关闭当前窗口的方式实现。具体实现步骤如下:
1. 创建一个 JFrame 对象,设置其大小、标题等属性。
2. 向 JFrame 对象中添加需要显示的组件,如标签、按钮等。
3. 创建一个 JMenuItem 对象,设置其文本和快捷键等属性。
4. 为 JMenuItem 对象添加一个 ActionListener 监听器,当用户点击菜单项时,执行打开新窗口的操作。
5. 在 ActionListener 监听器的 actionPerformed() 方法中,创建一个新的 JFrame 对象,设置其大小、标题等属性,并显示出来。同时,关闭当前窗口。
下面是一个示例代码,用于演示如何通过 JMenuItem 打开新窗口并关闭旧窗口:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
private JMenuItem newFrameMenuItem;
public MainFrame() {
super("Main Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrameMenuItem = new JMenuItem("New Frame", 'N');
newFrameMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
newFrameMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 创建新的 JFrame 对象
JFrame newFrame = new JFrame("New Frame");
newFrame.setSize(300, 200);
newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
newFrame.setVisible(true);
// 关闭当前窗口
dispose();
}
});
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.add(newFrameMenuItem);
menuBar.add(menu);
setJMenuBar(menuBar);
getContentPane().add(new JLabel("Main Frame"));
pack();
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
```
运行该程序后,点击 "New Frame" 菜单项即可打开一个新的窗口并关闭旧窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)