Reputation: 91
I have 2 issue that i need to ask, 1st how to get the horizontal scroll for my JTable, currently it shrink all the columns which is not readable at all. I have 20 columns to show in a Table.
2nd, how to adjust my table height width maximum to my screen size.
my current code is
Container cp = getContentPane();
ConnectionDB con = new ConnectionDB();
tableModel = con.getRecord(DEFAULT_QUERY);
table = new JTable(tableModel);
table.setPreferredScrollableViewportSize(new Dimension(900, 500));
table.setFont(new Font("Tahoma", Font.PLAIN, 12));
scrollPane = new JScrollPane(table);
centerPanel.add(scrollPane, BorderLayout.CENTER);
centerPanel.setBorder(BorderFactory.createTitledBorder("Books:"));
cp.add("Center", centerPanel);
Kindly help me in it, Thanks in Advance.
Upvotes: 2
Views: 13221
Reputation: 21
This may help you.
Dimension d = new Dimension(900, 800);
tbl_transaction.setAutoResizeMode(tbl_transaction.AUTO_RESIZE_OFF);
tbl_transaction.setPreferredSize(d);
tbl_transaction.setPreferredScrollableViewportSize(d);
Upvotes: 0
Reputation: 3941
To prevent that all columns are resized to the ScrollPane
size you can disable the auto resize:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Adding your ScrollPane
to the center of the BorderLayout
should set the maximum size to the screen size, because normally the JFrame can't become bigger.
To set the size of the ScrollPane
s ViewPort to the screen size you can use the awt Toolkit
.
table.setPreferredScrollableViewportSize(Toolkit.getDefaultToolkit().getScreenSize());
Upvotes: 10
Reputation: 1238
Add your JTable
inside JScrollPane
and set for scrollbars.
new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Code sample for JTable
to fit the screen size
public class TestJTableFitsScreenWidth {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
DefaultTableModel dtm = new DefaultTableModel(
new String[][]{
new String[] {"A", "B", "D"},
new String[] {"D", "E", "F"}
},
new String[] {"col1", "col2", "col3"});
JTable table = new JTable(dtm);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(table, BorderLayout.CENTER);
f.setVisible(true);
f.pack();
}
});
}
}
Upvotes: 1