我需要程序 - 主 JFrame 有 2 个按钮
- 按钮
- 按钮2
当我单击 button 时,它必须打开带有新选项的新 JFrame 窗口,而如果我单击 button2 则打开另一个窗口。
在这两个新窗口中,我必须添加像下一个和上一个这样的按钮。
我有一个问题,当我打开按钮 1,然后打开 2 个窗口时,主 JFrame 仍然可见。
我的第一个 swing 程序:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class example {
public static void main (String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("hello agin1");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button.addActionListener (new Action2());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(200,200);
JLabel label = new JLabel("you clicked me");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame3 = new JFrame("OKNO 3");
frame3.setVisible(true);
frame3.setSize(200,200);
JLabel label = new JLabel("kliknales");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
}
最佳答案
您将 ActionListener
添加到 button
两次。因此,将 button2
的代码更正为
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
此外,在 correct thread 上执行您的 Swing 操作通过使用 EventQueue.invokeLater
关于java - 如何创建一个带有两个按钮的窗口来打开一个新窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771269/