Reputation: 121
I created frame with button and when it is pressed all content is removed and replaced by new one. But I can not display label, here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
getContentPane().removeAll();
jLabel2 = new javax.swing.JLabel();
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Hello World!");
jLabel2.setLocation(80, 80);
jLabel2.setVisible(true);
getContentPane().add(jLabel2);
getContentPane().repaint();
pack();
}
What am I doing wrong? :(
Upvotes: 2
Views: 224
Reputation: 4940
You should use validate()
instead of repaint
. The rest of your source looks fine.
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
Upvotes: 1
Reputation: 209132
Instead of trying to remove all and add new components, use a CardLayout
, which will "layer" panels and let you navigate between them. See How to use CardLayout and you can see a simple example here
You can also see how to use CardLayout
with Netbeans GUI Builder here
Upvotes: 1