gpt4 book ai didi

java - 图片有时只会加载

转载 作者:行者123 更新时间:2023-12-01 15:39:37 25 4
gpt4 key购买 nike

我正在创建一个应用程序,其中绘制了图像,并且它运行得很好。然而,由于某种原因,图像已停止加载。该图像位于我的项目目录的根文件夹中。这是我的代码:

JFrame:

package com.cgp.tetris; 

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;

public class TetrisFrame extends JFrame {
private static final long serialVersionUID = 1L;

public static void main(String[] args) {
new TetrisFrame();
}

public TetrisFrame() {
add(new TetrisMenu());
setTitle("Tetris");
setSize(new Dimension(640, 576));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((d.width / 2) - 320, (d.height / 2) - 288);
}
}

JPanel:

package com.cgp.tetris;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class TetrisMenu extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private Thread thread;
private BufferedImage titletop, titlebottom;

public TetrisMenu() {
super();
}

public void run() {
loadImages();
}

private void loadImages() {
try {
titletop = ImageIO.read(new File("tetrispic.png"));
titlebottom = ImageIO.read(new File("titlebottom.png"));
} catch (IOException e) {
e.printStackTrace();
}
}

public void addNotify() {
super.addNotify();
thread = new Thread(this);
thread.start();
}

public void paint(Graphics g) {
super.paint(g);

g.drawImage(titletop, 0, 0, 640, 440, null);
g.drawImage(titlebottom, 0, 440, null);
}
}

提前致谢!

最佳答案

图像加载不一致的原因是加载是在线程中完成的,该线程具有不可预测的行为,更糟糕的是,该线程的启动取决于调用 addNotify 的时间(我猜这也是不可预测的)。您可以通过在构造函数中放置 loadImages(); ,然后放置 repaint(); 来解决此问题。摆脱 addNotify 重写、run 方法和 Runnable 修饰符。这只是一个临时解决方案(可能适合您的需求),因为不建议在 EDT(事件调度线程)上进行大量工作(加载许多图像),因为它可能会导致 GUI 无响应。图像加载应该在 SwingWorker 的实例中完成或者在构建 GUI 之前。

class TetrisMenu extends JPanel {

private static final long serialVersionUID = 1L;
private Thread thread;
private BufferedImage titletop, titlebottom;

public TetrisMenu() {
super();
loadImages();
repaint();
}

private void loadImages() {
try {
titletop = ImageIO.read( new File( "tetrispic.png" ) );
titlebottom = ImageIO.read( new File( "titlebottom.png" ) );
} catch ( IOException e ) {
e.printStackTrace();
}
}

public void paint( Graphics g ) {
super.paint( g );
if ( titletop != null )
g.drawImage( titletop, 0, 0, 640, 440, null );
if ( titlebottom != null )
g.drawImage( titlebottom, 0, 440, null );
}
}

关于java - 图片有时只会加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8280398/

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