Does anyone know a way that i can simplify this code?
Here is my code. Basically it allows me to enter an integer and I can prompt the user to press one of two buttons which then converts the integer into Fahrenhiet or Celcius.
Here is my code:
thanks in advance
Here is my code. Basically it allows me to enter an integer and I can prompt the user to press one of two buttons which then converts the integer into Fahrenhiet or Celcius.
Here is my code:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FtoCConversionTest{
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
ConvertorFrame frame = new ConvertorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ConvertorFrame extends JFrame{
public ConvertorFrame(){
setTitle("Fahrenheit to Celsius Calculator");
ConvertorPanel panel = new ConvertorPanel();
add(panel);
pack();
}
}
class ConvertorPanel extends JPanel{
public ConvertorPanel(){
setLayout(new BorderLayout());
//add the panel
panel = new JPanel();
//add JTextField and position it
textField = new JTextField();
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(2,1));
//add the text field label and position it
northPanel.add(new JLabel("Type the number to convert below: ", SwingConstants.LEFT));
northPanel.add(textField);
add(northPanel, BorderLayout.NORTH);
//set the panel and position it
panel.setLayout(new GridLayout(1,2));
//add buttons and position them
cButton = new JButton("Convert to Celsius");
panel.add(cButton);
fButton = new JButton("Convert to Fahrenheit");
panel.add(fButton);
add(panel, BorderLayout.SOUTH);
Converter converter = new Converter();
cButton.addActionListener(converter);
fButton.addActionListener(converter);
}
private class Converter implements ActionListener{
public void actionPerformed (ActionEvent event){
if (event.getSource() == cButton){
int c = (int)(((Double.parseDouble(textField.getText()))- 32) * 0.56);
textField.setText(c + " °C");
textField.requestFocus();
textField.selectAll();
}
else if(event.getSource() == fButton){
int f = (int)(((Double.parseDouble(textField.getText()))* 1.8) + 32);
textField.setText(f + " ºF");
textField.requestFocus();
textField.selectAll();
}
}
}
private JButton cButton, fButton;
private JTextField textField;
private JPanel panel;
}
Comment