2012-08-16 147 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