运行程序时出现NullPointerException:
JPanel[] myPanel = new JPanel[totalTests];
JTextField [] mytextfield = new JTextField[totalTests];
JComboBox[] myCombo = new JComboBox[totalTests];
JCheckBox[] myNotReturn = new JCheckBox[totalTests];
JCheckBox[] myNotEval = new JCheckBox[totalTests];
jLabelTestcount.setText(Integer.toString(totalTests));
jLabelToberesulted.setText(Integer.toString(totalTests));
for (int tst=0; tst< TestSetList.size(); tst++){
switch (TestSetList.get(tst).getTestSetup()){
case "TEXT" : {
myPanel[tst] = new JPanel();
myPanel[tst].setLayout(new GridLayout(1,5));
myPanel[tst].setSize(120, 60);
myPanel[tst].setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
myPanel[tst].setVisible(true);
jPanelTests.add(myPanel[tst]);
mytextfield[tst].setSize(10, 10);
myNotReturn[tst].setName("No Return");
myNotEval[tst].setName("Not Evauated");
JLabel testName = new JLabel(TestSetList.get(tst).getTestDesctiption());
myPanel[tst].add(testName);
myPanel[tst].add(mytextfield[tst]);
myPanel[tst].add(myNotReturn[tst]);
myPanel[tst].add(myNotEval[tst]);
myPanel[tst].add(myCombo[tst]);
请帮忙。添加JPanel没有错误,但是当我设置JTextfield的大小时,我得到NullPointerException。
答案 0 :(得分:0)
new JTextField[totalTests]
只构造一个可容纳JTextField
个实例的数组,但您的代码实际上从未构建任何JTextField
个实例。因此,mytextfield[tst]
始终为null
。
现在,关于myPanel[tst]
,您的代码 做了正确的事情 - 它构建了一个新的JPanel
并将其分配给myPanel[tst]
之前它尝试取消引用该数组元素。
在尝试取消引用mytextfield[tst]
之前,您需要执行类似的操作。例如:
mytextfield[tst] = new JTextField();
mytextfield[tst].setSize(10, 10);
...
您遇到与JComboBox和JCheckBox数组类似的问题。
答案 1 :(得分:0)
您的问题本身就有答案。您在JTextField上获取NullPointerException,同时将大小设置为相应的组件。这意味着在设置其大小之前,您尚未初始化JTextField。
mytextfield [tst] = new JTextField(); myNotReturn [tst] = new JCheckBox(); myNotEval [tst] = new JCheckBox();
JPanel[] myPanel = new JPanel[totalTests];
JTextField [] mytextfield = new JTextField[totalTests];
JComboBox[] myCombo = new JComboBox[totalTests];
JCheckBox[] myNotReturn = new JCheckBox[totalTests];
JCheckBox[] myNotEval = new JCheckBox[totalTests];
jLabelTestcount.setText(Integer.toString(totalTests));
jLabelToberesulted.setText(Integer.toString(totalTests));
for (int tst=0; tst< TestSetList.size(); tst++){
switch (TestSetList.get(tst).getTestSetup()){
case "TEXT" : {
myPanel[tst] = new JPanel();
myPanel[tst].setLayout(new GridLayout(1,5));
myPanel[tst].setSize(120, 60);
myPanel[tst].setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
myPanel[tst].setVisible(true);
jPanelTests.add(myPanel[tst]);
mytextfield[tst] = new JTextField();
mytextfield[tst].setSize(10, 10);
myNotReturn[tst] = new JCheckBox();
myNotReturn[tst].setName("No Return");
myNotEval[tst] = new JCheckBox();
myNotEval[tst].setName("Not Evauated");
JLabel testName = new JLabel(TestSetList.get(tst).getTestDesctiption());
myPanel[tst].add(testName);
myPanel[tst].add(mytextfield[tst]);
myPanel[tst].add(myNotReturn[tst]);
myPanel[tst].add(myNotEval[tst]);
myPanel[tst].add(myCombo[tst]);