日期:2014-05-20  浏览次数:20818 次

JPanel中动态添加JLabel无法显示,求大神
如题,程序中JLabel改成Label是可以正常显示的,为什么JLabel不行?

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

public class Test extends JFrame implements ActionListener {
JPanel p;
JButton b;
int flag = 0;

public Test(){
super("test");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
setVisible(true);
setSize(500,500);
setLayout(null);
b = new JButton("ok");
b.setBounds(20,20,60,20);
b.addActionListener(this);
p = new JPanel();
p.setSize(500,500);
p.setLayout(null);
p.add(b);
add(p);

}

public static void main(String args[]) {
new Test();
}

public void actionPerformed(ActionEvent e) {
if(e.getSource()==b){
flag++;
JLabel l = new JLabel("你好");
l.setBounds(50, 50*flag, 60, 25);
l.setVisible(true);
p.add(l);
}

}
}

------最佳解决方案--------------------
一旦你setvisible,你的图像已经绘画完成了,虽然你增加了按钮但是没有更新图片,可以增加个repint方法
if (e.getSource() == b) {
flag++;
JLabel l = new JLabel("你好");
l.setBounds(50, 50 * flag, 60, 25);
l.setVisible(true);
p.add(l);
repaint();

}
------其他解决方案--------------------
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==b){
            flag++;
            JLabel l = new JLabel("你好");
            l.setBounds(50, 50*flag, 60, 25);
            l.setVisible(true);
            p.add(l);
            repaint(); // 动态改变一定要调用repaint(),你缺少就是这个
        }

------其他解决方案--------------------
谢谢