簡體   English   中英

除非在將JButton添加到JPanel之后設置文本,否則為什么JButton不會顯示?

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

我有一個問題,我的JButton對象以奇怪的方式表現:

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:

按鈕在哪里?

當我用以下內容替換最后幾行時:

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

frame.add(panel);

我得到以下GUI:

現在按鈕出現了。

為什么是這樣? 我認為在按鈕的構造函數中給出一個字符串將導致與顯式調用setter相同。

正如人們所指出的那樣,在打包()框架並使框架可見之前,應該將組件添加到GUI中。

除非在將JButton添加到JPanel之后設置文本,否則為什么JButton不會顯示?

但是,要回答上述問題,即使框架可見,也可以向GUI添加組件。 執行此操作時,必須告知Swing已添加(或刪除)組件,以便可以調用布局管理器。 您可以使用以下代碼執行此操作:

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

在您調用按鈕上的setText(...)方法的情況下,按鈕實際上會為您調用revalidate()和repaint()。 每當您更改Swing組件的屬性時都會這樣做,因此您正在調用布局管理器,這意味着布局管理器在繪制按鈕之前可以為該按鈕指定大小/位置。

在原始代碼中,當您向GUI添加按鈕時,未調用布局管理器,因此它的默認大小為(0,0);

正如MadProgrammer指出的那樣(謝謝!),問題是由frame.setVisible(true)的位置引起的。

這需要是最后調用的東西,或者框架的刷新模式可能會導致像我的情況中發生的未渲染的組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM