Reputation: 357
I'm currently adding JPanels to a JScrollPane by pressing a button:
However, I can't get the panels to stack on top of each other when adding more than 1 panel to the scroll pane. The previously added panel in the scroll pane seems to be getting removed when I call getViewport().add().
Is there a way to get a JScrollPane to save it's children and make my GUI look like this when adding multiple JPanels with a button press?
MainWindow class:
JScrollPane trackerPanel = new JScrollPane();
trackerPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
trackerPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
trackerPanel.setPreferredSize(new Dimension(500, 400));
frame.getContentPane().add(BorderLayout.NORTH, trackerPanel);
frame.setVisible(true);
//method: called from EnterButtonListener to create and append TrackerTile to GUI
public void addTrackerTile() {
incrementTrackerPanelCounter();
TrackerTile trackerTile = new TrackerTile();
trackerPanel.getViewport().add(trackerTile);
}
TrackerTile class:
public class TrackerTile extends JPanel implements Scrollable {
public Dimension preferredSize = new Dimension(794, 100);
public TrackerTile() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
@Override
public Dimension getPreferredSize() {
return preferredSize;
}
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(794, 100);
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 128;
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 128;
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
Upvotes: 0
Views: 703
Reputation: 324108
The basic logic to create the GUI should be:
JPanel somePanel = new JPanel( some layout );
JScrollPane scrollPane = new JScrollPane( somePanel );
frame.add(scrollPane. BorderLayout.CENTER);
Then in the ActionListener
that adds new panels you just do:
somePanel.add( new TrackerTile() );
So its just like adding components to a panel. The only difference is that the panal has been added to a scroll pane.
There is no need to implement Scrollable
. But if you really want to customize the Scrollable properties
, then you need to implement Scrollable on the "somePanel", not the individual components you add to "somePanel".
Or another option is to use the Scrollable Panel which implements the Scrollable
interface and has methods that allow you to customize the behaviour.
Upvotes: 2