将JScrollPane添加到JTable组件 [英] Adding a JScrollPane to a JTable component

查看:83
本文介绍了将JScrollPane添加到JTable组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 JScrollPane 添加到我的 JTable ,但它似乎不起作用。我有一个 JTable ,包含21行和5列,我正在按照以下代码添加 JScrollPane 。 ..

I am trying to add a JScrollPane to my JTable, but it doesn't seem to works. I have a JTable with 21 rows and 5 columns, and I'm adding a JScrollPane as per the following code...

public Targy_felv() {
    JScrollPane scrollPane;
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(600, 300);
    table = new JTable();
    Object o[] = new Object[]{"Tárgynév", "Oktató", "Kredit", "Félév", "Tárgykód"};
    table.setModel(new DefaultTableModel(get_Tárgyak(), o));
    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(table);
    frame.add(table);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

有人可以帮我理解滚动条没有出现的原因。

Could someone please help me to understand why the scrollbars aren't appearing.

推荐答案

确保将 JScrollPane 添加到 JFrame ,而不是 JTable 。如果你最初只有一个 JFrame 和一个 JTable 你就可以像这样添加它......

Make sure you're adding the JScrollPane to your JFrame, not the JTable. If you originally just had a JFrame and a JTable you would have added it like this...

JTable table = new JTable();
JFrame frame = new JFrame();
frame.add(table);

如果您要添加 JScrollPane ,你需要更改 add()方法来添加 JScrollPane 而不是 JTable ,或者像这样......

If you're adding the JScrollPane, you need to change your add() method to add the JScrollPane instead of the JTable, either like this...

JTable table = new JTable();
JFrame frame = new JFrame();
frame.add(new JScrollPane(table));

或者像这样,如果你需要引用 JScrollPane 稍后在您的代码中......

or like this, if you need to reference the JScrollPane later in your code...

JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame();
frame.add(scrollPane);

这篇关于将JScrollPane添加到JTable组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆