我正在寫一些基本的Java遊戲代碼,我找不到解決我的問題。 下面是代碼:Java - 需要幫助java.lang.ArrayIndexOutOfBoundsException
[GameWindow.java]
package my.project.gop.main;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
public class GameWindow extends JFrame{
boolean fse = false;
int fsm = 0;
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[1];
public GameWindow(String title, int width, int height) {
setSize(width, height);
setLocationRelativeTo(null);
setTitle(title);
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");
}
}
}
[Main.java]
package my.tdl.main;
import my.project.gop.main.GameWindow;
public class Main {
public static void main(String[] args) {
GameWindow frame = new GameWindow("TheDLooter", 1280, 720);
frame.setFullscreen(1);
frame.setVisible(true);
}
}
我收到此錯誤信息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at my.project.gop.main.GameWindow.<init>(GameWindow.java:12)
at my.tdl.main.Main.main(Main.java:8)
問題一定在這裏 - 'device = GraphicsEnvironment.getLocalGraphicsEnvironment()。getScreenDevices()[1];'。你不能假設該數組至少有兩個元素。 – Eran
Java數組從零開始。嘗試將其更改爲零。 – duffymo
這很明顯,因爲java中的數組從0開始,編譯器明確指出哪一行存在問題。我認爲這是微不足道的。 –