我遇到了一个简单的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
面板上的所有内容消失时。
也有一些原因,在我添加了一点之后,我必须在它工作之前编译几次。
是的,我是新手。
希望得到一些帮助!
答案 0 :(得分:1)
不得在Event Dispatch Thread之外修改Swing组件。编辑主函数中的代码,如下所示:
SwingUtilities.invokeLater(() -> new første_prosjekt());
另外,请避免使用null
- 布局。请改用合适的布局管理器。