2015-07-29 1 views
1

У меня есть три переключателя с цветами фона, как показано ниже. enter image description hereцвет фона и равные размеры jradiobuttons

мне нужно, чтобы растянуть их все же размер, так что цвета фона однородны (с одинаковой шириной) .Tried добавлением setWidth(Dimension d), но это не работает.

public class TrafficLights { 
JFrame frame; 
JRadioButton stop,go,wait; 
JTextField signal; 
ButtonGroup grp; 
Dimension dim = new Dimension(200,30); 
public TrafficLights(){ 
    frame = new JFrame("Traffic Lights"); 
    frame.setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS)); 
    stop = new JRadioButton("Red"); 
    stop.setBackground(Color.RED); 
    stop.setSize(dim);  

    wait = new JRadioButton("Orange"); 
    wait.setBackground(Color.ORANGE); 
    wait.setSize(dim); 

    go = new JRadioButton("Green"); 
    go.setBackground(Color.GREEN); 
    go.setSize(dim); 

    grp = new ButtonGroup(); 
    grp.add(stop);grp.add(wait);grp.add(go); 
    frame.getContentPane().add(stop); 
    frame.getContentPane().add(wait); 
    frame.getContentPane().add(go); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.setMinimumSize(new Dimension(300,200)); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 
} 

ответ

3

Используйте JPanel с GridLayout, затем добавить кнопки на панели и панели к раме:

JPanel panel = new JPanel(new GridLayout(0, 1)); 
panel.add(button1); 
... 
frame.add(panel, BorderLayout.PAGE_START); 
+0

Да, я смог сделать это с помощью GridLayout и JPanel. Спасибо. Есть ли какой-либо другой ярлык? Потому что он усложняется, так как я продолжаю добавлять компоненты – Pradeep

+0

@Pradeep, я считаю, что разделение screeen на логическую группировку компонентов проще всего было разработать GUI. Нет ярлыков. – camickr

3

Вы можете использовать GridLayout(int rows, int cols):

frame = new JFrame("Traffic Lights"); 
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); 
    JPanel panel = new JPanel(new GridLayout(3, 1)); 
    frame.add(panel); 

    stop = new JRadioButton("Red"); 
    stop.setBackground(Color.RED); 
    stop.setSize(dim); 

    wait = new JRadioButton("Orange"); 
    wait.setBackground(Color.ORANGE); 
    wait.setSize(dim); 

    go = new JRadioButton("Green"); 
    go.setBackground(Color.GREEN); 
    go.setSize(dim); 

    grp = new ButtonGroup(); 
    grp.add(stop); 
    grp.add(wait); 
    grp.add(go); 
    panel.add(stop); 
    panel.add(wait); 
    panel.add(go); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.setMinimumSize(new Dimension(300, 200)); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 

Для подробнее информация: GridLayout