Domanda

I am creating a JFrame application that contains a menu, toolbar, table, and button panel. I want to use a scroll pane as the top-level container so that if the user resizes the application the buttons, etc. don't just fall off the screen.

Here is my constructor code for the main frame:

JPanel mainPanel = new JPanel(); // borderlayout, north=toolbar, center=table, south=buttton panel   
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder());        
mainPanel.add(new MainToolBar(inventoryActions, false), BorderLayout.NORTH);
InventoryTable inventoryTable = new InventoryTable();
JScrollPane tableScrollPane = new JScrollPane(new JTable());       
mainPanel.add(new JScrollPane(tableScrollPane), BorderLayout.CENTER);        
mainPanel.add(tableScrollPane, BorderLayout.CENTER);
inventoryTable.adjustColumnWidths();
mainPanel.add(new InventoryActionsButtonPanel(inventoryActions), BorderLayout.SOUTH);

JScrollPane mainScrollPane = new JScrollPane();
mainScrollPane.setBorder(BorderFactory.createEmptyBorder());
mainScrollPane.setViewportView(mainPanel);

getContentPane().add(mainScrollPane, BorderLayout.CENTER);

As you can see.. I am using a JPanel to contain the toolbar, table (nested in another scroll pane), and button panels. I then put this panel inside the main scroll pane. Finally, I add the main scroll pane to the content pane.

The initial size of my application is 800x600. When I run it everything looks fine. Here is a screenshot:

Initial Startup

When I resize the frame, however, the scroll panel "activates" way before the frame gets small as you can see here:

Scroll Pane Activated

Any idea as to why my scroll panel is showing the scroll bars while the frame is still that big? Is there some preferred size that I have to set?

Thank you.

Note, if I comment out the line of code that adds the scroll pain to the main panel (center) or if I use another swing component, such as a JButton, it doesn't behave as before:

//mainPanel.add(tableScrollPane, BorderLayout.CENTER);

Here is a screenshot:

Scrolls Correctly

È stato utile?

Soluzione

The (main) problem is the fact that the JScrollPane is using the JTable's getPreferredScrollableViewportSize, which overrides the getPreferredSize property.

By default this is set to 450x400.

You can change this by using JTable#setPreferredScrollableViewportSize

Another trick is to add the JTable to another container (like a JPanel) and set this as the scroll pane's view instead

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top