2011. 7. 13. 09:25

자바 스윙(Java Swing)과 이벤트 핸들러를 사용한 화씨 온도 섭씨로 환산하기

import java.awt.GridLayout ;
import java.awt.BorderLayout ;

import javax.swing.JFrame ;
import javax.swing.JPanel ;

import javax.swing.JLabel ;
import javax.swing.JTextField ;
import javax.swing.JButton ;

import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;

public class Fah2CelSwing extends JFrame implements ActionListener {
	JPanel panel = new JPanel() ;

	private JLabel labelFah ;
	private JLabel labelCel ;

	private JTextField textFieldFah ;
	private JTextField textFieldCel ;

	private JButton btn ; 

	Fah2CelSwing() {
		super() ;

		labelFah = new JLabel("화씨 온도") ;
		labelCel = new JLabel("섭씨 온도") ;

		textFieldFah = new JTextField() ;
		textFieldCel = new JTextField() ;

		btn = new JButton("화씨를 섭씨로 변환한다, 실시~잉.") ;

		panel.setLayout(new GridLayout(2, 2, 4, 4)) ;

		panel.add(labelFah) ;
		panel.add(textFieldFah) ;

		panel.add(labelCel) ;
		panel.add(textFieldCel) ;	

		textFieldFah.setHorizontalAlignment(JTextField.RIGHT) ;
		textFieldCel.setHorizontalAlignment(JTextField.RIGHT) ;
		
		this.add(panel, BorderLayout.CENTER) ;	
		this.add(btn, BorderLayout.SOUTH) ;

		btn.addActionListener(this) ;
	
		this.setTitle("화씨온도 ---> 섭씨온도 변환 버튼 액션 테스트") ;
		this.setSize(300, 120) ;

		this.setLocation(200, 200) ;
		this.setVisible(true) ;

		this.setDefaultCloseOperation(EXIT_ON_CLOSE) ;
	}

	public static void main(String[] args)	 {
		Fah2CelSwing f2cS = new Fah2CelSwing() ;
	}

	public void actionPerformed(ActionEvent ae) {
		double fah = 5.0 / 9.0 * (Double.parseDouble( textFieldFah.getText() ) - 32) ;
		textFieldCel.setText(Double.toString(fah)) ;
	}
}