gpt4 book ai didi

java - 如何正确绘制图像而不仅仅是主窗口?

转载 作者:行者123 更新时间:2023-12-02 00:43:16 27 4
gpt4 key购买 nike

如果我从 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 外部运行它,无法找到图像。

我在这里做错了什么?

最佳答案

在所有初始化完成之前不要显示对话框,即将 setVisible 移至构造函数中的最后一个方法。

为了更好地重用,根本不要让 JFrame 派生类调用 setVisible(true),让客户端来执行。

问题是,一旦显示窗口,对窗口所做的任何更改都必须在 GUI 线程上完成,否则您将遇到像您所看到的那样的虚假问题。

关于java - 如何正确绘制图像而不仅仅是主窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5708040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com