Hi everyone,
I'm trying to write a code that converts the number that a user inputs to either Celsius or Fahrenheit simply by pressing a button. So far I was able to compile and run the program displaying the panel, buttons, and the text field but I'm not sure how to write the code that gets the input and write the code to do the calculation and display it n the text field. Help me please.
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FtoCConversionTest{
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
Frame frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class Frame extends JFrame
{
public Frame()
{
setTitle("Fehrenheit to Celsius converter");
Panel panel = new Panel();
add(panel);
pack();
}
}
class Panel extends JPanel
{
public Panel()
{
setLayout(new BorderLayout());
//add text field and locate it
textField = new JTextField();
add(textField, BorderLayout.CENTER);
//add JPanel
panel = new JPanel();
panel.setLayout(new GridLayout(1,2));
//add buttons and locate them
addButton("Convert to Celsius", command);
addButton("Convert to Fehrenheit", command );
add(panel, BorderLayout.SOUTH);
}
private void addButton(String lable, ActionListener listener){
JButton button = new JButton(lable);
button.addActionListener(listener);
panel.add(button);
}
private JTextField textField;
private JPanel panel;
private ActionListener command;
}