我将制作一个类似于 cookie clickers 的 java 游戏,但似乎我无法将变量作为文本放入按钮中。
这就是导致问题的原因,因为变量不是字符串(我删除了代码的其他部分,因为它现在不重要):
import javax.swing.JFrame;
import javax.swing.JButton;
public class Frame {
public static int num1 = 0;
public static void main(String[] args){
JFrame f = new JFrame("Cookie Clicker");
JButton b1 = new JButton(num1);
f.setSize(500, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(b1);
}
}
如您所见,其中有 num1 变量,但它不会让它在那里。有什么想法可以让它发挥作用吗?
最佳答案
参见:http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
不存在以下构造函数:
new JButton(int);
要将 int 转换为 String,请参阅:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html ...更具体地说,使用:
String.valueOf(int) 的使用示例:
int fiveInt = 5;
String fiveString = String.valueOf(fiveInt); // sets fiveString value="5"
关于java - JButton 将按钮文本设置为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810307/