자바
자바 UI - Swing (RadioButton 응용)
록's
2023. 2. 16. 12:45
728x90
반응형
라디오 종류
러시안블루
라가머핀
라팜
맹크스
JRadioButton 버튼을 4개로 만들어서 만들기
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioButtonTest extends JFrame{
private JPanel radioPanel;
private JRadioButton rbCat1;
private JRadioButton rbCat2;
private JRadioButton rbCat3;
private JRadioButton rbCat4;
private JLabel lblPicture;
public RadioButtonTest() {
setTitle("RadioButtonTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(getRadioPanel(), BorderLayout.WEST);
this.getContentPane().add(getLblPicture(), BorderLayout.CENTER);
pack();
}
public JPanel getRadioPanel() {
if(radioPanel == null) {
radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4,1));
radioPanel.add(getRbCat1());
radioPanel.add(getRbCat2());
radioPanel.add(getRbCat3());
radioPanel.add(getRbCat4());
ButtonGroup group = new ButtonGroup();
group.add(getRbCat1());
group.add(getRbCat2());
group.add(getRbCat3());
group.add(getRbCat4());
}
return radioPanel;
}
public JRadioButton getRbCat1() {
if(rbCat1 == null) {
rbCat1 = new JRadioButton();
rbCat1.setText("Cat1");
rbCat1.setSelected(true);
rbCat1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getLblPicture().setIcon(new ImageIcon(getClass().getResource("Cat1.gif")));
}
});
}
return rbCat1;
}
public JRadioButton getRbCat2() {
if(rbCat2 == null) {
rbCat2 = new JRadioButton();
rbCat2.setText("Cat2");
rbCat2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getLblPicture().setIcon(new ImageIcon(getClass().getResource("Cat2.gif")));
}
});
}
return rbCat2;
}
public JRadioButton getRbCat3() {
if(rbCat3 == null) {
rbCat3 = new JRadioButton();
rbCat3.setText("Cat3");
rbCat3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getLblPicture().setIcon(new ImageIcon(getClass().getResource("Cat3.gif")));
}
});
}
return rbCat3;
}
public JRadioButton getRbCat4() {
if(rbCat4 == null) {
rbCat4 = new JRadioButton();
rbCat4.setText("Cat4");
rbCat4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getLblPicture().setIcon(new ImageIcon(getClass().getResource("Cat4.gif")));
}
});
}
return rbCat4;
}
public JLabel getLblPicture() {
if(lblPicture == null) {
lblPicture = new JLabel();
lblPicture.setIcon(new ImageIcon(getClass().getResource("Cat1.gif")));
}
return lblPicture;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
RadioButtonTest jFrame = new RadioButtonTest();
jFrame.setVisible(true);
}
});
}
}
- 실행 결과 -
728x90
반응형