0

I made a Jtable in my class, but once it fills up the whole designing page, it can't display the content further down. I decided to make the table scrollable. Below are my codes to initialize the Jtable:

brandTbl.setModel(new DefaultTableModel(
            new Object[][] {
                {null, null, null},
                {null, null, null},
        },
        new String[] {
            "Name", "Status", "ID"
        }
    ));
    brandTbl.setFont(new Font("Tahoma", Font.PLAIN, 14));
    brandTbl.setFillsViewportHeight(true);
    brandTbl.setColumnSelectionAllowed(true);
    brandTbl.setCellSelectionEnabled(true);
    brandTbl.setBackground(Color.WHITE);
    brandTbl.setBounds(490, 125, 480, 271);
    contentPane.add(brandTbl);

I tried to use JScrollPane, but my IDE told me it can't be resolved to a type.

camickr
  • 321,443
  • 19
  • 166
  • 288
Ian
  • 1
  • 1
    Don't do this: `brandTbl.setBounds(490, 125, 480, 271)'`. Period. – Hovercraft Full Of Eels Jul 17 '23 at 21:19
  • 2
    you must put the table in a `JScrollPane` (as its `ViewportView`) - see its [javadoc](https://docs.oracle.com/en/java/javase/20/docs/api/java.desktop/javax/swing/JScrollPane.html), it sure is a valid type (if correctly `import`ed) -- also check Oracle's tutorial [How to Use Tables](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#show) – user16320675 Jul 17 '23 at 21:26
  • 1
    Yes, put the JTable into a JScrollPane, and then place the scroll pane into a container that uses BorderLayout, such as the ContentPane, if you wish. Never constrain the table's size in such an artificial way either as that will mess up the scroll pane's functioning. – Hovercraft Full Of Eels Jul 17 '23 at 21:29
  • If I delete `brandTbl.setBounds()`, then the entire table would disappear. @HovercraftFullOfEels – Ian Jul 19 '23 at 17:22
  • Because you're likely using a null layout -- DON'T – Hovercraft Full Of Eels Jul 19 '23 at 17:23
  • Read the Swing docs to learn how to use JTables, JScrollPanes and layout managers. Otherwise you're code will be fighting against the Swing library, which is not wise, fun or useful. – Hovercraft Full Of Eels Jul 19 '23 at 17:24

0 Answers0