Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- class MyFrame extends Frame
- {
- public MyFrame(String title)
- {
- super(title);
- setLayout(new GridLayout(2,2));
- //setLocationRelativeTo(null);
- Dimension dim = getToolkit().getScreenSize();
- int screenWidth = dim.width;
- int screenHeight = dim.height;
- setLocation((screenWidth-100)/2,(screenHeight-170)/2);
- setSize(170,100);
- setVisible(true);
- setResizable(false);
- Label lc = new Label("Celsius");
- add(lc);
- TextField cel = new TextField(40);
- add(cel);
- Label lf = new Label("Fahrenheit");
- add(lf);
- TextField fah = new TextField(40);
- add(fah);
- cel.addActionListener(new TempListener(cel,fah,this));
- fah.addActionListener(new TempListener(cel,fah,this)); //Fahrenheit
- addWindowListener(new WindowClose());
- }
- }
- class TempListener extends Component implements ActionListener
- {
- TextField fah,cel;
- Frame f;
- public TempListener(TextField cel, TextField fah,Frame f)
- {
- this.fah=fah;
- this.f=f;
- this.cel=cel;
- }
- public void actionPerformed(ActionEvent ae)
- {
- try
- {
- Object source = ae.getSource();
- String text;
- double originalValue;
- double convertedValue;
- if(source==cel)
- {
- text=cel.getText();
- originalValue = Double.parseDouble(text);
- convertedValue=((originalValue*(9.0/5.0)+32));
- fah.setText(" " + convertedValue);
- }
- else
- {
- text=fah.getText();
- originalValue = Double.parseDouble(text);
- convertedValue = (originalValue-32)*(5.0/9.0);
- cel.setText(" "+ convertedValue);
- }
- }
- catch(Exception e)
- {
- JOptionPane.showMessageDialog(f,"Error: " +e.getMessage() + "\n\nTry entering again", "Input error", JOptionPane.ERROR_MESSAGE);
- cel.setText("");
- fah.setText("");
- }
- }
- }
- class WindowClose extends WindowAdapter
- {
- public void windowClosing(WindowEvent we)
- {
- System.exit(0);
- }
- }
- public class Temperature
- {
- public static void main(String args[])
- {
- Frame f = new MyFrame("C-F");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement