我正在尝试用java制作一个程序,当点击一个按钮时,它将打开一个新窗口。我使用了actionlistener和actioncommand来调用一个方法,该方法在调用时初始化另一个jframe。但是,当我单击按钮(因此调用了我的方法)时,什么也没有发生。我使用的是intellij社区版,代码编译得很好。
代码:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI implements ActionListener {
JFrame frame;
JFrame frame2;
JPanel panel;
JPanel panel2;
JLabel label1;
JLabel label2;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
int window;
String newlabel;
public enum Actions {
BUTTON1,
BUTTON2,
BUTTON3,
BUTTON4
}
public GUI() {
panel = new JPanel();
panel.setSize(190, 125);
frame = new JFrame();
frame.setSize(190,125);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
label1 = new JLabel("The C Family");
label1.setBounds(50,5,200,25);
panel.add(label1);
button1 = new JButton("C");
button1.setBounds(10,30,80,25);
button1.setActionCommand(Actions.BUTTON1.name());
button1.addActionListener(this);
panel.add(button1);
button2 = new JButton("C#");
button2.setBounds(100,30,80,25);
button2.addActionListener(this);
button2.setActionCommand(Actions.BUTTON2.name());
panel.add(button2);
button3 = new JButton("C++");
button3.setBounds(10,60,80,25);
button3.addActionListener(this);
button3.setActionCommand(Actions.BUTTON3.name());
panel.add(button3);
button4 = new JButton("Rust");
button4.setBounds(100,60,80,25);
button4.addActionListener(this);
button4.setActionCommand(Actions.BUTTON4.name());
panel.add(button4);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(Actions.BUTTON1.name())) {
window = 1;
newWindow();
} else if (e.getActionCommand().equals(Actions.BUTTON2.name())) {
window = 2;
newWindow();
} else if (e.getActionCommand().equals(Actions.BUTTON3.name())) {
window = 3;
newWindow();
} else if (e.getActionCommand().equals(Actions.BUTTON4.name())) {
window = 4;
newWindow();
}
}
public void newWindow() {
if(window == 1) {
newlabel = "C";
} else if (window == 2) {
newlabel = "C#";
} else if (window == 3) {
newlabel = "C++";
} else if (window == 4) {
newlabel = "Rust";
}
panel2 = new JPanel();
panel2.setSize(500,500);
frame2 = new JFrame();
frame2.setSize(500,500);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.add(panel);
panel2.setLayout(null);
label2 = new JLabel(newlabel);
label2.setBounds(105,20,200,25);
panel2.add(label2);
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}
1条答案
按热度按时间dm7nw8vv1#
frame.setVisible(true);
->frame2.setVisible(true);