大家晚上好,小弟写了个GridBagConstraints布局不知道报错:
Exception :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)布局封装的方法体:
 private void setupComponet(JComponent component, int gridx, int gridy,
                               int gridwidth, int ipadx, boolean fill) {
        final GridBagConstraints constraint = new GridBagConstraints();
        
        constraint.gridx = gridx;
        constraint.gridy = gridy;
        if (gridwidth > 1) {
         constraint.gridwidth = gridwidth;
        }
        if (ipadx > 0) {
         constraint.ipadx = ipadx;
        }
        //Insets(int top, int left, int bottom, int right) 
        //创建并初始化具有指定顶部、左边、底部、右边 inset 的新 Insets 对象
        constraint.insets = new Insets(0, 10, 0, 10);
        if (fill) {
         constraint.fill = GridBagConstraints.HORIZONTAL;
        }
        System.out.println(constraint.gridy+""+constraint.gridx);
        listFrame.add(component, constraint);
    }组件调用:
JPanel panel2 = new JPanel();
panel2.setLayout(new GridBagLayout());
 
setupComponet(new JLabel("过滤:"), 2, 0, 1, 1, false);-------此步调用封装的方法体,这步出错,final JTextField filterText = new JTextField();
setupComponet(filterText, 3, 0, 1, 150, true);
listFrame.add(panel2,new BorderLayout().NORTH);

解决方案 »

  1.   

    这是由于你传的是JLabel,应该是没有组件约束的,你  listFrame.add(component, null);就可以 
      

  2.   

    不好意思,JLabel是有组件约束的。setupComponet(new JLabel("过滤:"), 2, 0, 1, 1, false);-------此步调用封装的方法体,这步出错, 是因为在
    setupComponet方法中 listFrame.add(component, constraint); 出的问题,constraint是依赖于GirdBagLayout布局的,因为你的listFrame没有使用GirdBagLayout布局才造成的吧