TempKalk.java [Last ned]

/*
 * GUI-program for omregning av temperaturer
 * mellom grader Celsius og Fahrenheit.
 */
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class TempKalk extends JFrame implements ActionListener {
 
  JTextField txtC, txtF;
     JButton omregn, blank;
 
  public static void main(String[] args)  {
    TempKalk vindu = new TempKalk();
    vindu.setTitle("Temperaturkalkulator");
    vindu.setDefaultCloseOperation(EXIT_ON_CLOSE);
    vindu.opprettGUI();
    vindu.pack();
    vindu.setVisible(true);
  }
 
  private void opprettGUI() {
    setLayout( new FlowLayout() );
    add( new JLabel("Grader C:") );
    txtC = new JTextField(4);
    add(txtC);
    omregn = new JButton("Omregn");
    omregn.addActionListener(this);
    add(omregn);
    add( new JLabel("Grader F:") );
    txtF = new JTextField(4);
    add(txtF);
    blank = new JButton(" Blank ut ");
    blank.addActionListener(this);
    add(blank);
  }
 
  public void actionPerformed (ActionEvent e) {
    if ( e.getSource() == blank ) {
      txtC.setText("");
      txtF.setText("");
    }
    else if ( e.getSource() == omregn ) {
      String celsTxt = txtC.getText();
      String fahrTxt = txtF.getText();
      if ( celsTxt.equals("") ) {
        double F = Double.parseDouble(fahrTxt);
        double C = (5 * F - 160) / 9;
        txtC.setText( "" + avrund(C) );
      }
      else if ( fahrTxt.equals("") ) {
        double C = Double.parseDouble(celsTxt);
        double F = 32 + (9.0/5) * C;
        txtF.setText( "" + avrund(F) );
      }
      /**********************************************
      * NB! Alternativet til  Double.parseDouble()
      * er å bruke  import java.lang.Double.*;
      * i headingen og så kun  parseDouble()  her.
      **********************************************/
    }
  }
 
  // Hjelpemetode
  private double avrund(double tall) {
     return (int)(tall*10 + 0.5) / 10.0;
  }
 
}
Kildekode blir vist ved hjelp av GeSHi.