简体   繁体   English

将多个项目绘制到一个JPanel

[英]Drawing Multiple Items to a JPanel

I am trying to create a JPanel with two simple buttons. 我试图用两个简单的按钮创建一个JPanel。 The first button doubles the number of RoachComponent components in the panel. 第一个按钮使面板中RoachComponent组件的数量增加RoachComponent The second button will clear all of the roaches off. 第二个按钮将清除所有蟑螂。

Now, I have the majority of the program working, but there is a rather serious problem. 现在,我已经完成了程序的大部分工作,但是存在一个相当严重的问题。 Only one roach per click is added, even when it's supposed to be adding a couple thousand roaches. 每次点击仅添加一只蟑螂,即使应该添加几千只蟑螂也是如此。 I have tested everything that I can think of, but it's still eluding me. 我已经测试了所有我能想到的东西,但是它仍然使我难以理解。 Even when I manually add two roaches, only one is displayed. 即使我手动添加了两只蟑螂,也只显示了一只。 Here is the code in my main function. 这是我主要功能中的代码。 I'm 99% sure that everything is correct in every other part of the code, although I can post it if needed. 我有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);

}

一个问题是,您需要在添加RoachComponent之后重新验证JPanel

panel.revalidate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM