S.S.G
JRadioButton & Item 본문
3개의 라디오버튼을 생성하여 각 라디오버튼이 선택되면 해당하는 이미지를 출력하는 응용프로그램 만들어 보기.
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Test extends JFrame {
Container contentPane;
JRadioButton[] radio = new JRadioButton[3];
String[] text = { "사과", "배", "체리" };
ImageIcon[] image = {
new ImageIcon("images/apple.jpg"), new ImageIcon("images/pear.jpg"),
new ImageIcon("images/cherry.jpg") };
JLabel imageLabel = new JLabel(); // 이미지가 출력될 컴포넌트
Test() {
setTitle("연습");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel radioPanel = new JPanel(); //3개의 라디오 버튼이 부착될 패널
radioPanel.setBackground(Color.GRAY);
ButtonGroup g = new ButtonGroup(); //버튼 그룹 객체 생성
for (int i = 0; i < radio.length; i++) {
radio[i] = new JRadioButton(text[i]); //라디오버튼 생성 하고
g.add(radio[i]); //버튼 그룹에 넣고
radioPanel.add(radio[i]); //패널에 부착하기
radio[i].addItemListener(new MyItemListener()); //라디오버튼 Item 리스너
}
radio[2].setSelected(true); //최초에 체리가 선택되어 있도록 설정
contentPane.add(radioPanel, BorderLayout.NORTH);
contentPane.add(imageLabel, BorderLayout.CENTER);
imageLabel.setHorizontalAlignment(SwingConstants.CENTER); //이미지 중앙정렬
setSize(400, 500);
setVisible(true);
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.DESELECTED)
return; //라디오버튼이 선택 해제된 경우 그냥 리턴
if (radio[0].isSelected())
imageLabel.setIcon(image[0]);
else if (radio[1].isSelected())
imageLabel.setIcon(image[1]);
else
imageLabel.setIcon(image[2]);
}
}
public static void main(String arg[]) {
new Test();
}
}
실행 결과
'코딩 > JAVA' 카테고리의 다른 글
JColorChooser (컬러 다이얼로그) (0) | 2016.07.06 |
---|---|
Action 이벤트를 이용한 콤보박스 (0) | 2016.07.05 |
MouseListener 사용 해보기 (0) | 2016.07.04 |
이벤트 리스너 작성해보기(내부클래스, 독립된 클래스, 익명 클래스) (0) | 2016.07.04 |
Collections 클래스 활용 (0) | 2016.07.04 |