我知道之前已经有人问过这个问题,但我仍然无法让它发挥作用。
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();
}
}
我在线程“Thread-2”java.lang.IllegalStateException中得到异常:组件必须在线上有一个有效的对等点
,我尝试制定缓冲区策略。我认为我应该先制作框架,但我确实在制作制定缓冲区策略的线程之前调用它。
最佳答案
基本上,你的问题从这里开始......
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();
}
}
});
}
这里很生气...
public class Initialize {
public static void main(String[] args) {
GUI.main(args);
GUI objGUI = new GUI();
Thread threadGUI = new Thread(objGUI);
threadGUI.start();
}
}
基本上,发生了什么,GUI.main
方法正在创建一个 GUI
的新实例,该实例显示在屏幕上,然后您创建另一个实例图形用户界面...
GUI objGUI = new GUI();
Thread threadGUI = new Thread(objGUI);
threadGUI.start();
您尝试使用它来创建BufferStrategy
,但该实例在屏幕上不可见(可显示,或附加到 native 对等点),因此您的问题...
相反,摆脱GUI
中的main
方法,它实际上并没有给你带来任何好处,并在Initialize
中应用它的逻辑>
GUI frame = new GUI();
// Better idea to do this before you make the frame visible
// as it can change the frame borders and cause some issues
frame.setResizable(false);
frame.setVisible(true);
Thread thread = new Thread(frame);
thread.start();
您还可以在 run
方法中添加检查,以等待 JFrame
变得可显示...
@Override
public void run() {
while (!isDisplayable()) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
//...
您还应该阅读 BufferStrategy
上的 JavaDocs更好地了解如何管理它们...
关于java - 缓冲区策略 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811139/