0

When I want to add a label to the Panel, it will not appear until resizing the frame. It does not update.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Actions_GUI
{
    JFrame frame;
    JPanel panel;
    JButton button;
    JLabel label;

    Actions_GUI()
    {
        frame = new JFrame();
        frame.setSize(400,300);
        frame.setTitle("WHY ?");

        panel = new JPanel();
        panel.setBackground(Color.black);

        button = new JButton(" WHY ?");

Here's the event for creating a label on the main panel.

        button.addActionListener(new ActionListener()
        {
             public void actionPerformed(ActionEvent e)
             {
                 label=new JLabel(" Why Don't Upadate? ");
                 label.setForeground(Color.magenta);
                 panel.add(label);
             }
        });
        panel.add(button);


        frame.add(panel);
        frame.setVisible(true);
    }  

    public static void main(String [] args)
    {
        Actions_GUI object = new Actions_GUI();
    }
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • 1
    Try adding `panel.invalidate()` to force panel to update. – Marko Živanović Mar 12 '15 at 14:24
  • This post will be useful : http://stackoverflow.com/questions/3718435/refresh-jframe-after-adding-new-components .Use a layout (like border layout) for the frame and also the panel for managing the locations of components. – Clyde D'Cruz Mar 12 '15 at 14:28
  • @MarkoŽivanović , thanks, i am tried " panel.revalidate() " it was solution for problem, thanks – Hardi Alves Mar 12 '15 at 14:32

1 Answers1

0

You need a call to repaint()

        public void actionPerformed(ActionEvent e)
         {
             label=new JLabel(" Why Don't Upadate? ");
             label.setForeground(Color.magenta);
             panel.add(label); // adding a label will automatically invalidate the component
             panel.revalidate();
             panel.repaint(); // you need to repaint
         }
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • You need revalidate() before the repaint(). The revalidate() basically invokes the layout manager otherwise the component still has a size of (0, 0) and there is nothing to repaint(). – camickr Mar 12 '15 at 14:47
  • @camickr good point. I was thinking doing panel.add(label) would invalidate the component - and it will - but I forgot that you need to call (re)validate after that :) – ControlAltDel Mar 12 '15 at 14:58