How do I make my button display at the time I want it to?

ⅰ亾dé卋堺 提交于 2019-12-02 16:06:15

问题


I'm working on this game for my girlfriend and I've been stuck on the same problem for a few days now. Basically, I want her to be able to press the "Gather Wood" button 5 times then, right after she presses it the fifth time, the "Create Fire" button should pop up.

1.The problem is that no matter which way I attempt to program the method to show up on the fifth button press it just doesn't show up.

  1. I would appreciate any coding tips or anything y'all think I can do to clean up my current code.

    private static JPanel panel;
    private static int woodCounter;
    private static int leafCounter;
    private static JFrame frame;
    
  2. This is the gather wood button

    public static int gatherWood() {
    woodCounter = 0;
    
    JButton wood = new JButton("Gather Wood");
    
    wood.addActionListener(new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("Gathering Wood");
            woodCounter++;
            woodCounter++;
            System.out.println(woodCounter);
        }
    });
    
    wood.setVisible(true);
    panel.add(wood, new FlowLayout(FlowLayout.CENTER));
    
    return woodCounter;
    }
    
  3. This is the create fire button

    public static void createFire() {
    JButton fire = new JButton("Create Fire");
    
    fire.addActionListener(new ActionListener() { 
    
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("Creating a fire.");
    
            woodCounter = woodCounter - 10;
        }
    });
    
    fire.setVisible(true);
    panel.add(fire, new FlowLayout(FlowLayout.CENTER));
    } 
    

回答1:


Basically, I want her to be able to press the "Gather Wood" button 5 times then, right after she presses it the fifth time, the "Create Fire" button should pop up.

I don't see any "if logic" anywhere that tells the code to do anything.

Once you fix that (and verify that the "createFire()` method is invoked) I suspect the next problem is that when you add a component to a visible Swing GUI the basic code should be:

panel.add(...);
panel.revalidate();
panel.repaint();

You need the revalidate() to invoke the layout manager otherwise the added component has a size of (0, 0) and there is nothing to paint.

panel.add(fire, new FlowLayout(FlowLayout.CENTER));

Don't keep trying to change the layout manager. That is not what the second parameter is used for. The layout manager of the panel should be set only once when the panel is created.



来源:https://stackoverflow.com/questions/39856325/how-do-i-make-my-button-display-at-the-time-i-want-it-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!