1

2 つの単純なボタンを持つ JPanel を作成しようとしています。RoachComponent最初のボタンは、パネル内のコンポーネントの数を 2 倍にします。2 番目のボタンはすべてのゴキブリを駆除します。

現在、プログラムの大部分は動作していますが、かなり深刻な問題があります。数千匹のゴキブリを追加することになっている場合でも、1 回のクリックで 1 匹のゴキブリしか追加されません。考えられることはすべてテストしましたが、まだうまくいきません。手動でゴキブリを 2 匹追加しても1 匹しか表示されません。これが私のメイン関数のコードです。必要に応じて投稿できますが、コードの他のすべての部分ですべてが正しいことを 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);

}
4

2 に答える 2

6
于 2013-02-01T23:19:46.483 に答える
1

JPanel1 つの問題は、次を追加した後に再検証する必要があることですRoachComponent

panel.revalidate();
于 2013-02-01T23:19:28.780 に答える