2014-04-01 35 views
0

當我運行下面的代碼時,前2個按鈕不會出現;然而,第三個在框架中是可見的。程序沒有返回適當的RadioButton結果

public class RadioButton { 
    RadioButton(){ 
     JFrame frame = new JFrame(); 
     JRadioButton button1 = new JRadioButton("One"); 
     button1.setBounds(50, 20, 50, 20); 
     JRadioButton button2 = new JRadioButton("Two"); 
     button2.setBounds(50, 50, 50, 20); 
     JRadioButton button3 = new JRadioButton("Three"); 
     button2.setBounds(50, 80, 50, 20); 
     ButtonGroup bg = new ButtonGroup(); 
     bg.add(button1); 
     bg.add(button2); 
     bg.add(button3); 
     frame.add(button1); 
     frame.add(button2); 
     frame.add(button3); 
     frame.setSize(300, 300); 
     frame.setVisible(true); 
     frame.setLayout(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 
     new RadioButton(); 
    } 

} 
+0

我注意到你在button2上設置了兩次邊界,而從不在button3上。錯字? –

回答

1

我猜想,因爲OP將佈局管理器設置爲null,所以絕對定位是想要的。這通常不被推薦。請參閱tutorial

您需要按如下方式重新排序代碼 - 即在之前設置佈局,以設置組件的邊界。

public class RadioButton { 

RadioButton() { 
    JFrame frame = new JFrame(); 
    JRadioButton button1 = new JRadioButton("One"); 
    JRadioButton button2 = new JRadioButton("Two"); 
    JRadioButton button3 = new JRadioButton("Three"); 
    ButtonGroup bg = new ButtonGroup(); 
    frame.setLayout(null); 
    bg.add(button1); 
    bg.add(button2); 
    bg.add(button3); 
    frame.setSize(300, 300); 
    frame.add(button1); 
    frame.add(button2); 
    frame.add(button3); 
    button1.setBounds(50, 20, 80, 20); 
    button2.setBounds(50, 50, 80, 20); 
    button3.setBounds(50, 80, 80, 20); 

    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      frame.setVisible(true); 
     } 
    }); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

public static void main(String[] args) { 
    new RadioButton(); 
} 
} 

我使用的OS X和我需要使按鈕有點大,以避免他們的標題顯示爲'...'。最後我用invokeLater,這是IIRC最好的做法。

1

您需要設置的佈局管理器的容器,我建議你閱讀tutorial

RadioButton(){ 
    JFrame frame = new JFrame(); 
    JRadioButton button1 = new JRadioButton("One"); 
    JRadioButton button2 = new JRadioButton("Two"); 
    JRadioButton button3 = new JRadioButton("Three"); 
    ButtonGroup bg = new ButtonGroup(); 
    bg.add(button1); 
    bg.add(button2); 
    bg.add(button3); 
    frame.getContentPane().setLayout(new FlowLayout()); 
    frame.add(button1); 
    frame.add(button2); 
    frame.add(button3); 
    frame.setSize(300, 300); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 
1

JFrame的默認佈局是BorderLayout。沒有指定區域,您添加的每個組件都將被放置到BorderLayout.CENTER中。由於button3是最後添加的,它取代了button2(button2在添加時替換了button1)。您可以使用FlowLayout創建一個JPanel,並在那裏添加三個按鈕。然後將JPanel添加到JFrame