[英]how to add Jlabel to Jpanel outside the constructor?
I am able to use add(new Jlabel()) to create label on my Jpanel inside the Jpanel constructor, but once I called add() using other function, the label is not shown on the panel. 我可以使用add(new Jlabel())在Jpanel构造函数中的Jpanel上创建标签,但是一旦使用其他函数调用add(),该标签就不会显示在面板上。 What did I do wrong? 我做错了什么?
public class DisplayPanel extends JPanel {
JLabel headerField = new JLabel("Choose a file to generate report.");
JLabel dateField = new JLabel("123");
JLabel meanField = new JLabel("");
JLabel minField = new JLabel("");
JLabel maxField = new JLabel("");
JLabel stdDevField = new JLabel("");
public DisplayPanel() {
super();
setBackground(Color.white);
setLayout(new GridLayout(6, 1));
add(headerField);
**//add(new JLabel("123")); this will work**
}
public void setFields(DataManager d)
{
dateField.setText(d.getStartDate() + " - " + d.getEndDate());
meanField.setText("Mean: " + d.getMean());
minField.setText("Min: " + d.getMin());
maxField.setText("Max: " + d.getMax());
stdDevField.setText("Std Dev: " + d.getStdev());
this.add(new JLabel("123")); **//this doesn't work**
}
In order to get any newly added component to appear after the JPanel
has been made visible, you need to call revalidate()
and typically repaint()
. 为了使任何新添加的组件在JPanel
变得可见之后出现,您需要调用revalidate()
,通常是repaint()
。 The reason that 的原因
add(new JLabel("123"));
works in the constructor the JPanel
is validated when added to its container, typically a JFrame
. 在将JPanel
添加到其容器(通常是JFrame
时,将对JPanel
进行验证。 Adding the label at the inialization stage is simpler as you only have to call JLabel#setText
and no revalidate/repaint
calls are necessary. 在初始化阶段添加标签更为简单,因为您只需调用JLabel#setText
而无需revalidate/repaint
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.