繁体   English   中英

使用JTable作为JScrollPane的columnHeader,同时保持每列的宽度

[英]using JTable as JScrollPane's columnHeader while maintaining width of each column

只是寻找一个快速的答案:是否可以使用JTable作为JScrollPane的columnHeader?

我有一个具有不同列宽和列标题的configed JTable,并计划使用标题作为滚动窗格的columnHeader。 我怎样才能做到这一点? 我把桌子摆好

scrollPane.setColumnHeaderView(table);

但它没有显示出来。

所以感谢Guillaume Polet,它应该是

scrollpane.setColumnHeaderView(table.getTableHeader());

但是现在所有的列都具有相同的宽度,尽管我在表中设置了不同的值。 我怎么能让表格栏显示不同的宽度?

如果我理解正确,您希望表格的列标题显示在视口的列标题中,但是您希望视口视图中还有其他内容吗?

然后,您需要获取表头并将其设置为视口的列标题。

这是一个例子:

import java.awt.BorderLayout;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTableHeader {

    protected void initUI() {
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        Vector<String> colNames = new Vector<String>();
        for (int i = 0; i < 5; i++) {
            colNames.add("Col-" + (i + 1));
        }

        table = new JTable(data, colNames);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        scrollpane = new JScrollPane();
        scrollpane.setColumnHeaderView(table.getTableHeader());
        scrollpane.setViewportView(new JLabel("some label in the viewport view"));
        frame.add(scrollpane, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    private JTable table;
    private JScrollPane scrollpane;

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTableHeader().initUI();
            }
        });
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM