我知道這已經被問過,但我仍然無法讓它工作。緩衝區策略IllegalStateException
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
我試圖制定緩衝策略。我認爲我應該首先制定框架,但是在制定制定緩衝策略的線程之前,我確實會這樣做。
好感謝,現在居然窗口彈出。但它並沒有畫出線條。這就是我對循環: for循環(縮短,以適應) \t \t \t \t \t \t顯卡=(Graphics2D的)bufferStrategy.getDrawGraphics(); \t \t \t \t \t \t graphics.setBackground(Color.WHITE); \t \t \t graphics.setColor(Color.BLACK); (Math.random()*((200-50)+ 1)+ 50),(int)(Math.random()*((200-50))。 )+ 1)+50)); \t \t \t \t \t \t graphics.dispose(); \t \t \t bufferStrategy.show(); \t \t \t \t \t \t嘗試{ \t \t \t \t主題。睡眠(10); \t \t \t}趕上(InterruptedException的發送){ \t \t \t \t e.printStackTrace(); \t \t \t} \t \t \t \t \t \t infiniteVar = 0; \t \t} – Bloodwing
我在想,'JRootPane'阻止了什麼被繪製到了框架上。考慮使用'java.awt.Canvas'來渲染並將其添加到您的框架 – MadProgrammer