如何动态添加JButton到JPanel? [英] How to Dynamically Add JButton to JPanel?

查看:615
本文介绍了如何动态添加JButton到JPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NetBeans中,我使用GUI编辑器制作JFrame,并在框架中放置了JPanel。
目前,我正在尝试在类构造时在面板中创建一个新按钮。
这是我的代码,但我似乎无法让它工作。
(第一行显示按钮,其他行尝试显示它。)

In NetBeans, I have used the GUI editor to make a JFrame and I've put a JPanel in the frame. At the moment, I'm trying to make a new button in the panel when the class constructs. This is the code I have, but I can't seem to get it to work. (The first line makes the button, the other lines try to show it.)

this.jPanel2.add(new JButton("Test"),BorderLayout.NORTH);
this.jPanel2.validate();
this.jPanel2.revalidate();
this.jPanel2.repaint();
this.jPanel2.setVisible(true);
this.revalidate();
this.setVisible(true);
this.repaint();

我一直在谷歌上搜索,但似乎无法让它发挥作用。

I've been googling all night, but can't seem to get it to work.

推荐答案

有时当你没有看到按钮时,它就是布局管理器问题(因为你没有设置正确的属性)对于布局管理器)。您可以通过禁用它来测试它:

Some times when you don't see a button it is a layout manager issue (as in you aren't setting the right properties for the layout manager). You can test this by disabling it:

this.jPanel2.setLayoutManager(null);

并设置按钮的界限( JButton.setBounds())。

And setting bounds for the button (JButton.setBounds()).

如果以上解决了您的问题,那么您需要查看您正在使用的LayoutManager设置的要求(另请参阅Robin的答案)。

If the above fixes your problem, then you need to look into the requirements set by the LayoutManager you are using (see also the answer by Robin).

所有对的调用validate() revalidate() repaint()不需要这样做。

All the calls to validate(), revalidate() and repaint() are not needed to do this.

这篇关于如何动态添加JButton到JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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