java吧 关注:1,232,686贴子:12,697,361
  • 0回复贴,共1

求助:JComponent与JFrame问题

只看楼主收藏回复

public class Prove_8_JComponent extends JComponent{
int X = 100,Y = 100;
final JFrame frame = new JFrame("a");
ImageIcon img = new ImageIcon("Image/libraryUI.png");
ImageIcon img1 = new ImageIcon("Image/humanBody.png");
Image im;
JLabel label = new JLabel(img);
public void setUI(){
System.out.println("c");
frame.setLocation(200, 100);
frame.setSize(900, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label.setBounds(0, 0, 900, 600);
frame.add(this);
frame.setVisible(true);
new Thread(new Thread(){
public void run(){
while(true){
try{
frame.repaint();
Thread.sleep(20);
}catch(Exception e){
}
}
}
}).start();
}
public void paintComponent(Graphics g){
System.out.println("a");
Color c = g.getColor();
g.setColor(Color.red);
g.fillRect(200, 200, 200, 200);
g.setColor(c);
X++;
}
public void paint(Graphics g){
super.paint(g);
g.fillRect(X, Y, 200, 200);
frame.add(label);
X++;
System.out.println("e");
}
public static void main(String [] args){
new Prove_8_JComponent().setUI();
}
}
问题:JComponent绘制中,如果将 frame.add(label)移动到setUI()处会出现paint()被JFrame覆盖的问题,而将它放在paint()中就不会出现这种情况,可是按照JFrame的绘图规律,应该两种情况都是JLable在底层出现,为什么JComponent中将JLabel放在和JFrame相同的位置,会遮住paint的绘制内容呢?求高手解答一下问题出在哪里呢?


IP属地:山东1楼2014-09-22 14:55回复