2016-04-24 6 views
0

が私のメインクラスです。ここなぜ私のアイコンは再描画されませんか?ここで

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で車を再描画したいのですが、それではない。この仕事をするために私は何をすべきですか?私はそれを後でスレッドとして実行することを計画しているので、実行方法でそれを持っていますが、今は移動したいだけです。

答えて

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 Sの使用について注意が必要だろうこれにより問題が発生し、予期しない結果が生じる可能性があるため、代わりに、Swing Timerをこのような目的で使用することをおすすめします。

詳しくはConcurrency in SwingHow to use Swing Timersをご覧ください。

関連する問題