我的简单 Java 程序遇到了问题。在这里你可以看到我所做的:
public class første_prosjekt {
int numbers[] = new int[9];
int total;
public første_prosjekt(){
frame();
}
public void frame(){
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b0 = new JButton("=");
b1.setBounds(125, 250, 75, 75);
b2.setBounds(250, 250, 75, 75 );
b3.setBounds(375, 250, 75, 75);
b4.setBounds(125, 350, 75, 75);
b5.setBounds(250, 350, 75, 75);
b6.setBounds(375, 350, 75, 75);
b7.setBounds(125, 450, 75, 75);
b8.setBounds(250, 450, 75, 75);
b9.setBounds(375, 450, 75, 75);
b0.setBounds(50, 50, 50, 50);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "THE BUTTON WORKED FLAWLESSLY");
JOptionPane.showMessageDialog(null, "Second message");
total = +1;
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "2 added");
JOptionPane.showMessageDialog(null, total);
}
});
b3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "3 added");
}
});
b4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showConfirmDialog(null, "4");
}
});
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
panel.add(b6);
panel.add(b7);
panel.add(b8);
panel.add(b9);
frame.add(panel);
}
public static void main(String[] Args){
new første_prosjekt();
}
}
设置可能很糟糕,但这不是重点。当我添加 JButton b4
时,面板上的所有内容都消失了。
另外,出于某种原因,在我添加了一些内容之后,我必须先编译它几次才能工作。
是的,我对此很陌生。
希望得到一些帮助!
- 谢谢:)
最佳答案
不得在事件分派(dispatch)线程之外修改 Swing 组件。在主函数中编辑代码,如下所示:
SwingUtilities.invokeLater(() -> new første_prosjekt());
此外,避免使用 null
布局。请改用合适的布局管理器。
关于java - JButton 让我面板上的所有内容都消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837365/