如果我从netbeans运行它,有时它会按预期绘制图像..但有时我只得到主窗口,并在移动鼠标后显示“开始”按钮。
public class my_gui extends JFrame {
public my_gui() {
setTitle("Broscute 1.0 :p");
setSize(954, 320);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage("src/img/test.png"));
setVisible(true);
initUI();
}
public final void initUI() { //ui here
setLayout(null);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, 954, 320);
getContentPane().add(panel);
JButton button = new JButton("Start!");
button.setBounds(0, 0, 954, 40);
final ImagePanel[] label = new ImagePanel[4];
int i, j;
for(i=40, j=0;i<=220;i+=60, j++){
label[j] = new ImagePanel(0, i);
label[j].setBounds(0, 0, 954, 320);
panel.add(label[j]);
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
label[3].X += 100;
}
});
panel.add(button);
}
}
class ImagePanel extends JComponent{
public int X, Y;
float v = 10;
private BufferedImage image;
ImagePanel(){}
public ImagePanel(int x, int y) {
X = x; Y = y;
try {
image = ImageIO.read(new File("src/img/broasca.png"));
} catch (IOException ex) {
// handle exception...
}
}
@Override
public void paintComponent(Graphics g) {
super.paintChildren(g); //a friend told me I should put it here
g.drawImage(image, X, Y, this); // see javadoc for more info on the parameters
repaint(); //I think this should go here
}
}
在IDE外部运行它无法找到图像。
我在这里做错了什么?
答案 0 :(得分:2)
在完成所有初始化之前不要显示对话框,即将setVisible移动到构造函数中的最后一个方法。
为了更好地重用,根本没有JFrame派生类调用setVisible(true),让客户端去做。
问题是,一旦你显示窗口,你对窗口做的任何改变都必须在GUI线程上完成,否则你会得到像你看到的虚假问题。
答案 1 :(得分:1)
您通常在paintComponent
中做的第一件事就是通过super.paintComponent()
清除屏幕外的位图 - 我打赌这是您的问题。