我正在遵循这个tutorial,但是我不知道以下2个类在解释每件事的错误所在,因为只有两个类,我试图再次观看本教程,但仍然没有找到错误
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gameofthrones;
import java.awt.*;
import javax.swing.*;
/**
*
* @author issba
*/
public class ClassOGP extends JFrame{
boolean fse =false;
int fsm = 0;
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[1];
public ClassOGP(String title,int width,int height){
setTitle(title);
setSize(width,height);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
}
private void setfullscreen(){
switch(fsm){
case 0:
System.out.println("No fullscreen");
setUndecorated(false);
break;
case 1:
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
break;
case 2:
device.setFullScreenWindow(this);
setUndecorated(true);
break;
}
}
public void setFullscreen(int fsnm){
fse = true;
if(fsm <= 2){
this.fsm = fsnm;
setfullscreen();
}else{
System.err.println("Error " + fsnm + " is not supported");
}
}
}
这是主类,其中没有太多代码。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gameofthrones;
/**
*
* @author issba
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ClassOGP frame = new ClassOGP("Game Of thrones",1280,720);
frame.setFullscreen(1);
frame.setVisible(true);
}
}
错误消息在这里
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at gameofthrones.ClassOGP.<init>(ClassOGP.java:18)
at gameofthrones.Main.main(Main.java:20)
C:\Users\issba\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
最佳答案
这行:
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[1];
正在抛出错误。尝试将
1
更改为0
。不过,这只是一个快速修复,您应该将设备声明为实例或类成员,然后在构造函数中分配它。然后,如果没有屏幕设备,您可以进行错误检查。如下所示:
public class ClassOGP extends JFrame{
/* other code */
public GraphicsDevice device;
public ClassOGP(String title,int width,int height) {
if(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length() > 0) {
// you can also check for multiple devices here to see if you want
// to use one other than the zero'th index
device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0];
} else {
System.out.println("ERROR: No devices ... exiting.");
System.exit();
}
/* other code */
}
/* rest of class */
}
关于java - ArrayIndexOutOfBoundsException 2D游戏开发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37041052/