Search code examples
javaswingjtablejpaneljoptionpane

JTable inside a JPanel inside a JOptionPane won't resize as wanted


I have two JTable objects inside a JPanel with GridLayout. I put them in a JOptionPane and I show them as an OK_CANCEL popup. I also put a JScrollPane on both tables.

However, the JOptionPane's size is enormous. I have tried setting different table, scroll pane and jpanel sizes with:

table.setSize(int w, int h)
jpanel.setSize(int w, int h)
jscrollpane.setSize(int w, int h)

but none of those would result in a smaller JOptionPane (or table).

This is how it looks, I use 1366*768 as resolution. None of the mentioned above would make any difference

This is how it looks

private void showEditItemSuppliersDialog()
    {
    String newItemSupplierTables [] = { "#", "Name", "" };
        JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));

        /* table 1 */
        allItemsEditItemSuppliersTableModel = new DefaultTableModel(null, newItemSupplierTables);

        allItemsEditItemSuppliersTable = new JTable(allItemsEditItemSuppliersTableModel);
        allItemsEditItemSuppliersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane allItemsEditItemSuppliersTableScrollPane = new JScrollPane();
        allItemsEditItemSuppliersTableScrollPane.setViewportView(allItemsEditItemSuppliersTable);
        /* table 1 end */

        /* table 2 */
        allItemsEditItemSuppliersAllTableModel = new DefaultTableModel(null, newItemSupplierTables);

        allItemsEditItemSuppliersAllTable = new JTable(allItemsEditItemSuppliersAllTableModel);
        allItemsEditItemSuppliersAllTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane allItemsEditItemSuppliersAllTableScrollPane = new JScrollPane();
        allItemsEditItemSuppliersAllTableScrollPane.setViewportView(allItemsEditItemSuppliersAllTable);
        /* table 2 end*/

        panel.add(allItemsEditItemSuppliersTableScrollPane);
        panel.add(allItemsEditItemSuppliersAllTableScrollPane);

        int option = JOptionPane.showConfirmDialog(null, panel, "Edit", JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.YES_OPTION)
        {   
            System.out.println("Pressed OK");
        }
    }

Solution

  • You should set the preferred viewport size of the tables using setPreferredScrollableViewportSize(Dimension).