JScrollPane中消失的组件

时间:2014-06-12 15:38:59

标签: java swing jscrollpane

我试图在Swing-UI项目中添加滚动视图。所以我有一个JPanel(容器)里面有一些JPanels(卡片),我想把一个容器放在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);

之后一切正常,但是当我尝试滚动时,容器会消失:
在滚动之前:

Before


After

我做错了什么?

-------编辑------ MealListView代码:

` 公共类MealListView扩展了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;             
        }           
    }

}

}

我必须将此处的布局更改为null(它是FlowLayout)。

1 个答案:

答案 0 :(得分:2)

JScrollPane的观看端口添加MealListPanel,而不是使用scrollPane.add(mlp);

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

您也可以使用JScrollPane#setViewport()scrollPane.getViewport().add(mlp)