java 另一个窗口_java点击按钮,出现另一个窗口
时间: 2023-10-20 12:23:25 浏览: 54
要实现在 Java 中点击按钮出现另一个窗口,可以使用 JFrame 和 JButton 类。首先,需要创建一个 JFrame 对象来表示主窗口,并在主窗口中添加一个 JButton 对象,用于触发打开另一个窗口的事件。接下来,需要实现一个 ActionListener 来处理按钮点击事件,当用户点击按钮时,该 ActionListener 将会创建一个新的 JFrame 对象来表示另一个窗口。
以下是一个示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
private JButton openButton;
public MainFrame() {
// 创建主窗口
super("Main Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
// 创建按钮
openButton = new JButton("Open New Window");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 创建新窗口
JFrame newFrame = new JFrame("New Window");
newFrame.setSize(200, 150);
newFrame.setLocationRelativeTo(MainFrame.this);
newFrame.setVisible(true);
}
});
// 将按钮添加到主窗口中
JPanel panel = new JPanel();
panel.add(openButton);
getContentPane().add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
}
```
在上面的代码中,我们首先创建了一个名为 MainFrame 的类,该类继承自 JFrame 类。在 MainFrame 的构造函数中,我们创建了一个名为 openButton 的按钮,并为该按钮添加了一个 ActionListener。当用户点击按钮时,ActionListener 会创建一个新的 JFrame 对象来表示另一个窗口,并将该窗口设置为可见。
最后,在 main 函数中,我们创建了一个 MainFrame 对象,并将其设置为可见。当用户运行该程序时,将会看到一个主窗口,该窗口中包含一个名为 "Open New Window" 的按钮。当用户点击该按钮时,将会打开一个新窗口。