繁体   English   中英

如何在我希望的时间显示按钮?

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

我正在为我的女友开发这款游戏,而现在我在同一个问题上停留了几天。 基本上,我希望她能够按5次“ Gather Wood”按钮,然后在她第五次按该按钮后,立即弹出“ Create Fire”按钮。

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

基本上,我希望她能够按5次“ Gather Wood”按钮,然后在她第五次按该按钮后,立即弹出“ Create Fire”按钮。

我看不到任何告诉代码执行任何操作的“如果逻辑”。

修复此问题(并验证是否调用了“ createFire()`”方法)之后,我怀疑下一个问题是,当您将组件添加到可见的Swing GUI中时,基本代码应为:

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

您需要revalidate()来调用布局管理器,否则添加的组件的大小为(0,0),没有任何内容可绘制。

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

不要继续尝试更改布局管理器。 那不是第二个参数的用途。 创建面板时,面板的布局管理器仅应设置一次。

暂无
暂无

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

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