I want to pass the JLabel to Integer, The following code does not work even with Integer.valueOf() and Integer.parse()
This are the following code I've Tried:
Test 1:
JLabel life = new JLabel("204");
int x = Integer.valueOf(life).intValue();
Test 2:
JLabel life = new JLabel("204");
int x = Integer.parseInt(life);
No. You can't magically convert a Label to Integer.
However you can get the string of that label and then convert.
JLabel life = new JLabel("204");
int x = Integer.parseInt(life.getText());
Note that, you'll be succeed when there is proper text. For ex
"203", "34343" works but not "A2342"
Related
I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:
JLabel carbLbl;
int totCarbs = 0;
public Main() {
carbLbl = new JLabel("Total Carbs: " + totCarbs);
carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
foodList.addRow(s);
totCarbs += Integer.parseInt(s[2]);
carbLbl.repaint();
}
}
There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?
The JLabel is not "bound" to your integer variable. When you change the integer you need to update the JLabel using carbLbl.setText(String.valueOf(totCarbs))
Is there not a way to simply update the JLabel using the initial constructor parameters?
carbLbl = new JLabel("Total Carbs: " + totCarbs);
What parameters? There is only a single parameter, the String to be displayed.
The compiler concatenates the hard coded String with the value of your "totCarbs" variable to create a single String.
The compiler will essentially treat the above code like:
String text = "Total Carbs" + totCarbs;
carbLbl = new JLabel( text );
The JLabel has no idea how the String was created (ie. that a variable was used to build the string).
I understand the concept of concatenation, but I just feel like that's a workaround
It is not a work around. The API of the setText(...) method states you provide a single String. So, if you want to update the label you need to provide the entire String.
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
I've been looking all over the net for a code that is something like this:
JTextField[] jt = new JTextField{jTextField1,jTextField2,..};
I had a copy of this code once and I kept it in a hard disk because I know I might use it in the future, but the disk died!
can anyone help me find this code? It gives me error so please do correct this for me. thanks!
by the way, this is an array for an existing jTextField and it runs inside a button when pressed.
EDIT: since this was flagged as possible duplicate, heres my explanation.
The classic initialization has already been tested and what ive seen yet so far in declaring jTextField array is this:
JTextField[] jt = new jTextField[10];
specifying the value then adding it.
jTextField[n] = new JTextField(jTextField1);
if i use that method, I would have to type it all over again.
jTextField[n] = new JTextField(jTextField2);
jTextField[n] = new JTextField(jTextField3);.. and so on and so forth.
now what I am looking for is what i've said on the sample code. I have used this once but I was clumsy enough not to back it up.
This is wrong syntax and will throw a compilation error:
JTextField[] jt = new JTextField{jTextField1,jTextField2};
You need to do:
JTextField[] jt = new JTextField[] {jTextField1,jTextField2}; // or you can do {jTextField1,jTextField2};
I tried this and it works fine:
JTextField j1 = new JTextField();
JTextField j2 = new JTextField();
JTextField[] j = new JTextField[] {j1, j2};
//JTextField[] j = {j1, j2}; // This syntax also works
System.out.println(j);
I think it's not possible to do what you want. Try to code some cycle to create and add JTextFields to you array.
int x = 2;
JTextField[] textFields = new JTextField[x];
for(int i = 0;i < x; i++) {
JTextField textField = new JTextField(blabla);
textField.setSomething();
textFields [i] = textField;
}
Silly netbeans..
I closed my project down and re-opened it just to try it out. well guess what. the code works properly now.
public void arrayoftextboxes(){
JTextField[] jt = {jTextField1, jTextField2};
}
I have the following code:
int[] matrix = new int[9][9];
(for int x = 0; x <= 8; x++){
(for int y = 0; y <= 8; x++){
JtextField matrix[x][y] = new JtextField(“Matrix" x + y)
int[] coords = new int[2];
coords[0] = x;
coords[1] = y;
matrix[x][y].putClientProperty("coords", coords);
matrix[x][y].setText(game[x][y]);
}
}
After the loops end, I need a way of finding out which textfield the user typed into (the user also hits enter). So:
1. How do I check if a JtextField has been edited without knowing which one it is or its name?
2. How do I check which "coords" the textfield is positioned at? I have an idea of how to do it, but for some reason I cannot code it.
I feel like the answer is staring me right in the face, but its late, I'm tired, and I'm getting flustered. Thanks!
The answer depends on what you want to achieve.
If you're only interested in the end result, you could use an ActionListener (for when the user hits Enter) and a FocusListener for when they don't and leave the field any way (assuming you want to know this)
When the respective event occurs, you can inspect the source of the event by using getSource. Now this returns Object, but you can use instanceof to determine if the object can be cast to a JTextField...
For example...
Object source = evt.getSource();
if (source instanceof JTextField) {
JTextField field = (JTextField)source;
int[] coords = field.getClientProperty("coords");
}
Take a look at How to write an Action Listener and How to write a Focus Listener for more details.
Depending on your needs, you could also take a look at Validating Input
I am trying to get user inputs from a textbox so I can take the user input to calculate the displacement for a ball.
I tried this
double initialvelocity = new JTextBox("enter your initial velocity");
so I have a variable with data that I can use. I just cant get it to work and this has been a obstacle to my first proper java project.
Could anyone suggest how I can get a variable to store data using JTextField or is there other alternatives?
A JTextField should be stored like this:
JTextField v0TextField = new JTextField ("initial velocity");
And when you want to access the current string in the text box:
String strV0TextBox = v0TextField.getText();
Then you'll want to parse this into a double:
double initialvelocity = Double.parseDouble(strV0TextField);
If you just want to get input from the user the easiest way is to use a dialog:
double value = Double.parseDouble(
JOptionPane.showInputDialog("please enter value"));
The correct way to use JTextField is
JTextField box = new JTextField(" Enter Initial Velocity");
String velocity_str = box.getText();
Than parse into a double
double initialvelocity = Double.parseDouble(velocity_str);
See this tutorial for using a jTextField here.
You want to instantiate the box like:
JTextField myTextField = new JTextField("enter your initial velocity");
//Probably should do some kind of validation on the input if you only want numbers
//get The Text and parse it as a double
double initVelocity = Double.parseDouble(myTextField.getText());