2

これは以前に尋ねられたことは知っていますが、まだ機能させることができません。

public class GUI extends JFrame implements Runnable{

    public static JPanel contentPane;
    public static Graphics2D graphics;
    public static BufferStrategy bufferStrategy;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI frame = new GUI();
                    frame.setVisible(true);
                    frame.setResizable(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GUI() {
        setResizable(false);
        setTitle("Tower Defense Game");
        setIgnoreRepaint(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);


    }

    @Override
    public void run() {

        createBufferStrategy(2);
        bufferStrategy = getBufferStrategy();
        graphics = (Graphics2D) bufferStrategy.getDrawGraphics();

        for(int infiniteVar = 0; infiniteVar == -1; infiniteVar++){

            graphics.setBackground(Color.WHITE);
            graphics.drawLine(100, 100, (int) (Math.random() * ((200-50) + 1) + 50), (int) (Math.random() * ((200-50) + 1) + 50));

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            infiniteVar = 0;
        }
    }
}
public class Initialize {

public static void main(String[] args){

    GUI.main(args);

    GUI objGUI = new GUI();
    Thread threadGUI = new Thread(objGUI);
    threadGUI.start();
}
}

Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer on the lineバッファー戦略を立てようとするところにたどり着きました。最初にフレームを作成することになっていると思いますが、バッファ戦略を作成するスレッドを作成する前にそれを呼び出します。

4

1 に答える 1