2012-08-16 150 views
2

我將JLabel和JCombobox附加到JPanel.This工作正常。但是,當我爲此添加兩個按鈕時,我看不到這些按鈕。在Java Swing中將按鈕添加到JPanel

下面是我的代碼:

JPanel jPanel=new JPanel(); 
jPanel.setLayout(null); 
JLabel label = new JLabel("Welcome");      
label.setFont(new Font("Helvetica", Font.ROMAN_BASELINE, 13));   
jPanel.add(label);  
JComboBox combo = new JComboBox(comboboxbean); 
combo.setPreferredSize(new Dimension(285, 20)); 
combo.setFont(new Font("Helvetica", Font.ROMAN_BASELINE, 13));   
jPanel.add(combo);   
startButton = new JButton("Start"); 
stopButton = new JButton("Stop"); 
startButton.addActionListener(this); 
startButton.setActionCommand("enable"); 
jPanel.add(startButton); 
stopButton.addActionListener(this); 
stopButton.setActionCommand("enable"); 
jPanel.add(stopButton); 
Insets insets = jPanel.getInsets();    

Dimension size = label.getPreferredSize(); 
     label.setBounds(20 + insets.left, 30 + insets.top, 
        size.width, size.height); 

Dimension size1 = combo.getPreferredSize(); 
    combo.setBounds(20 + insets.left, 65 + insets.top, 
        size1.width, size1.height); 

Dimension size2 = startButton.getPreferredSize(); 
    startButton.setBounds(20 + insets.left, 100 + insets.top, 
       size2.width, size2.height); 

Dimension size3 = stopButton.getPreferredSize(); 
    stopButton.setBounds(20 + insets.left, 130 + insets.top, 
      size3.width, size3.height);   

frame.add(jPanel); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.setVisible(true); 

最後我加入的JPanel到一個JFrame。對於JPanel,我已將佈局設置爲null。 我找不到爲什麼按鈕不顯示。 任何幫助表示讚賞。

+1

發佈整個代碼,包括添加標籤和組合框的代碼。 – 2012-08-16 11:25:37

+2

請勿使用空白布局,而應使用適當的佈局管理器! – 2012-08-16 11:36:46

+0

Dan我現在已經發布了整個代碼.. – vijay 2012-08-16 11:45:13

回答

2

如果佈局爲空,則表示您必須使用setBounds()方法來定位添加到JPanel的組件。您目前沒有這樣做,所以我認爲無論是在JPanel之外還是在JComboBox以下,都可以使用按鈕。
無論如何,如果你想讓你的按鈕在特定的位置,你必須告訴他們,這將不會像使用非空的Layout那樣自動。

+0

嗨miNde,我用setBounds(),但我沒有得到它。請參閱現在編碼。 – vijay 2012-08-16 11:47:19