我希望这是一个简单的问题。我有一个JComboBox,选择0,1,2,3 ...... 10。根据JComboBox中选择的数字,我希望我的GUI添加JLabel和JTextField。因此,如果选择数字3,则GUI应添加3个JLabel和3个JTextField。等等。
我正在使用JLabel和JTextFields数组来完成此任务,但我在运行时收到空指针异常,并且没有添加任何标签或字段。
代码:
3
ActionListener代码:
private void createComponents()
{
//Create Action Listeners
ActionListener comboListener = new ComboListener();
//Create Components of the GUI
parseButton = new JButton("Parse Files");
parseButton.addActionListener(comboListener);
numberLabel = new JLabel("Number of Files to Parse: ");
String[] comboStrings = { "","1", "2","3","4","5","6","7","8","9","10" };
inputBox = new JComboBox(comboStrings);
inputBox.setSelectedIndex(0);
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(2,10));
centerPanel = new JPanel();
centerPanel.add(numberLabel);
centerPanel.add(inputBox);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(parseButton, BorderLayout.SOUTH);
totalGUI.add(centerPanel, BorderLayout.CENTER);
add(totalGUI);
}
答案 0 :(得分:0)
感谢MadProgrammer的评论,这个问题已得到解答。
将循环编辑为:
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i] = new JLabel();
fileField[i] = new JTextField();
fieldLabel[i].setText("File "+i+":");
fieldPanel.add(fieldLabel[i]);
fieldPanel.add(fileField[i]);
}
解决了这个问题。