JAVA :: 스윙 컴포넌트(1)

smi·2021년 2월 12일
0

JAVA (자바)

목록 보기
25/62
post-thumbnail

➕ 상속 구조

JComponent추상 클래스이며, 스윙 컴포넌트들이 상속받는 많은 공통 메소드와 상수들을 구현하고 있다. 또한 새로운 컴포넌트를 만들려면 반드시 JComponent를 상속받아 만들어야 한다.


💡 JLabel

💬 생성자

JLabel() // 빈 레이블
JLabel(Icon image) // 이미지 레이블
JLabel(String text) // 문자열 레이블
JLabel(String text, Icon image, int hAlign) // 문자열과 이미지를 가진 레이블

ㆍhAlign : 수평 정렬의 값 (ex. SwingConstants.LEFT, RIGHT, CENTER 중 하나)
👉 예시
ImageIcon image = new ImageIcon("images/sunset.jpg"); // 이미지 로딩 
JLabel imageLabel = new JLabel(image);

💡 JButton

💬 버튼을 마우스로 선택하면 Action 이벤트가 발생한다.

💬 생성자

JButton() // 빈 버튼
JButton(Icon image) // 이미지 버튼
JButton(String text) // 문자열 버튼
JButton(String text, Icon image) // 문자열과 이미지 모두 가진 버튼 

💬 이미지 버튼 만들기

normalIcon : 버튼이 보통 상태에 있을 때 출력되는 디폴트 이미지
rolloverIcon : 버튼 위에 마우스가 올라가면 출력되는 이미지
pressedIcon : 마우스 버튼이 눌러져 있는 동안 출력되는 이미지

👉 예시
ImageIcon normalIcon = new ImageIcon("images/normalIcon.gif");
ImageIcon rolloverIcon = new ImageIcon("images/rolloverIcon.gif");
ImageIcon pressedIcon = new ImageIcon("images/pressedIcon.gif");
        
JButton button = new JButton("버튼", normalIcon); //normalIcon 달기
button.setRolloverIcon(rolloverIcon); // rolloverIcon 달기
button.setPressedIcon(pressedIcon); // pressedIcon 달기

💬 normalIcon 이미지 바꾸기

ImageIcon newIcon = new ImageIcon("images/newIcon.gif");
button.setIcon(newIcon); // 디폴트 이미지 변경

💡 JCheckBox

💬 선택과 해제의 두 상태만 가지는 컴포넌트

💬 생성자

JCheckBox();
JCheckBox(Icon image);
JCheckBox(Icon image, boolean selected); // selected(true이면 선택 상태)
JCheckBox(String text, Icon image);
JCheckBox(String text, Icon image, boolean selected);

💬 setSelected() : 체크박스의 상태를 변경

JCheckBox apple = new JCheckBox("사과");
apple.selSelected(true); // 선택 상태로 변경. false면 해제 상태

💬 Item 이벤트 : 체크박스나 라디오 버튼이 선택되거나 해제될 때 발생하는 이벤트

ItemEvent 객체 메소드 : Item 이벤트가 발생하면 ItemEvent 객체가 생성되어 itemStateChanged()에 전달된다.

int getStateChang()
// 체크박스가 선택된 경우 ItemEvent.SELECTED, 해제된 경우 ,ItemEvent.DESELECTED 리턴
Object getItem()
// 이벤트를 발생시킨 아이템 객체 리턴. 체크박스의 경우 JCheckBox 컴포넌트의 레퍼런스 리턴

💡 JRadioButton

💬 체크박스와 거의 동일하지만 라디오버튼은 버튼 그룹에 속한 하나의 라디오버튼만 선택 가능하다.

💬 생성자

JRadioButton();
JRadioButton(Icon image);
JRadioButton(Icon image, boolean selected); // selected(true이면 선택 상태)
JRadioButton(String text);
JRadioButton(String text, boolean selected);
JRadioButton(String text, Icon image);
JRadioButton(String text, Icon image, boolean selected); 

💬 라디오버튼 생성과정 : 버튼 그룹 객체 생성 ⇒ 라디오버튼 컴포넌트 생성 ⇒ 라디오버튼을 버튼 그룹에 삽입 ⇒ 라디오버튼을 컨테이너에 삽입

💬 라디오버튼도 선택되거나 해제되어 상태가 달라지면 Item 이벤트가 발생한다.

profile
공부한 거 올려요 :)

0개의 댓글