Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

I need help withButtonHandler, getActionCommand

843806Mar 4 2009 — edited Mar 5 2009
I trying to write a GUI app. I have to convert Celsius to Fahrenheit and vice versa.
This is what I got so far, but when I press any of the two buttons I got an error message

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JLabel;

public class Conversion extends JFrame
{
private JTextField textField1;
private JTextField textField2;
private JButton buttonF;
private JButton buttonC;
private JLabel label1;


public Conversion()
{
super("Converting Farenheit and Celcius degrees");
setLayout( new FlowLayout() );

label1 = new JLabel( "Enter number" );
//label1 = setVerticalTextPosition(swingConstants.TOP);
//label1 = setHorizontalTextPosition(swingConstants.LEFT);
add( label1 );

textField1 = new JTextField( 10 );
add( textField1 );

textField2 = new JTextField( 10 );
add( textField2 );

buttonC = new JButton("Celcius" );
add( buttonC );

buttonF = new JButton("Farenheit");
add( buttonF );

ButtonHandler handler = new ButtonHandler();
buttonF.addActionListener( handler );
buttonC.addActionListener( handler );
} // end constructor

private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
String num = "";
double result;

if( event.getSource() == buttonF ){
num = event.getActionCommand();
double c = Double.parseDouble(num);
result = getFarenheit(c);
textField2.setText("" + result);

}
else if( event.getSource() == buttonC ){
num = event.getActionCommand();
double f = Double.parseDouble(num);
result = getCelcius(f);
textField2.setText(result + "");
}

}
}
public double getFarenheit(double c)
{
double result = 9 / 5.0 * c + 32;
return result;
}
public double getCelcius(double f)
{
double result = 5.0/9 * (f - 32);;
return result;
}
}// end class ConversionFrame
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 2 2009
Added on Mar 4 2009
11 comments
256 views