gpt4 book ai didi

java - 线程中的异常 "main"java.lang.IllegalArgumentException : setSelectedIndex: 4 out of bounds

转载 作者:行者123 更新时间:2023-12-01 07:33:32 27 4
gpt4 key购买 nike

我正在尝试制作一个游戏,但我的代码根本无法工作,我不知道为什么。我是一名经验不足的新手程序员,并且对我的代码感到非常沮丧。我一直在尝试解决这个问题,但没有成功。请帮助我。

public class hello {
//Int's and things
static JButton Play = new JButton("<PLAY>");
static JFrame pane = new JFrame("CIrCUT 0.0.2");
static JLabel Title = new JLabel("CIrCUT");
static JLabel none = new JLabel(" ");
static JPanel panel = new JPanel(new GridLayout(10, 10, 10, 10));
static JButton Options = new JButton("<OPTIONS>");
static JPanel panel2 = new JPanel(new GridLayout(10, 10, 10, 10));
static String b[] = new String[3];
static int panelLoct = 1;
JComboBox optionlist = new JComboBox();

void initialize() {
b[0] = "High";
b[1] = "Medium";
b[2] = "Low";

//title
pane.setTitle("CIrCUT 0.0.2");
//drop down
optionlist .setModel(new DefaultComboBoxModel(new String[] {"Option", "High", "Medium", "Low"}));
optionlist.setSelectedIndex(4);
optionlist.addActionListener((ActionListener) this);
//other pane-related things
if (panelLoct == 1) {
pane.setLayout(new GridLayout(10, 10));
panel.setMaximumSize(new Dimension(500, 500));
pane.setSize(500, 500);
pane.setMaximumSize(new Dimension(500, 500));
panel.add(Title);
panel.add(none);
panel.add(Play);
panel.add(Options);
panel2.add(optionlist);
Play.setSize(new Dimension(500, 450));
pane.setLocation(500, 50);
pane.setBackground(Color.lightGray);
pane.setContentPane(panel);
pane.pack();
pane.setMinimumSize(new Dimension(500, 500));
pane.setContentPane(panel);
OptionButtonHandler cbHandler = new OptionButtonHandler();
Options.addActionListener(cbHandler);
pane.setVisible(true);
}
}

public void windowClosing(WindowEvent e) {
System.exit(0);
}

private static class OptionButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
pane.remove(panel);
pane.add(panel2);
}
}

public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
cb.getSelectedItem();
}

public static void main(String args[]) {
hello a = new hello();
a.initialize();
}
}

我认为问题出在 JComboBox 上,但每当我删除它时,我都会收到错误。

编辑

这是错误

at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at hello.initialize(hello.java:36)
at hello.main(hello.java:81)

最佳答案

JComboBox optionlist = new JComboBox();
optionlist.setSelectedIndex(4);

这将导致异常,因为您正在设置 JComboBox 的索引。只是不要这样做。在选择索引之前,先用项目填充组合框。

事实上,您在哪里向 JComboBox 添加任何项?

请注意,将来如果您对代码生成的异常有疑问,您需要在此处发布实际的异常堆栈跟踪,并为我们指示哪一行抛出异常。

关于java - 线程中的异常 "main"java.lang.IllegalArgumentException : setSelectedIndex: 4 out of bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15127495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com