Munchmallow Munchmallow - 2 months ago 10
Java Question

JScrollPane doesn't belong to JTable

I added a JScrollPane for my JTable. It showed up, but not scrollable.

public class AddDepartment extends JFrame {
private static JPanel contentPane;
private Connection DBConnection;
static Connection conn = new DBConnection().connect();
static PreparedStatement pstmt = null;
static ResultSet rs = null;
static DefaultTableModel model = null;
private static JTable tableDepartments;
private static JScrollPane scrollPane;

public AddDepartment() throws SQLException {
model = new DefaultTableModel();
tableDepartments = new JTable(model);
tableDepartments.setSize(new Dimension(197, 66));
tableDepartments.setLocation(161, 34);


private static void updateDepartments() throws SQLException {
try {
String sql = "SELECT Name FROM Departments";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();

while ( {
String departmentName = rs.getString("Name");
model.addRow(new Object[] { departmentName });
if (tableDepartments.getRowCount() > 5) {
scrollPane = new JScrollPane(tableDepartments);
scrollPane.setSize(new Dimension(10, 50));
scrollPane.setLocation(360, 34);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
} finally {

Departments table:

Departments table

This is how it looks like

Above picture shows how it looks like. I cannot scrolldown.


By constraining your JTable size:

tableDepartments.setSize(new Dimension(197, 66));

you prevent it from sizing as needed and thus prevent it from scrolling. Don't do this, but instead let it expand to its desired size. If this doesn't fix your problem, then you will need to create and post a valid sscce, a program that has no database code, no code not relevant to the problem and that demonstrates your problem for us.

Other issues include a gross over-use of the static modifier, and your setting absolute sizes and positions (and likely use of null layouts) but that's for another question

You're adding your JTable twice to the GUI, once to the JScrollPane (good) and again to the contentPane (bad), and this is messing you up since you can only add a component to one container. The 2nd add is removing the jtable from the jscrollpane. Solution: don't do this. Add the jscrollpane to the contentPane, not the JTable.

So get rid of: