JButton set the button text to a variable - java

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?

See: http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
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:
Example use of String.valueOf(int):
int fiveInt = 5;
String fiveString = String.valueOf(fiveInt); // sets fiveString value="5"

Try to get the value of int to String:
JButton b1 = new JButton(String.valueOf(num1));

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

Related

Calculator in Swing Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calc implements ActionListener
{
JFrame f;
JPanel p;
JTextField jt1,jt2,jt3;
JButton j1,j2;
static double a=0,b=0,result=0;
static int operator=0;
calc()
{
f = new JFrame();
p = new JPanel();
jt1 = new JTextField(20);
jt2 = new JTextField(20);
j1 = new JButton("+");
j2 = new JButton("-");
jt3 = new JTextField();
f.add(p);
p.add(jt1);
p.add(jt2);
p.add(j1);
p.add(j2);
j1.addActionListener(this);
j2.addActionListener(this);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()=="+")
{
a=Double.parseDouble(jt1.getText());
operator = 1;
b=Double.parseDouble(jt2.getText());
switch(operator)
{
case 1: result=(a+b);
}
jt3.setText(result);
}
}
public static void main(String [] args)
{
calc obj = new calc();
}
}
i'm making a calculator using java swing, the output of this code is:
calc.java:48 error: incompatible types: double cannot be converted to String
jt3.setText(result);
i think this is not a big error, well help me to get rid of this, i just want to sum didn't add more functions like multiply or minus or etc, i just want to run as small code first then i'll add more functions to it well help will be appreciated thanks.
Easy way is:
//jt3.setText(result);
jt3.setText("" + result);
This will force the compiler to create a String of the two values.
Use jt3.setText(String.valueOf(result));.
.setText() only accept String type.
You can see it in Class TextField.
Class text can accept only string values.
where the result you provided as an argument is Double
You can use this to convert it as a string
string converted = Double.toString(result);
This error is because JTextField is expecting a String to set the text to it, not a double, so, you need to either:
jt3.setText(String.valueOf(result));
Or
jt3.setText("" + result);
The first one will convert result to a String value, while the second one will concatenate an empty String to result, and return a String as well.
However one last suggestion I want you to take note of is, don't use single letter variables, make them more descriptive, for example:
JFrame f; //This should be JFrame frame;
The same for the JPanel and the rest of your variables, since in larger programs it could be hard to remember that f means a JFrame and not the conversion to Fahrenheit from Celsius or a formula like F = m * a, it may be confusing and really hard to debug / understand later on.
And also as has been said in the comments above, use .equals to compare String in Java, see How do I compare strings in Java? for more on this

Java: How To Use Arrays

I was learning about arrays today in school, and I am trying to do this problem, but cannot figure it
// Fortune Teller
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class FortuneTeller extends JFrame
implements ActionListener
{
private static final EasySound ding = new EasySound("ding.wav");
// Declare an array of "fortunes" (strings):
___________________________________________
...
private JTextField display;
public FortuneTeller()
{
super("Fortune Teller");
display = new JTextField(" Press \"Next\" to see your fortune...", 25);
display.setBackground(Color.WHITE);
display.setEditable(false);
JButton go = new JButton("Next");
go.addActionListener(this);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(display);
c.add(go);
}
public void actionPerformed(ActionEvent e)
{
// Pick and display a random fortune:
___________________________________________
...
display.setText(" " + __________________ );
ding.play();
}
public static void main(String[] args)
{
JFrame window = new FortuneTeller();
window.setBounds(300, 300, 300, 100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
}
I am trying to fill in the blanks.
For the first one,, would it just be just be String [] Fortune;?
But how would I end up initializing it?
And then for the second part, what would I have to do?
Please help as I am extremely lost.
Here are some hints to help you (without actually doing your homework for you).
You can create and populate an array of strings in one line using the following syntax:
String[] colours = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};
You can generate a random number between zero and x (inclusive) using the following syntax:
int randomNumber = Math.random() * (x + 1);
You can select a random string from an array with the following syntax:
String randomColour = colours[Math.random() * colours.length];
As found by the simple Google search "How to declare an array in Java":
String[] fortune = {"You're going to be right","You're going to die","You're going to find a cat"};
This also initializes the array.
Then to get the an element of the array, you do:
fortune[1];
//Returns: You're going to die
For this though, I'd do a random number generator to pick a number between 0 and the length of the array:
int value = Math.random() * fortune.length;
fortune[value];

Issues creating java GUI with while loop

I am creating a java GUI which is a fortune teller. The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. I have made already for the most part. But now I am having some trouble creating the while loops to display the strings without repeating. I have looked at my book which didn't really help. If you guys could point me in the right direction,it would be much appreciated. Thanks!
I entered all of the code so you can see the variables used. But my question starts at class RndButtonListener.
package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
* #author a3cal_000
*/
class FortuneTellerFrame extends JFrame
{
final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
final private JButton quitBtn, rndBtn;
final private JLabel titleLbl, iconLbl;
final private JTextArea displayTa;
final private JScrollPane scroller;
public String[] fortune = new String [12];
int newIndex, oldIndex;
private static final int HEIGHT = 250;
private static final int WIDTH = 450;
public FortuneTellerFrame()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
displayPnl = new JPanel();
buttonPnl = new JPanel();
titlePnl = new JPanel();
ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
iconLbl = new JLabel(icon);
titleLbl = new JLabel("Fortune Teller!");
displayTa = new JTextArea();
imagePnl = new JPanel();
scroller = new JScrollPane();
// Create the layout of the title panel
titlePnl.setLayout(new GridLayout(2,1));
add(mainPnl);
// Set the label to the panel.
titlePnl.add(titleLbl);
titlePnl.add(iconLbl);
// add the panel to the main panel.
mainPnl.add(titlePnl, BorderLayout.NORTH);
mainPnl.add(scroller, BorderLayout.CENTER);
mainPnl.add(displayTa, BorderLayout.CENTER);
// Create the "Get my fortune button.
rndBtn = new JButton("Get My Fortune!");
quitBtn = new JButton("Quit");
// Add the buttons to the buttonPnl in grid layout.
buttonPnl.add(rndBtn);
buttonPnl.add(quitBtn);
// Create the grid layout for the button panel.
buttonPnl.setLayout( new GridLayout(1, 2));
// Add the button panel to the grid layout, South.
mainPnl.add(buttonPnl, BorderLayout.SOUTH);
ActionListener listener = new RndButtonListener();
rndBtn.addActionListener(listener);
quitBtn.addActionListener(listener);
}
class RndButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
fortune[0] = "He who throws dirt is losing ground.";
fortune[1] = "You will find the love of your life in food.";
fortune[2] = "Do or do not, there is no try.";
fortune[3] = "Tomorrow is a better day to try anything of importance.";
fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
fortune[5] = "You can't be late until you show up.";
fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
fortune[7] = "If youre at the top it means you have further to fall.";
fortune[8] = "Even in last place, youre still in the race.";
fortune[9] = "The road to riches is paved on the failures of others.";
fortune[10] = "If you feel like your going no where, get off the treadmill.";
fortune[11] = "Thinking about going to the gym is just as good as going.";
Random rnd = new Random(fortune.length);
do
{
newIndex = rnd.nextInt(fortune.length);
}
while(newIndex == oldIndex);
do
{
System.out.println(fortune[newIndex]);
displayTa.append(fortune[newIndex] + "||");
displayTa.updateUI();
mainPnl.updateUI();
oldIndex = newIndex;
}
while(newIndex != oldIndex);
class QuitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
}
}
}
The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again.
Instead try using...
do {
newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);
You also don't need the second loop, it's just clutter that confuses the situation.
You may also find that...
displayTa.append(fortune[newIndex] + "\n");
produces nicer output (IMHO)
You may also wish to take a look at How to use Scroll Panes
Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt().
Random rnd = new Random(fortune.length);
Do it this way
Random rnd = new Random();
and also consider the formatting solution given by MadProgrammer.
Random() gives you same number pattern. Try Random(System.currentTimeMillis()). It uses current time as seed, so you can get real random numbers.
I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes)
ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();
Then add in some numbers starting from 0 to code for the fortunes.
for(int i = 0; i < fortune.length; i++) {
fortuneSeq.add(i);
}
Then I used the shuffle() method from the Collections class to randomize the list.
Collections.shuffle(fortuneSeq);
After that, just loop through to access the fortunes.
for(int i = 0; i < fortune.length; i++) {
System.out.println(fortune[fortuneSeq.get(i)]);
//...
}
Edit: Silly autocorrect, you don't like programmers.
Edit: Fixed some furtunes instead of fortunes and fixed println statement.

How to create an array by inputting numbered into a textfield, Java applet

My assignment is to input 20 numbers via a text field then out the mean, the median and the total using a while loop. I should be able to figure out the while loop myself, but I can't get the text field to input numbers into an array. Please help, here is my code so far:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class whileloopq extends Applet implements ActionListener
{
Label label;
TextField input;
int[] numArray = new int[20];
int num;
public void init ()
{
Label label = new Label("Enter numbers");
TextField input = new TextField(5);
add(label);
add(input);
input.addActionListener(this);
}
public void actionPerformed (ActionEvent ev)
{
int num = Integer.parseInt(input.getText());
int index = 0;
numArray[index] = num;
index++;
input.setText("");
}
public void paint (Graphics graf)
{
graf.drawString("Array" + numArray, 25, 85);
}
}
Any help would be much appreciated.
(Answer written under the assumption that this is a homework assignment.)
You know how to parse an integer from a string, as you show with your usage of Integer.parseInt, but you are calling it to parse the entire 20 characters as one integer. You need to get each character individually to be parsed.
I recommend using a for loop, and String#substring to substring the input text into several strings of length one.
Alternatively, you can split the input text around an empty string and then iterate through the resulting array (note that the first string in the array will be empty), but the other approach is more likely the one expected from someone new to Java, so you'll have to use your judgement here.
In actionPerformed() you are trying to read from class filed input.setText("");
but in init() you didn't initialized that field but created and added to applet local variable
TextField input = new TextField(5);
so class field is steal null. Change it to
input = new TextField(5);
import java.awt.*;
public class frame4array extends Frame
{
Checkbox c1[];
TextField t1[];
int i;
frame4array(String p)
{
super(p);
c1=new Checkbox[2];
t1=new TextField[2];
for(i=0;i<2;i++)
{
t1[0]=new TextField();
t1[0].setBounds(200, 50, 150, 30);
t1[1]=new TextField();
t1[1].setBounds(200, 80, 150, 30);
c1[0]=new Checkbox("Singing");
c1[0].setBackground(Color.red);
c1[0].setBounds(430,200,120,40);
c1[1]=new Checkbox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
}
setFont(new Font("Arial",Font.ITALIC,40));
}
public static void main(String s[])
{
frame4array f1=new frame4array("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}

How to append data in JTextArea in Java?

I am using this code to show text in a JTextArea:
jTextArea1.setText(jTextArea1.getText() + text + "\r\n");
jTextArea1.repaint();
But it shows an exception:
java.lang.NullPointerException
You never instantiated your JTextArea. Also, you might want to check out JTextArea#append.
jTextArea1.setText(jTextArea1.getText() + text + "\r\n");
StringBuilder sb = new StringBuilder();
if(jTextArea1.getText().trim().length() > 0){
sb.append(jTextArea1.getText().trim());
}
sb.append(text).append("\r\n");
jTextArea1.setText(sb.toString());
Above two friends gave you answer.
I want to explain it. Because first times I also met that problem. I solved that, but today solve as above code snippet.
As Jeffrey pointed out, you have to create an object instance before you call non-static methods on it. Otherwise, you will get a NullPointerException. Also note that appending a text to a JTextArea can be done easily by calling its JTextArea.append(String) method. See the following example code for more detail.
package test;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.start();
}
private void start() {
JTextArea ta = new JTextArea();
ta.append("1\n");
ta.append("2\n");
ta.append("3\n");
JFrame f = new JFrame();
f.setSize(320, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(ta);
f.setVisible(true);
}
}
The following code adds text to the text area. Note that the text system uses the '\n' character internally to represent newlines; for details, see the API documentation for DefaultEditorKit.
private final static String newline = "\n";
...
textArea.append(text + newline);
Source

Categories

Resources