因此,当我尝试运行我的代码时,它工作正常,但我没有点击按钮。 我已经解决了我从中获得的错误,但我不明白为什么我的窗口上没有按钮。
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public Main () {
JFrame mainWindow = new JFrame("Main Window");
mainWindow.setSize(1200, 800);
mainWindow.setTitle("Main Window");
mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
JButton button = new JButton("Click Me");
add(button);
button.addActionListener(this);
}
public static void main(String args[]) {
new Main();
}
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);
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:1)
尝试将mainWindow.add(button);
添加到JFrame mainWindow = ...
,如下所示:
JButton button = new JButton("Click Me");
mainWindow.add(button);
代码块应该是:
public Main () {
JFrame mainWindow = new JFrame("Main Window");
mainWindow.setSize(1200, 800);
mainWindow.setTitle("Main Window");
mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
JButton button = new JButton("Click Me");
mainWindow.add(button);
button.addActionListener(this);
}