3

如何从 jpanel 中删除组件。在下面的代码中,文本字段是根据 val 创建的。这对于创建工作正常。但是当微调器中的值降低时,文本字段也应该减少。

我试图从数组 txtField 中删除所有组件并且没有工作。

int val = (int) textFieldGen.getModel().getValue(); //getting the value from JSpinner

JTextField[] txtField = new JTextField[val]; 

//tried panel.revalidate(); panel.repaint();

//removing elements if exists.  gives null pointer exception.  

try {
     for (JTextField txtComp : txtField) {
       panel.remove(txtComp);
    }
} catch (Exception ex) {
        System.out.println(ex);
}

panel.revalidate();
panel.repaint();


//creating    
int row = 1;
for (int i = 0; i < txtField.length; i++) {
    row++;           
    layout.appendRow(RowSpec.decode("30px"));
    txtField[i] = new JTextField(10);
    panel.add(txt[i], cc.xy(4, row));
}
panel.revalidate();
panel.repaint();
4

3 回答 3

5

我看不到您remove(...)在“面板”JPanel 上调用的位置,因此我不知道您如何删除 JTextFields。一些建议:

  • 如果您必须走您提议的当前路线,请使用单个专用容器 JPanel,该容器将 JTextFields 保存在 GridLayout 中并且不包含其他组件。
  • 在添加新组件之前删除所有组件(如果这是您需要做的)
  • 在移除和添加之后调用revalidate()容器 JPanel 上的和“repaint()”。
  • 考虑改为使用 JTable,您只需添加或删除行。在我看来,这将是解决此类问题的最简单和最干净的解决方案。
于 2012-09-18T01:01:42.390 回答
2

Why not simply have a method accepting the number of JTextFields you want and let it return a JPanel with the correct number of needed JTextFields already added to the JPanel with appropriate layout and all:

public JPanel createPanel(int numberOfTextFields) {
    JPanel panel=new JPanel(new ...);//create new panel

    JTextField tfs[]=new JTextField[numberOfTextFields];//create array of textFields

    for(int i=0;i<numberOfTextFields;i++) {
        tfs[i]=new JTextField();//create the textfield
        panel.add(tfs[i]...);//add it to the panel
    }

    return panel;
}

and simply remove the last JPanel from the JFrames contentPane.

Or empty the JFrame again using: getContentPane().removeAll(); and add the new JPanel to it and the JPanel which contains the user controls, though the user controls panel wont have to be re-created each time.

于 2012-09-18T09:12:45.800 回答
2

JTextField[] txtField = new JTextField[val];

This line does NOT init the array, just creates one with a count of val. The elements are null by default, hence throwing the NullPointerException when you iterate the array with the for-each loop.

You need to initialize the array with valid JTextField objects.

于 2012-09-18T02:53:29.433 回答