[英]Drawing Multiple Items to a JPanel
我試圖用兩個簡單的按鈕創建一個JPanel。 第一個按鈕使面板中RoachComponent
組件的數量增加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);
}
刪除frame.repaint();
所有代碼frame.repaint();
並在panel.revalidate()
之前添加jpanel.repaint();
(最終的樣子)一切都取決於使用的LayoutManager
的JPanel
為了更好的幫助,請盡快發布和SSCCE
一個問題是,您需要在添加RoachComponent
之后重新驗證JPanel
:
panel.revalidate();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.