这是我的主要类:
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 重新粉刷汽车,但它没有。我应该怎么做才能完成这项工作?我把它放在一个运行方法中,因为我计划稍后让它作为线程运行,但现在,我只想让它移动。
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 Timer
来做这样的事情。
查看 Swing 中的并发性和如何使用 Swing 计时器以获取更多详细信息