组件没有出现在我的formPanel上

时间:2015-07-20 03:52:24

标签: java swing

我有一个扩展JPanel的formPanel,它直接位于扩展JFrame的MainFrame上。

// this is the constructor of the mainframe

public MainFrame() {
    super("Invoice Generator");

    toolBar=new ToolBar();
    formPanel=new FormPanel();

    setLayout(new BorderLayout());
    add(toolBar, BorderLayout.NORTH);
    add(formPanel, BorderLayout.CENTER);


// this is where i add the custom components

 setBackground(new Color(170, 175, 255));


        setVisible(true);
        layout();
        setSize(new Dimension(500, 250));
    }



public void layout() {

    setLayout(new GridBagLayout());

    GridBagConstraints gc = new GridBagConstraints();

    /////////////first row/////////////////////////////
    gc.gridx=0;
    gc.gridy=0;
    gc.weightx=1;
    gc.weighty=1;
    gc.insets=new Insets(2, 2, 2, 2);
    gc.anchor=GridBagConstraints.NONE;

    add(new JButton("Booked by"), gc);

    gc.gridx=1;
    gc.gridy=0;
    gc.weightx=1;
    gc.weighty=1;
    gc.insets=new Insets(2, 2, 2, 2);
    gc.anchor=GridBagConstraints.NONE;

    add(text1, gc);

}

我的组件没有出现在我的formPanel上,为什么?

1 个答案:

答案 0 :(得分:0)

您的layout方法似乎在JFrame而不是formPanel

上运行

像...一样的东西。

public void layout() {

    formPanel.setLayout(new GridBagLayout());

    GridBagConstraints gc = new GridBagConstraints();

    /////////////first row/////////////////////////////
    gc.gridx=0;
    gc.gridy=0;
    gc.weightx=1;
    gc.weighty=1;
    gc.insets=new Insets(2, 2, 2, 2);
    gc.anchor=GridBagConstraints.NONE;

    formPanel.add(new JButton("Booked by"), gc);

    gc.gridx=1;
    gc.gridy=0;
    gc.weightx=1;
    gc.weighty=1;
    gc.insets=new Insets(2, 2, 2, 2);
    gc.anchor=GridBagConstraints.NONE;

    formPanel.add(text1, gc);

}

可能会更好。

我很想创建一个从JPanel扩展的自定义类,它封装了这些字段,然后只需将它添加到框架中。