프로그램설명 - 반지름의 값을 적고...원 둘레와 원의 면적 버튼을 누를시 아래 텍스트필드에 그 값이 나오게 하여라.


1. 먼저 이벤트는 어떠한 행동을 하였을때 발생하는 액션리스너를 이용하였다.

2. 액션리스너를 상속받는 클래스는 외부클래스로 두었다.(이 밖에 내부클래스로 사용하는법과 그 안에 메인클래스에 함수로 사용하는법 세가지가 있다.)

3. 그리하여 총 3개의 클래스로 만들었다.

MyFrame클래스 - 스윙을 이용하여 GUI 환경의 컴포넌트들을 만들고 이벤트를 등록한다.

MyActionHandle 클래스 - 이벤트 발생시 발생되는 행동들이 실행하는 클래스.

MyFrameTest클래스 - 프로그램을 시작한다.




MyActionHandle

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

public class MyActionHandler  implements ActionListener //액션인터페이스를 사용

{

    private MyFrame f;  

   

    public MyActionHandler(MyFrame f) //포인터로 MyFrame클래스를 가져온다.

    {

        this.f = f;

    }   

    public void actionPerformed(ActionEvent e)

    {

        double d;       

        if(e.getSource()==f.getButton())

        {

            d = Double.parseDouble(f.getTextField());

            f.setTextField(d *3.14);

        }

        else if(e.getSource()==f.getButton2())

        {

            d = Double.parseDouble(f.getTextField());

            f.setTextField(d*d*3.14);

        }

    }   

}

MyFrame

import javax.swing.*;

 

public class MyFrame extends JFrame //JFrame을 상속받는다.

{

    private JPanel panel;

    private JButton b1;

    private JButton b2;

    private JLabel l1;

    private JTextField t1;

    private JTextField t2;

 

    public JButton getButton(){ //MyFrameprivate 변수로 인해 get set 함수만들기

            return b1;

        }       

    public JButton getButton2(){

            return b2;

        }       

    public String getTextField(){

            return t1.getText();

        }   

    public void setTextField(Double d){

            t2.setText(Double.toString(d));

    }     

 

    public MyFrame()

    {       

         setSize(300, 150);

         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         setTitle("연습~");

         panel = new JPanel();

         b1 = new JButton("원의 둘레");

         b2 = new JButton("원의 면적");

         l1 = new JLabel("반지름의 길이를 입력해주세요:");

         t1 = new JTextField(5);

         t2 = new JTextField(10);        

         MyActionHandler han = new MyActionHandler(this); //리스너클래스 생성

         b1.addActionListener(han); //리스너등록

         b2.addActionListener(han);        

         panel.add(l1);

         panel.add(t1);

         panel.add(b1);

         panel.add(b2);

         panel.add(t2);

         add(panel);

         setVisible(true);

    }    

}

 

MyFrameTest

public class MyFrameTest

{

    public static void main(String[] args)

    {

        MyFrame my = new MyFrame();

    }

}


Posted by 아몰라