JRadioButton이란?
JRadioButton은 JToggleButton의 하위 클래스로, 선택(selected) 또는 해제(deselected)라는 두 가지 상태를 가지는 버튼입니다. 체크박스와 달리 라디오 버튼은 ButtonGroup 클래스를 통해 그룹으로 묶여 관리되며, 동일한 그룹 안에서는 한 번에 하나의 라디오 버튼만 선택할 수 있습니다. 그룹 내에서 새로운 라디오 버튼이 선택되면, 이전에 선택되어 있던 버튼은 자동으로 해제됩니다.
이러한 라디오 버튼들은 BoxLayout을 활용하면 수평 또는 수직 방향으로 손쉽게 정렬할 수 있습니다.
수평 정렬 예제 코드
아래 예제에서는 Box.createHorizontalBox()로 생성한 수평 박스 4개에 각각 5개씩, 총 20개의 라디오 버튼을 배치합니다. 그리고 GridLayout을 사용해 이 박스들을 세로로 나열함으로써, 각 행마다 라디오 버튼 5개가 수평으로 정렬된 화면을 만듭니다.
import java.awt.*;
import javax.swing.*;
public class HorizontalRadioButtonsTest extends JPanel {
public HorizontalRadioButtonsTest() {
JRadioButton jrb1 = new JRadioButton(" RB1");
JRadioButton jrb2 = new JRadioButton(" RB2");
JRadioButton jrb3 = new JRadioButton(" RB3");
JRadioButton jrb4 = new JRadioButton(" RB4");
JRadioButton jrb5 = new JRadioButton(" RB5");
Box box1 = Box.createHorizontalBox();
box1.add(jrb1);
box1.add(jrb2);
box1.add(jrb3);
box1.add(jrb4);
box1.add(jrb5);
JRadioButton jrb6 = new JRadioButton(" RB6");
JRadioButton jrb7 = new JRadioButton(" RB7");
JRadioButton jrb8 = new JRadioButton(" RB8");
JRadioButton jrb9 = new JRadioButton(" RB9");
JRadioButton jrb10 = new JRadioButton(" RB10");
Box box2 = Box.createHorizontalBox();
box2.add(jrb6);
box2.add(jrb7);
box2.add(jrb8);
box2.add(jrb9);
box2.add(jrb10);
JRadioButton jrb11 = new JRadioButton(" RB11");
JRadioButton jrb12 = new JRadioButton(" RB12");
JRadioButton jrb13 = new JRadioButton(" RB13");
JRadioButton jrb14 = new JRadioButton(" RB14");
JRadioButton jrb15 = new JRadioButton(" RB15");
Box box3 = Box.createHorizontalBox();
box3.add(jrb11);
box3.add(jrb12);
box3.add(jrb13);
box3.add(jrb14);
box3.add(jrb15);
JRadioButton jrb16 = new JRadioButton(" RB16");
JRadioButton jrb17 = new JRadioButton(" RB17");
JRadioButton jrb18 = new JRadioButton(" RB18");
JRadioButton jrb19 = new JRadioButton(" RB19");
JRadioButton jrb20 = new JRadioButton(" RB20");
Box box4 = Box.createHorizontalBox();
box4.add(jrb16);
box4.add(jrb17);
box4.add(jrb18);
box4.add(jrb19);
box4.add(jrb20);
setLayout(new GridLayout(4, 1));
add(box1);
add(box2);
add(box3);
add(box4);
}
public static void main(String[] args) {
JFrame frame = new JFrame("HorizontalRadioButtons Test");
frame.add(new HorizontalRadioButtonsTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(375, 250);
frame.setVisible(true);
}
}
실행 결과
프로그램을 실행하면 아래 그림과 같이 라디오 버튼들이 각 행마다 5개씩 수평으로 깔끔하게 정렬되어 표시되는 것을 확인할 수 있습니다.
