gpt4 book ai didi

java - 为什么我的图标不会重新绘制?

转载 作者:行者123 更新时间:2023-12-01 10:00:44 26 4
gpt4 key购买 nike

这是我的主要类(class):

package fast;

import java.awt.BorderLayout;
import java.awt.Color;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Fast {

public JFrame frame = new JFrame("Fast");
public JPanel panel = new JPanel();
public Screen screen = new Screen();

public Fast() throws IOException {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 500);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
frame.setBackground(Color.YELLOW);
frame.add(screen);
screen.setBackground(Color.WHITE);
}
public static void main(String[] args) throws IOException {
Fast f = new Fast();
Thread thread = new Thread(new Screen());
thread.start();
}
}

这是我的屏幕类:

package fast;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Screen extends JPanel implements Runnable {
BufferedImage img = ImageIO.read(new File("bg.png"));
ImageIcon car = new ImageIcon("sCar.png");
public int x = 50;

public Screen() throws IOException {

}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
car.paintIcon(this, g, x, 50); // I want this to move
drawBackground(g);
}
private void drawBackground(Graphics g) { // testing
g.setColor(Color.YELLOW);
g.fillRect(x, 100, 50, 50);
}
@Override
public void run() {
System.out.println("Hello");
x = 300;
repaint();
}
}

当我的程序到达“Hello”时,我希望它在 x = 300 处重新绘制汽车,但它没有。我应该怎么做才能使这项工作成功?我将它放在 run 方法中,因为我计划稍后将其作为线程运行,但现在,我只想让它移动。

最佳答案

screen 上显示的 Screen 实例与您尝试更新的 Screen 实例不同

public class Fast {

// screen #1
public Screen screen = new Screen();

public Fast() throws IOException {
//...
// Screen #1 on the screen
frame.add(screen);
//...
}
public static void main(String[] args) throws IOException {
//...
// Screen #2, which is not on the screen
Thread thread = new Thread(new Screen());
thread.start();
}
}

我也会小心使用 Thread 来更新 UI 的状态,因为这可能会导致问题并产生意外的结果,相反,我鼓励您使用 Swing 计时器类似这样的事情。

看看Concurrency in SwingHow to use Swing Timers了解更多详情

关于java - 为什么我的图标不会重新绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829339/

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