TAGS :Viewed: 9 - Published at: a few seconds ago

[ Disappearing components in JScrollPane ]

I'm trying to add scroll view in my Swing-UI project. So I've got a JPanel(container) with some JPanels(cards) inside, and I want to put a container in JScrollPane:

MealListPanel mlp = new MealListPanel(meals);   
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10,50,1000,400);
scrollPane.setLayout(new ScrollPaneLayout());
scrollPane.add(mlp);
this.add(scrollPane);

After that everything is ok, but when I try to scroll, a container disappears:
Before scroll:

Before


To

After

What am I doing wrong?

------- Edit ------ Code of MealListView:

` public class MealListView extends JPanel{

private final List<Meal> meals;
public MealListView(List<Meal> meals) {
    this.meals = meals;
    this.configure();
    this.drawMeals();
}

private void configure() {
    this.setBounds(0, 0, 1000, 700);
    this.setPreferredSize(new Dimension(1000, 700));
    this.setLayout(null);
}

private void drawMeals()
{   
    System.out.println("Drawing meals");
    int daysCount = 2;
    int mealsCount = 3;

    int columnsCount = 0;               
    int rowsCount = 0;

    int viewWidth = 200;
    int viewHeight = 270;

    for(int index = 0;index < meals.size();index++)
    {           
        MealCardView rp = new MealCardView(meals.get(index));
        Rectangle r = new Rectangle((columnsCount * (10+viewWidth)) + 10,
                 (rowsCount * (10+viewHeight)) + 10,
                 viewWidth, viewHeight);
        rp.setBounds(r);            
        this.add(rp);

        columnsCount++;
        if(columnsCount>=mealsCount-1)
        {
            rowsCount++;
            columnsCount=0;             
        }           
    }

}

}

I had to change layout here to null (it was FlowLayout).

Answer 1


Add MealListPanel in JScrollPane's view port instead of using scrollPane.add(mlp);

MealListPanel mlp = new MealListPanel(meals);   
JScrollPane scrollPane = new JScrollPane(mlp);

You can use JScrollPane#setViewport() or scrollPane.getViewport().add(mlp) as well.