swing组件问题

来源:百度知道 编辑:UC知道 时间:2024/06/17 13:42:20
创建了一个JFrame,里面加了一些按钮和输入框,但是这些按钮和输入框只有在获得焦点之后才可以显示,这是为什么啊?
我测试了一下,重写paint(),它里面的东西会把同位置的组件覆盖掉
package windows;

import java.awt.Frame;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Color;

public class NewTest extends Frame {
private javax.swing.JButton b=new JButton(new ImageIcon("materials/image/icon.gif"));
public NewTest(){
super();
this.setUndecorated(true);
this.setBounds(20, 20, 400, 300);
this.setVisible(true);
this.setLayout(null);
b.setBounds(20, 40, 50, 20);
this.add(b);
this.repaint();
}
public void paint(java.awt.Graphics g){
g.setColor(Color.BLACK);
g.drawRect(0, 0, this.getWidth(), this.getHeight());
}
}

如果把paint()方法去掉都好,但是加上这个方法就只有在鼠标移动到上面的时候才出现,可能是paint()和paintComponents()调用先后的问题,但是查资料发现调用paint是在先的啊,实在不明白是怎么回事

写了个程序测试了下组件的绘制顺序,这个是结果:
parent.repaint
parent.paintComponent
parent.paintBorder
child.paintComponent
child.paintBorder
child.paintChildren
child.paint
parent.paintChildren
parent.paint
能解释你的疑问了吧

代码贴出来看看

这是因为,你必须加个监听

不可能啊