当我想在面板上添加标签时,它将不会出现,直到调整框架大小

时间:2015-03-12 14:21:04

标签: java swing jframe jpanel jbutton

当我想向Panel添加标签时,在调整框架大小之前不会显示。它没有更新。

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 ?");

以下是在主面板上创建标签的事件。

        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();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要调用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
         }