gpt4 book ai didi

java - 如何让按钮在我想要的时间显示?

转载 作者:行者123 更新时间:2023-12-02 03:19:07 25 4
gpt4 key购买 nike

我正在为我的女朋友开发这款游戏,几天来我一直被同样的问题困扰。基本上,我希望她能够按“收集木材”按钮 5 次,然后,在她第五次按后,“生火”按钮应该弹出。

1.问题是,无论我尝试以哪种方式编程该方法以显示在按下第五个按钮时,它都不会显示。

  • 如果有任何编码技巧或你们认为我可以做的任何事情来清理我当前的代码,我将不胜感激。

    private static JPanel panel;
    private static int woodCounter;
    private static int leafCounter;
    private static JFrame frame;
  • 这是收集木材按钮

    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;
    }
  • 这是创建火按钮

    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));
    }
  • 最佳答案

    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.

    我在任何地方都没有看到任何告诉代码执行任何操作的“if 逻辑”。

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

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

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

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

    不要一直尝试更改布局管理器。这不是第二个参数的用途。面板的布局管理器只能在创建面板时设置一次。

    关于java - 如何让按钮在我想要的时间显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856325/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com