gpt4 book ai didi

java - repaint() 方法不会重新绘制我的屏幕

转载 作者:行者123 更新时间:2023-12-01 16:36:54 27 4
gpt4 key购买 nike

我在这里尝试做的是从我的 loadbg() 方法中调用 repaint() 方法。但是,repaint() 不起作用,并且我的图像(存储在 var bg 中)不会加载到屏幕上。关于为什么这行不通的任何建议?

package core;

/*** @author Adil

* 2DPlatformer
* Written by Adil
* Built upon the player-core framework (written by Adil)
* GNU Licensed

*/
import java.awt.*;

import javax.swing.JFrame;

import javax.swing.ImageIcon;

@SuppressWarnings("serial") //Suppress serial warning ID
public class Core extends JFrame {

public static void main(String[] args) {
DisplayMode dm = new DisplayMode(800, 600, 16,
DisplayMode.REFRESH_RATE_UNKNOWN);
//new display with parameters 800x600 + 16 bit color depth
Core i = new Core(); //new core class var
i.run(dm);
}
//variables for image loading below
public Screen s;
public Image bg;
public boolean loaded = false;

//run method below
public void run(DisplayMode dm) {
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setFont(new Font("Ubuntu", Font.PLAIN, 24));
s = new Screen();
loaded = false;
try {
s.setScreenSize(dm, this);
loadbg();
try {
Thread.sleep(5000);
} catch (Exception ex) {
}
} finally {
s.RestoreScreen();
}
}

public void loadbg() {
bg = new ImageIcon(
"file:\\\\home\\adil\\Desktop\\pack_2\\bgame.jpg").getImage();
loaded = true;
s.repaint();//s is my screen object, but it won't repaint.
}

public void paint(Graphics g) {
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
if (loaded) {
g.drawImage(bg, 0, 0, null);
}
}
}

最佳答案

1)更好的方法是 Icon/ImageIconJLabel ,而不是使用 paint() 绘制 Image

2) 对于 Swing,有 paintComponent() 而不是 paint()

3) 不要将 Thread.sleep(int) 用于 Swing GUI javax.swing.Timer相反,因为在 Thread.sleep(int) 期间,您的 GUI 只是卡住,没有其他任何事情

关于java - repaint() 方法不会重新绘制我的屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125318/

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