【问题标题】:Disappearing components in JScrollPaneJScrollPane 中消失的组件
【发布时间】:2014-06-12 15:38:58
【问题描述】:

我正在尝试在我的 Swing-UI 项目中添加滚动视图。所以我有一个 JPanel(container),里面有一些 JPanel(cards),我想在 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);

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


我做错了什么?

------- 编辑 ------ 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)。

【问题讨论】:

    标签: java swing jscrollpane


    【解决方案1】:

    JScrollPane 的视口中添加MealListPanel,而不是使用scrollPane.add(mlp);

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

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

    【讨论】:

    • 这行得通,但只有一点点。现在只有卡片是不可见的。
    • 你为什么使用setBounds()setLayout()
    • 分享MealListPanel的相关代码?
    • 嗯...我在主 JPanel 中使用 AbsoluteLayout,所以我必须(?)使用setBounds() 设置滚动窗格的位置。 setLayout() 在这里无关紧要 - ScrollPanelayout 默认设置。我试图将布局设置为 null。
    • I'm using AbsoluteLayout in main JPanel, - 不要! Swing 旨在与布局管理器一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多