2016-10-04 156 views
0

我正在为我的女朋友制作这款游戏​​,而且现在我一直被困在同一个问题上。基本上,我希望她能够按下“收集木材”按钮5次,然后在第五次按下按钮后,弹出“创建火灾”按钮。如何让我的按钮在我想要的时候显示?

1.问题是,无论我尝试将方法编程为第五个按钮时显示的方法,它都不会显示出来。

  1. 我会很感激任何编码技巧或任何你们都认为我可以做的事来清理我目前的代码。

    private static JPanel panel; 
    private static int woodCounter; 
    private static int leafCounter; 
    private static JFrame frame; 
    
  2. 这是捡柴按钮

    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. 这是导致火灾按钮

    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)); 
    } 
    
+0

您的'面板'是否足够显示两个按钮? – VGR

+0

谁在调用'gatherWood()'和'createFire()'以及如何? –

+0

对不起,需要很长时间才能回复。我只是通过说gatherWood()和createFire()来主要调用它,并且我不知道面板有大小,所以我不知道它的大小。 –

回答

2

基本上,我希望她能够按然后在她按下第五个按钮之后,“收集木材”按钮5次那么应该弹出“Create Fire”按钮。

我没有看到任何告诉代码做任何事的“if逻辑”。

一旦你解决这个问题(并验证“createFire()`方法被调用),我怀疑下一个问题是,当你将组件添加到一个可见的Swing GUI的基本代码应该是:

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

您需要revalidate()调用布局管理器,否则增加的分量的大小为(0,0)并没有什么画画。

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

不要让试图改变布局管理器。这不是第二个参数用于什么当面板创建时,面板的管理员只能设置一次。

+0

我曾尝试过,但在执行if/else语句后,我没有在面板上调用该方法。我只是把它放在我的代码中,现在它可以工作。谢谢。 –

相关问题