Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm having trouble figuring out the logic behind why my code isn't working. I'm new to GUI programming and java as well, and I'm still a little rough on the format of creating a GUI program. In the code I'm trying to convert Celsius to Fahrenheit and vice versa. Any help would be appreciated. Thanks!
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class myGUIClass<FahrenheitButtonHandler> extends JFrame{
private JLabel msgCelsius;
private JLabel msgFahrenheit;
private JButton btnCelsius;
private JButton btnFahrenheit;
private static JTextField fldCelsius;
private static JTextField fldFahrenheit;
Container contain;
public myGUIClass(String myGUIWindow){
super("myGui");
contain = getContentPane();
contain.setLayout(new FlowLayout());
msgCelsius = new JLabel("Degrees in Celsius");
btnCelsius = new JButton("Convert From Celsius to Fahrenheit");
fldCelsius = new JTextField(15);
msgFahrenheit = new JLabel("Degrees in Fahrenheit ");
btnFahrenheit = new JButton("Convert From Fahrenheit to Celsius");
fldFahrenheit = new JTextField(15);
contain.add(msgCelsius);
contain.add(fldCelsius);
contain.add(btnCelsius);
contain.add(msgFahrenheit);
contain.add(fldFahrenheit);
contain.add(btnFahrenheit);
CelsiusButtonHandler btnHandlerCelsius = new CelsiusButtonHandler();
btnCelsius.addActionListener(btnHandlerCelsius);
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerFahrenheit);
setSize(400,200);
setVisible(true);
}//end method
private class CelsiusButtonHandler implements ActionListener{
//#Override
//implement the listener interface methods to process the events
public void actionPerformed(ActionEvent ae){
Integer celsius;
Integer fahrenheit;
try{
if (ae.getSource() == btnCelsius){
celsius = Integer.parseInt(fldCelsius.getText());
fahrenheit = Math.round((9 /(float)5)) * (celsius + 32);
fldFahrenheit.setText(fahrenheit.toString());
}//end if
}//end try
catch (Exception e){
fldFahrenheit.setText("");
}//end catch
}//end inner class
}//end class
private class FahrenheitButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent a){
Integer fahrenheit1;
Integer celsius1;
try{
if(a.getSource()== btnFahrenheit){
fahrenheit1 = Integer.parseInt(fldFahrenheit.getText());
celsius1 = Math.round((5 / (float)9)) * (fahrenheit1 - 32);
fldCelsius.setText(celsius1.toString());
}//end if
}//end try
catch (Exception e){
fldCelsius.setText("");
}//end catch
}//end method
}//end private class
public static void main (String[] args){
#SuppressWarnings("rawtypes")
myGUIClass guiClass = new myGUIClass(null);
guiClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main
}//end outer class
//theres a problem with the math in these lines:
//am i not casting these correctly? whenever i input 50 i'm supposed to get 122 but i get 164.
//fahrenheit = Math.round((9 /(float)5)) * (celsius + 32);
//celsius1 = Math.round((5 / (float)9)) * (fahrenheit1 - 32);
Ignoring the code issues that make the example uncompliable...
You have an integer division problem...
celsius = (5 / 9) * (fahrenheit - 32);
If 5/9 = 0 as the resulting value is converted to an integer.
Try using something more like...
celsius = Math.round((5 / (float)9)) * (fahrenheit - 32);
Now, personally, I would be using a double or float instead of an int and formatting the result but that's me. You'll need to do the same thing FahrenheitButtonHandler
In your FahrenheitButtonHandler class, you are also applying the wrong value to the text field...
celsius1 = Integer.parseInt(fldFahrenheit.getText());
fahrenheit1 = celsius1*(9/5)+32;
fldCelsius.setText(celsius1.toString());
You applying the celsius1 value, which is the value your extract from the fldFahrenheit field, not the calculated result, it should be
fldCelsius.setText(fahrenheit1.toString());
...but remember, there is still the interger division problem you need to correct for this...
Finally, you registered the wrong ActionListener to the btnFahrenheit
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerCelsius); // <-- Wrong listener...
It should be...
FahrenheitButtonHandler btnHandlerFahrenheit = new FahrenheitButtonHandler();
btnFahrenheit.addActionListener(btnHandlerFahrenheit);
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?
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 have a question I have a program where I want to test the users ability to remember a random list of colors. Based off if the users input is right or wrong it will ask for the next color.
So I got it all work up to where the user inputs the first color. Before it has the user input on the first color. The program is already assuming the user input is wrong, even tho it hasn't asked for any input.
I know from previously knowledge I could like flush the buffer, can you do that with JOptionPane?
Or is this another issue I'm not seeing?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Testing
{
//Intialization of the whole program for everything to pass information
public JFrame main;
public JLabel lbInsturctions;
public JLabel welcomeMessage;
public JLabel homeScreen;
public JLabel homeScreenColors;
public JTextField txtInput;
public int num = 1;
public String colorList = "";
public String[] color = {"red","green","blue","brown","yellow", "gold", "orange", "silver"};
public String[] solution = new String[5];
//sets up the window and random colors
public Testing ()
{
Random r = new Random();
for (int i = 0; i<solution.length; i++)
{
solution[i] = color[r.nextInt(7)];
colorList = Arrays.toString(solution);
}
JOptionPane.showMessageDialog(null, "Lets test your memory. Memorize these colors: " + colorList);
main = new JFrame ();
main.setSize (500,300);
main.setTitle ("Ultimate Colors");
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setLayout(new FlowLayout());
intializeGame();
main.setVisible(true);
}
public void intializeGame ()
{
//All Intiazations
lbInsturctions = new JLabel();
homeScreen = new JLabel();
txtInput= new JTextField(null, 15);
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
main.add(lbInsturctions);
main.add(txtInput);
txtInput.addActionListener(new colorTester());
}
public class colorTester implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
//grabs the users input to see if it is corect
String guess= "";
guess = txtInput.getText();
System.out.println(guess);
//Checks to see if the users input is the same as the initalizaton
if (color[num+1].equalsIgnoreCase(guess) || num > 6)
{
System.out.println("You got it!");
++num;
lbInsturctions.setText("Enter color number " + num + ":");
txtInput.setText("");
}
//if the User input is wrong
else
{
System.out.println("It's a good thing your not graded!");
txtInput.setVisible(false);
lbInsturctions.setText("It's a good thing this is not graded!");
}
if (num == 5)
{
lbInsturctions.setText("You memory is perfect good job!");
txtInput.setVisible(false);
}
}
}
}//end of program
This has nothing to do with flushing buffers.
You're getting user input here: guess = txtInput.getText(); which is in the intializeGame method. Meaning you're getting the text from the txtInput JTextField on its creation, before the user has had a chance to enter anything into the field. I think that you're used to programming linear console programs, where you get the user's input immediately, but that's not how event-driven GUI's work. Instead you must get and react to the user's input on event, here perhaps the ActionListener of some button. Perhaps your code needs a "submit" JButton or something similar, and in its ActionListener, extract the input from the JTextField and respond to it. Do this and your code has a better chance of working.
Other issues:
you don't ever appear to have added your txtInput JTextField into the GUI.
same for the homeScreen JLabel
Edit your new code posted at the bottom of your question has the same problem.
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
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);
}
}