有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组件未出现在我的formPanel上

我有一个扩展JPanel的formPanel,它直接集中在扩展JFrame的大型机上

// 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) 个答案

  1. # 1 楼答案

    您的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扩展,然后简单地将其添加到框架中