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?

4
  • 1
    You have to convert the int number to a String, e.g. new JButton(String.valueOf(num1)) Commented Jun 12, 2015 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); Commented Jun 12, 2015 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!")); Commented Jun 12, 2015 at 19:22
  • oh nevermind.. I din't realize something.. :D Commented Jun 12, 2015 at 20:49

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

Try to get the value of int to String:

JButton b1 = new JButton(String.valueOf(num1));

Comments

1

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

1 Comment

Although the information presented in your link is useful, just linking to a source isn't usually considered a quality answer. Can you elaborate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.