这是我的主要课程:
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();
}
}
当我的程序达到“你好”时,我希望它在x = 300时重新绘制汽车,但事实并非如此。我应该怎么做才能使这项工作?我在run方法中有它,因为我计划稍后将它作为一个线程运行,但是现在,我只是想让它移动。
答案 0 :(得分:1)
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
来更新用户界面的状态,因为这可能会导致问题并产生意外结果,相反,我鼓励您使用Swing { {1}}这样的事情。
有关详细信息,请查看Concurrency in Swing和How to use Swing Timers