当我想向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();
}
}
答案 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
}