【问题标题】:How to add a JTable to a JPanel如何将 JTable 添加到 JPanel
【发布时间】:2016-04-28 16:12:06
【问题描述】:

我的问题似乎有点愚蠢,但每次我使用 swing 时,我都会遇到桌子问题。所以我正在做一个学校项目,我需要将一些 JTable 添加到一个带有 GridBagLayout 的 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();
  }
}

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

提前致谢。

【问题讨论】:

    标签: java swing jtable gridbaglayout


    【解决方案1】:
    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);
    }
    

    【讨论】:

    • 首先,感谢您花时间回答我。所以我已经按照你的指示。现在我可以看到我猜想的 JScrollPane 的边框,如果我在上面调用setPreferedSize()。但我看不到上面有数据的表格。
    • @SebastienMURE:你一定做错了什么,因为它对我来说很好。请参阅上面的修改。
    • 是的,我创建 JScrollPane 的方式似乎有问题,现在一切正常,非常感谢。
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2013-04-05
    • 2017-09-19
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多