[英]Why won't my icon repaint?
Here is my main 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();
}
}
Here is my screen class: 这是我的屏幕课程:
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();
}
}
When my program reaches "Hello", I want it to repaint the car at x = 300, but it does not. 当我的程序到达“ Hello”时,我希望它在x = 300处重绘汽车,但不是。 What should I do to make this work? 我应该怎么做才能使这项工作? I have it in a run method because I plan on having it run as a thread later, but for now, I just want it to move. 我将其包含在run方法中,因为我计划稍后将其作为线程运行,但是现在,我只希望它移动。
The instance of Screen
which is displayed on the screen
and the instance of Screen you're trying to update are not the same 该实例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();
}
}
I'd also be careful about using Thread
s to update the state of the UI as this could cause issues and generate unexpected results, instead, I'd encourage you to use a Swing Timer
for something like this. 我还应谨慎使用Thread
来更新UI的状态,因为这可能会导致问题并产生意外的结果,相反,我鼓励您对此类情况使用Swing Timer
。
Have a look at Concurrency in Swing and How to use Swing Timers for more details 了解Swing中的并发性以及如何使用Swing计时器以了解更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.