To create a scrollable JTable
component we have to use a JScrollPane
as the container of the JTable
. Besides, that we also need to set the table auto resize mode to JTable.AUTO_RESIZE_OFF
so that a horizontal scroll bar displayed by the scroll pane when needed. If we do not turn off the auto resize mode, the columns of the table will be resized to fit the available window size.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;
public class ScrollableJTable extends JPanel {
public ScrollableJTable() {
initializeUI();
}
private static void showFrame() {
JPanel panel = new ScrollableJTable();
panel.setOpaque(true);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Scrollable JTable");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ScrollableJTable::showFrame);
}
private void initializeUI() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 250));
JTable table = new JTable(20, 20);
// Turn off JTable's auto resize so that JScrollPane will show a horizontal
// scroll bar.
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}
}
Below is the result of the code snippet above.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Using this, I can’t add content to the table.