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
Related
Yes, I read through the various post with regards to this but their scenarios where a bit different and didn't explain what is going on in the background.
Lets say the following program is created in a country where decimal points use '.' notation but then executed in a country which uses ',' notation.
For example, 1.23 and 1,23 are technically the same number but with different notations.
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.*;
class LocaleTestDecimal extends JFrame implements ActionListener
{
static JTextField t;
static JFrame f;
static JButton b;
static JLabel l;
static JLabel localLabel;
LocaleTestDecimal()
{
}
public static void main(String[] args)
{
Locale locale = Locale.getDefault();
f = new JFrame("Locale = " + locale.toString());
l = new JLabel("nothing entered");
b = new JButton("submit");
LocaleTestDecimal te = new LocaleTestDecimal();
b.addActionListener(te);
t = new JTextField(16);
//default value of 1.23
t.setText(Double.toString(1.23));
NumberFormat format = NumberFormat.getInstance(Locale.ITALY);
Number number = null;
try {
number = format.parse("1.23");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double d = number.doubleValue();
l.setText(Double.toString(number.doubleValue()));
JPanel p = new JPanel();
p.add(t);
p.add(b);
p.add(l);
f.add(p);
f.setSize(300, 300);
f.show();
}
// if the button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("submit")) {
// set the text of the label to the text of the field
l.setText(t.getText());
// set the text of field to blank
t.setText(" ");
}
}
}
The above code runs fine and as expected when my Locale is set to English.
After changing my Windows Region and Format to Italy.
And changed my Eclipse VM arguments
The numbers still use the '.' notation for numbers. Even using the NumberFormat didn't seem to change the value on the JFrame.
The title of the JFrame contains the locale which confirms it is Italy.
Question 1:
Why am I not seeing numbers using the ',' notation?
Question 2:
As these numbers expected to dynamically change simply based on the Locale set?
I Need To convert years of days and this error stops me.
help please.. need to pass it now.
error: bad operand types for binary operator '*'
error: result = screen * 365;
^
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DaysOfYears extends JFrame implements ActionListener
{
JTextField screen = new JTextField(30);
JButton conBtn = new JButton("Convert");
JLabel jb = new JLabel ("");
private double result;
public DaysOfYears(){
super("Convert Your Years in Days");
setSize(400, 200);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(screen);
add(conBtn);
add(jb);
conBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
result = screen * 365;
jb.setText(""+result);
}
public static void main (String[] args) {
DaysOfYears days = new DaysOfYears();
days.show(true);
}
}
I think you wanted to parse the text value of your JTextField and then perform your multiplication. Something like,
result = Integer.parseInt(screen.getText()) * 365;
Note that leap years have 366 days.
The JTextField holds its contents as String. You will need to convert it to integer unless of course you are supplying a string representation of a double data type within the JTextField.
Try something like:
result = Integer.valueOf(screen.getText()) * 365;
Here screen is a object of JTextFieldso multiply operation will not perform on the object of JTextField type you can grab the values of this object convert it into any Number type then try to multiplying. It will solve your problem .
Try this......
result = Integer.parseInt(screen.getText()) * 365;
// this will perform multiply actually. Thnak you
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?.
I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered
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);
}
}