【发布时间】:2013-02-01 23:13:22
【问题描述】:
我正在尝试创建一个带有两个简单按钮的 JPanel。第一个按钮使面板中RoachComponent 组件的数量翻倍。第二个按钮将清除所有蟑螂。
现在,我的大部分程序都在运行,但有一个相当严重的问题。每次点击只添加一个蟑螂,即使它应该添加几千只蟑螂。我已经测试了我能想到的所有东西,但它仍然让我望而却步。即使我手动添加了两只蟑螂,也只显示一只。这是我的主要功能中的代码。我 99% 确信代码的其他所有部分都正确无误,尽管我可以在需要时发布它。
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
// Button to create a new roach
JButton button = new JButton("New Roach");
final RoachPopulation roachPopulation = new RoachPopulation(2);
// The label for displaying the results
final JLabel label = new JLabel("Population: " + roachPopulation.getPopulation());
// ActionListener class
class doubleListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("------------------");
for (int i = 0; i < roachPopulation.getPopulation(); i++) {
RoachComponent newRoach = new RoachComponent();
panel.add(newRoach);
newRoach.getCoords();
}
panel.repaint();
frame.repaint();
roachPopulation.doublePopulation();
label.setText("Population: " + roachPopulation.getPopulation());
// Showing that there *is* the correct number of roaches in the panel.
System.out.println(panel.getComponentCount());
}
}
RoachComponent r1 = new RoachComponent();
RoachComponent r2 = new RoachComponent();
panel.setLayout(new BorderLayout());
panel.add(button, BorderLayout.SOUTH);
panel.add(label, BorderLayout.NORTH);
panel.add(r1);
panel.add(r2);
//panel.add(component, BorderLayout.CENTER);
frame.add(panel);
frame.repaint();
ActionListener doubleListener = new doubleListener();
button.addActionListener(doubleListener);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
【问题讨论】:
-
关于,
" I'm 99% sure that everything is correct in every other part of the code, although I can post it if needed.":你不知道错误来自哪里,所以你最好不要做任何假设。我无法根据这个 sn-p 判断出什么问题,而且没有人有时间或渴望查看所有代码,因此我建议您将所有内容归结为 sscce 并发布。
标签: java swing jpanel jcomponent