본문 바로가기
프로그래밍 언어/자바

AWT - GUI 프로그래밍 #3 Button

by 블루데이제이 2022. 9. 12.
728x90
반응형

▶ Button

프로그램에서 기본적으로 사용되는 컴포넌트입니다. 주로 사용자의 입력을 받아들일 때 사용됩니다.

■ 주요 생성자

- Button() : 빈 버튼 생성

- Button(String label) : 주어진 label을 표시하는 버튼을 생성

Button button = new Button("버튼");

■ 주요 메소드

- String getLabel() : 버튼의 텍스트를 얻음

- void setLabel(String label) : 버튼의 텍스트 설정

package awt;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;

class ButtonFrame{
	private Panel panel;
	private Button redButton, blueButton, yellowButton;
	public ButtonFrame(String title) {
		Frame frame = new Frame(title);
		panel = new Panel();
		
		redButton = new Button("빨간색");
		blueButton = new Button("파란색");
		yellowButton = new Button("노란색");
		
		panel.add(redButton);
		panel.add(blueButton);
		panel.add(yellowButton);
		
		frame.add(panel);
		
		frame.setSize(500,500);
		frame.setLocation(100, 100);
		frame.setVisible(true);
	}
}

public class ButtonTest {	

	public static void main(String[] args) {
		new ButtonFrame("Button");
	}
}

기본적인 Button을 나타내는 소스입니다. 버튼을 클릭해도 아무런 이벤트가 발생하지 않습니다.

지난 포스팅에서 배웠던 버튼에 리스너를 등록해야 합니다.

여기에서는 버튼을 클릭하면 Panel의 색상을 바꾸는 이벤트를 등록하도록 하겠습니다.


package awt;

import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class ButtonFrame{
	private Panel panel;
	private Button redButton, blueButton, yellowButton;
	private ColorListener listener;				//이벤트 리스너
	public ButtonFrame(String title) {
		Frame frame = new Frame(title);
		listener = new ColorListener();
		panel = new Panel();
		
		redButton = new Button("빨간색");
		redButton.setActionCommand("red");		//ActionCommand 설정
		redButton.addActionListener(listener);	//이벤트 리스너 등록
		
		blueButton = new Button("파란색");
		blueButton.setActionCommand("blue");
		blueButton.addActionListener(listener);
		
		yellowButton = new Button("노란색");
		yellowButton.setActionCommand("yellow");
		yellowButton.addActionListener(listener);
		
		panel.add(redButton);
		panel.add(blueButton);
		panel.add(yellowButton);
		
		frame.add(panel);
		
		frame.setSize(500,500);
		frame.setLocation(100, 100);
		frame.setVisible(true);
	}
	
	class ColorListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			String command = e.getActionCommand();
			if(command.equals("red")) {
				panel.setBackground(Color.RED);
			}else if(command.equals("blue")) {
				panel.setBackground(Color.BLUE);
			}else if(command.equals("yellow")){
				panel.setBackground(Color.YELLOW);
			}
			
		}
		
	}
}


public class ButtonTest {	

	public static void main(String[] args) {
		new ButtonFrame("Button");
	}
}

728x90
반응형

'프로그래밍 언어 > 자바' 카테고리의 다른 글

[자바] 배열로 큐 구현하기  (78) 2024.05.08
[이클립스] import 한번에 하기  (0) 2024.02.01
AWT - GUI 프로그래밍 #2 Label  (0) 2022.09.12
AWT - GUI 프로그래밍 #1  (0) 2022.09.12
예외 처리  (0) 2022.09.12