标签不会动态创建一个低于其他标签

时间:2017-10-30 12:54:14

标签: java xml

http://ibb.co/hvrdbR private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
       //删除现有面板         String xmldoc =" ./ src / com / ui / Data.xml&#34 ;;           尝试{             JLabel label2 = new JLabel();
            文件fXmlFile = new File(xmldoc);             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();             Document doc = dBuilder.parse(fXmlFile);             doc.getDocumentElement()正常化();             NodeList nList = doc.getElementsByTagName(" username");              for(int temp = 0; temp< nList.getLength(); temp ++){                 节点nNode = nList.item(temp);                  if(nNode.getNodeType()== Node.ELEMENT_NODE){                     元素eElement =(元素)nNode;                       String text = eElement.getTextContent();                       的System.out.println(文字);
                    jPanel7.setBackground(Color.WHITE);                       jPanel7.setLayout(new FlowLayout());                       jPanel7.add(LABEL2);                      label2.setText(文本);                       label2.setPreferredSize(new Dimension(100,40));                       label2.setFont(new Font(" Times New Roman",Font.BOLD,24));
                      }                catch(Exception ex){                System.out.println("数据库异常:userExists()");             }     }

仅创建标签并粘贴所有用户名

1 个答案:

答案 0 :(得分:0)

在循环的每次迭代中,jPanel7.add(label2)被调用一次。但是,您反复使用相同的JLabel实例。

会发生什么?

JPanel.add(Component)java.awt.Container.add(Component)中定义,并被委托给java.awt.Container.addImpl(Component, Object, int)。在代码中:

 /* Reparent the component and tidy up the tree's state. */
 if (comp.parent != null) {
      comp.parent.remove(comp);
      if (index > component.size()) {
           throw new IllegalArgumentException("illegal component position");
      }
 }
 // ...
 comp.parent = this;

尝试将Component添加到已包含此Container的{​​{1}}将导致在实践中不会发生任何事情。因此,最后,您的Component只有一个孩子 - jPanel7

正确的做法是什么?

label2