2011. 7. 13. 12:07

자바 스윙(Java Swing)을 활용한 간단한 계산기

 

import java.awt.FlowLayout ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.JTextField ; import javax.swing.JButton ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; public class SwingCalc1st extends JFrame implements ActionListener { private JLabel labelPlus ; private JLabel labelEqual ; private JTextField textFieldLeftNum ; private JTextField textFieldRightNum ; private JTextField textFieldResult ; private JButton btn ; SwingCalc1st() { super() ; labelPlus = new JLabel(" + ") ; labelEqual = new JLabel(" = ") ; textFieldLeftNum = new JTextField("", 8) ; textFieldRightNum = new JTextField("", 8) ; textFieldResult = new JTextField("", 12) ; btn = new JButton("계산하기") ; this.setLayout( new FlowLayout() ) ; this.add(textFieldLeftNum) ; this.add(labelPlus) ; this.add(textFieldRightNum) ; this.add(labelEqual) ; this.add(textFieldResult) ; this.add(btn) ; textFieldLeftNum.setHorizontalAlignment(JTextField.RIGHT) ; textFieldRightNum.setHorizontalAlignment(JTextField.RIGHT) ; textFieldResult.setHorizontalAlignment(JTextField.RIGHT) ; btn.addActionListener(this) ; this.setTitle("간단한 스윙 계산기") ; this.setSize(500, 70) ; this.setLocation(200, 200) ; this.setVisible(true) ; this.setDefaultCloseOperation(EXIT_ON_CLOSE) ; } public static void main(String[] args) { SwingCalc1st sc1 = new SwingCalc1st() ; } public void actionPerformed(ActionEvent ae) { double result = Double.parseDouble(textFieldLeftNum.getText()) + Double.parseDouble(textFieldRightNum.getText()) ; textFieldResult.setText( Double.toString(result) ) ; } }