如何将 JTable 添加到 JPanel

How to add a JTable to a JPanel

我的问题看起来有点愚蠢,但每次我使用 swing 时,我都会遇到表格问题。所以我正在做一个学校项目,我需要使用 GridBagLayout 将一些 JTable 添加到 JPanel,但是我看不到 JTable 正在添加到我的面板。

这是代码:

public class MainView extends JFrame {

    private static Dimension dimensionFenetre = new Dimension(1980, 1000);
    Object[][] team = {
        {"France", "80"},
        {"Germany", "80"},
        {"Italy", "80"},
        {"England", "80"}
};

String  titleColumn[] = {"Team", "Overall"};

public MainView() {

    JPanel panelFenetre = new JPanel(new GridBagLayout());
    add(panelFenetre);
    setVisible(true);
    panelFenetre.setVisible(true);
    setSize(dimensionFenetre);

    panelFenetre.add(getTable1(), getTable1Constraints());
}

private JTable getTable1() {

    JTable table = new JTable(team, titleColumn);
    table.setVisible(true);

    return table;
}

private GridBagConstraints getTable1Constraints() {

    GridBagConstraints gbcTable1 = new GridBagConstraints(
            0, 1,
            1, 1,
            1, 1,
            GridBagConstraints.CENTER,
            GridBagConstraints.NONE,
            new Insets(0, 0, 0, 0),
            0, 0);

    return gbcTable1;
  }
}

还有一个简单的 Main :

public class Main {

public static void main(String[] args) {
    MainView mainView = new MainView();
  }
}

如果有人,提供一些线索,那就太好了。

提前致谢。

  1. 不要调用 setSize(),而是在添加组件后调用 pack() 让布局管理器完成他们的工作。
  2. 首先将 JTable 添加到 JScrollPane,然后将其添加到 GUI。
  3. 最重要的是,在添加所有组件 之后,不要在 JFrame 上调用 setVisible(true)

适合我:

public MainView() {
    JPanel panelFenetre = new JPanel(new GridBagLayout());
    add(panelFenetre);

    // setVisible(true);
    // panelFenetre.setVisible(true);
    // setSize(dimensionFenetre);

    panelFenetre.add(new JScrollPane(getTable1()), getTable1Constraints());        
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
}