gpt4 book ai didi

java - 如何在单击 JButton 时使其输出加倍。例如,我单击 jButton 一次,但我想输出 2

转载 作者:行者123 更新时间:2023-12-02 09:36:00 24 4
gpt4 key购买 nike

我正在尝试制作 cookie clicker 游戏,我现在想要对升级进行编程,例如:当我购买第一次升级时,我想要如果我单击一次即可获得 2 个 cookie,在升级之前,如果我单击一次我只得到 1 个 cookie。我不知道如何编码,而且将来我想编码更多的升级。我请求某人帮助我整理可用于点击升级的代码。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.*;

public class JavaApplication13 {

public static void main(String[] args) {
DBP prozor = new DBP();
prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prozor.setVisible(true);
}
}

class DBP extends JFrame {
private JLabel oznaka;

public DBP() {
setTitle("Cookie Clicker");
setSize(500, 150);
setLayout(new FlowLayout(FlowLayout.CENTER, 30, 20));

oznaka = new JLabel("No points!");
add(oznaka);
JButton dugme = new JButton("Click");
add(dugme);

JButton upgrade = new JButton("Buy upgrade!");
add(upgrade);
upgrade.setVisible(false);

dugme.addActionListener(new ActionListener() {
private int brojac;

@Override
public void actionPerformed(ActionEvent e) {

brojac++;
oznaka.setText("Points " + brojac);
if (brojac == 5) {
upgrade.setVisible(true);
}
}
});

upgrade.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
upgrade.setVisible(false);
System.out.println("SA");
}
});
}
}

最佳答案

最简单的方法是,如果用户单击了升级按钮,则保留一个 boolean 值。如果他这样做了,请再增加一次“cookies”。

public class JavaApplication13 {

public static void main(String[] args) {
// All swing applications must run on their own thread.
SwingUtilities.invokeLater(() -> {
DBP prozor = new DBP();
prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prozor.setVisible(true);
});

}

}

class DBP extends JFrame {
private JLabel oznaka;
private boolean upgraded; //whether user upgraded

public DBP() {
setTitle("Cookie Clicker");
setSize(500, 150);
setLayout(new FlowLayout(FlowLayout.CENTER, 30, 20));

oznaka = new JLabel("No points!");
add(oznaka);
JButton dugme = new JButton("Click");
add(dugme);

JButton upgrade = new JButton("Buy upgrade!");
add(upgrade);
upgrade.setVisible(false);

dugme.addActionListener(new ActionListener() {
private int brojac;

@Override
public void actionPerformed(ActionEvent e) {

brojac++;
if (upgraded)
brojac++;
oznaka.setText("Points " + brojac);
if (brojac == 5) {
upgrade.setVisible(true);

}

}
});

upgrade.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
upgrade.setVisible(false);
upgraded = true;
}
});
}
}

关于java - 如何在单击 JButton 时使其输出加倍。例如,我单击 jButton 一次,但我想输出 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57517405/

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