Reputation: 1061
just looking for a quick answer: is it possible to use a JTable as a JScrollPane's columnHeader?
I have a configed JTable with different column width and column title, and plan to use the header as the columnHeader of a scrollpane. How can I achieve this? I set the table with
scrollPane.setColumnHeaderView(table);
but it doesn't show up.
so thanks to Guillaume Polet, it should be
scrollpane.setColumnHeaderView(table.getTableHeader());
but all the columns have the same width now although I set them with different values in my table. How could I let the table columns show different width?
Upvotes: 1
Views: 4850
Reputation: 47608
If I understand you correctly, you want the column headers of your table to appear in the column headers of the viewport but you want something else in the viewport view?
Then you need to grab the table header and set it as the column header of the viewport.
Here is an example:
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();
}
});
}
}
Upvotes: 3