1

I will make a java game similar to cookie clickers, but is seems that I can't put a variable as a text in the button.

This is what is causing the problems, because the variable isn't a string(I cut out the other part of the code, because it's not important for now):

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

As you can see there's the num1 variable in there and it won't let it to be there. Any ideas how to make it work?

Błażej Michalik
  • 4,474
  • 40
  • 55
Tom Lenc
  • 765
  • 1
  • 17
  • 41
  • 1
    You have to convert the `int` number to a `String`, e.g. `new JButton(String.valueOf(num1))` – Holger Jun 12 '15 at 18:59
  • The `JButton` function is `public JButton(String text, Icon icon)`. Where `icon` is provided by default if not passed. But the text should be `String`. You can do `new JButton(""+num1);` – user3337714 Jun 12 '15 at 19:04
  • ok, both ways work, but how do I change the text in the GridLayout buttons by a code? This is the code for one GridLayout button: buttonPanel1.add(new JButton(num1 + " Cookies!")); – Tom Lenc Jun 12 '15 at 19:22
  • oh nevermind.. I din't realize something.. :D – Tom Lenc Jun 12 '15 at 20:49

3 Answers3

3

See: http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html

enter image description here

There exists no constructor for the following:

new JButton(int);

For converting int to String see: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html ... more specifically, use:

enter image description here

Example use of String.valueOf(int):

int fiveInt = 5;
String fiveString = String.valueOf(fiveInt); // sets fiveString value="5"
VILLAIN bryan
  • 701
  • 5
  • 24
1

You need to make a string representation of your integer variable, as described here: How do I convert from int to String?.

Community
  • 1
  • 1
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Although the information presented in your link is useful, just linking to a source isn't usually considered a quality answer. Can you elaborate? – Olivier Poulin Jun 12 '15 at 19:02
1

Try to get the value of int to String:

JButton b1 = new JButton(String.valueOf(num1));
hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36