除非在将JButton添加到JPanel后设置了文本,否则为什么不显示JButton? [英] Why does a JButton not show unless text is set after JButton is added to JPanel?

查看:101
本文介绍了除非在将JButton添加到JPanel后设置了文本,否则为什么不显示JButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JButton对象的行为方式很奇怪:

I have a problem with my JButton objects behaving in an odd way:

JFrame frame = new JFrame();
frame.setSize(new Dimension(200, 200));
frame.setVisible(true);

//Constraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1.0;
constraints.weighty = 1.0;
...
//

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
JButton button = new JButton("Categories:");
panel.add(button, constraints);
frame.add(panel);

这将产生以下GUI:

按钮在哪里?

当我用以下内容替换最后几行时:

When I replace the last few lines with the following:

JPanel panel = new JPanel();
JButton button = new JButton();
panel.add(button, constraints);
button.setText("Categories:");

frame.add(panel);

我得到以下GUI:

该按钮现在显示.

这是为什么?我认为在按钮的构造函数中提供一个字符串将导致与显式调用setter相同.

Why is this? I thought giving a string in the constructor of the button would result in the same as explicitly calling the setter.

推荐答案

正如人们所指出的那样,应在打包()框架并使框架可见之前将组件添加到GUI中.

As people have pointed out components should be added to the GUI before you pack() the frame and make the frame visible.

为什么除非将JButton添加到JPanel中之后设置文本,否则JButton不会显示?

Why does a JButton not show unless text is set after JButton is added to JPanel?

但是,要回答上述问题,即使框架可见,也可以将组件添加到GUI.执行此操作时,必须告诉Swing已添加(或删除)了组件,以便可以调用布局管理器.您可以使用以下代码执行此操作:

However, to answer the above question, you can add components to the GUI even when the frame is visible. When you do this you must tell the Swing that components have been added (or removed) so the layout manager can be invoked. You do this with code like the following:

panel.add(...);
panel.revalidate();
panel.repaint();

在您的情况下,当您在按钮上调用setText(...)方法时,该按钮实际上会为您调用revalidate()和repaint().只要您有效地更改了Swing组件的属性,就可以调用布局管理器来完成此操作,这意味着可以在绘制按钮之前由布局管理器为其指定大小/位置.

In your case when you invoke the setText(...) method on the button the button actually invokes revalidate() and repaint() for you. This is done whenever you change a property of a Swing component so effectively you are invoking the layout manager which means the button can be assigned a size/location by the layout manager before it is painted.

在您的原始代码中,将按钮添加到GUI时未调用布局管理器,因此其默认大小为(0,0);

In your original code the layout manager was not invoked when you added button to the GUI so it had a default size of (0, 0);

这篇关于除非在将JButton添加到JPanel后设置了文本,否则为什么不显示JButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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