只是寻找一个快速的答案:是否可以使用 JTable 作为 JScrollPane 的 columnHeader?
我有一个已配置的 JTable,具有不同的列宽和列标题,并计划将标题用作滚动 Pane 的 columnHeader。我怎样才能做到这一点?我用
scrollPane.setColumnHeaderView(table);
但它没有出现。
所以感谢Guillaume Polet,应该是
scrollpane.setColumnHeaderView(table.getTableHeader());
但是现在所有的列都具有相同的宽度,尽管我在我的表格中为它们设置了不同的值。如何让表格列显示不同的宽度?
最佳答案
如果我没理解错的话,您希望表格的列标题显示在视口(viewport)的列标题中,但您希望在视口(viewport) View 中显示其他内容?
然后您需要获取表格标题并将其设置为视口(viewport)的列标题。
这是一个例子:
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();
}
});
}
}
关于java - 使用 JTable 作为 JScrollPane 的 columnHeader,同时保持每列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035102/