2


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? :(

My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
mullen18
  • 121
  • 2
  • 7
  • try setLocation(0,0); - it might be out of view.. – christian.s Mar 04 '14 at 16:42
  • thanks :) but it is in parent's location coordinations, so I have already try it, but same problem. – mullen18 Mar 04 '14 at 16:50
  • 1
    For better help sooner, please post a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the problem. – splungebob Mar 04 '14 at 17:20
  • I would avoid absolute positioning like the plague and use layouts instead. Then you can tell the container it needs to update and have it position your label automatically, in the best location based on panel size, screen resolution, and other factors outside of your control. –  Mar 04 '14 at 17:21
  • thanks for layout advice. it helped me on my next move. THANK YOU VERY MUCH ! :) – mullen18 Mar 05 '14 at 11:24

3 Answers3

2

instead of repaint() try validate().

user3297129
  • 299
  • 1
  • 6
1

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

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thank you! It was very helpful. When I corrected previous problem, I had problem with layout, then I read your answer and used it :) thanks – mullen18 Mar 05 '14 at 11:09
  • If the answer helped you solve your problem, feel free to tick the check mark as the accepted answer :) – Paul Samsotha Mar 05 '14 at 11:11
1

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.

My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
  • thank you very much, it worked! I thought that repaint() is that correct method, but I was wrong. Thanks AGAIN! :) – mullen18 Mar 05 '14 at 11:05