【发布时间】:2017-06-24 14:33:21
【问题描述】:
关于这个post。 我试图显示 9 个图标,9 个文本字段,但出现错误
java.lang.ArrayIndexOutOfBoundsException: 9
下面是标签代码
static void addIt(JTabbedPane tabbedPane, String text) throws IOException {
JPanel panel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
foodLabel = new JLabel[ELEMENTS];
qtyField = new JTextField[ELEMENTS];
file = new File[ELEMENTS];
imageIcon = new ImageIcon[ELEMENTS];
image = new BufferedImage[ELEMENTS];
for (int i = 0; i < ELEMENTS; i++) {
try {
file[i] = new File("C:\\Users\\tony\\Desktop\\MedSalad.png");
file[i + 1] = new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png");
file[i + 2] = new File("C:\\Users\\tony\\Desktop\\Spaghetti.png");
file[i + 3] = new File("C:\\Users\\tony\\Desktop\\PadThai.png");
file[i + 4] = new File("C:\\Users\\tony\\Desktop\\RamenNoodles.png");
file[i + 5] = new File("C:\\Users\\tony\\Desktop\\SpaghettiAndMeatBalls.png");
file[i + 6] = new File("C:\\Users\\tony\\Desktop\\chickenRice.jpg");
file[i + 7] = new File("C:\\Users\\tony\\Desktop\\thaiFood.jpeg");
file[i + 8] = new File("C:\\Users\\tony\\Desktop\\vietnamFood.jpg");
image[i] = ImageIO.read(file[i]);
imageIcon[i] = new ImageIcon(image[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < ELEMENTS; i++) {
foodLabel[i] = new JLabel(imageIcon[i]);
qtyField[i] = new JTextField(3);
}
gbc.gridx =0;
for (int i = 0; i < ELEMENTS; i++) {
if (i % 3 == 0) {
gbc.gridy += 2;
gbc.gridx = 0;
}
panel.add(foodLabel[i], gbc);
gbc.gridy++;
panel.add(qtyField[i], gbc);
gbc.gridx++;
gbc.gridy--;
tabbedPane.addTab(text, panel);
}
}
错误指向
file[i + 1] = new File("C:\\Users\\tony\\Desktop\\JapanesePanNoodles.png");
【问题讨论】:
-
哪一行抛出异常? ELEMENTS的价值是什么?
-
ELEMENTS 为 9。错误指向
file[i] = new File("C:\\Users\\tony\\Desktop\\MedSalad.png"); -
你确定错误没有指向下面的一行吗?
-
@Sentry 感谢您的指出。帖子已更新。
标签: java arrays user-interface indexoutofboundsexception