在Java Swing中将按钮添加到JPanel [英] Adding Button to JPanel in Java Swing

查看:78
本文介绍了在Java Swing中将按钮添加到JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将JLabel和JCombobox附加到JPanel.这很好.但是当我再添加两个按钮时,看不到那些按钮.

I am appending a JLabel and JCombobox to a JPanel.This works fine.But when I add two more buttons to this,I cannot see those buttons.

下面是我的代码:

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.我找不到为什么按钮不显示的原因.感谢您的帮助.

Finally I am adding the JPanel to a JFrame. I have set the layout as null for JPanel. I cant find why the buttons are not displayed. Any help is appreciated.

推荐答案

如果布局为null,则意味着您必须使用 setBounds()方法来放置添加到组件中的组件. JPanel .您目前还没有这样做,所以我认为按钮是在 JPanel 之外还是在 JComboBox 下方绘制的.
无论如何,如果您想将按钮放在特定位置,则必须告诉他们,这不会像使用null以外的 Layout 时那样自动.

If the layout is null, it means that you have to use the setBounds() method to position the components you add to your JPanel. You are not currently doing that, so I think buttons are drawn whether outside of the JPanel, or below your JComboBox.
Anyway if you want your buttons at specifics positions you have to tell them, this will not be automatic like it is when using a Layout other than null.

这篇关于在Java Swing中将按钮添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆