不打印应在printComponent方法中打印的消息。我的印象是没有调用paint方法。如果没有,为什么不呢?
import java.util.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
public class Main extends JFrame{
CustomComponent cc;
public static void main(String[] args) {
Main m = new Main();
}
public Main(){
setTitle( "Diverse Testari 7");
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 400);
cc = new CustomComponent();
cc.setImage("rgbcmy.jpg");
add(cc);
pack();
setVisible( true );
}
}
class CustomComponent extends JPanel{
BufferedImage img = null;
public void setImage( String str ){
try {
img = ImageIO.read( new File( str ) );
System.out.println("SUCCESS!");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
System.out.println("altceva");
super.paintComponent(g);
System.out.println("ceva");
}
}
答案 0 :(得分:2)
在Main
构造函数中添加此代码:
new Thread(new Runnable() {
public void run() {
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
}
}).start();
paintComponent
只会在您repaint();
时调用。
此外,永远不要使用setLayout(null);
。请参阅here。
此代码将不断重新绘制面板,因此它将不断调用paintComponent
。这很好,因为它将始终保持面板更新。您也可以在更改面板中的内容时调用repaint();
。