You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用CardLayout展示不同排序JList时卡片无法显示

解决CardLayout下JList无法显示的问题

嘿,我一眼就瞅出你代码里的关键问题了——你给JScrollPane添加JList的方式完全错了!

问题出在哪?

JScrollPane是个特殊的容器,它内部有个专门的视口(Viewport)用来承载需要滚动的组件。你直接调用standPane.add(vorlesungen)这种方式,并不会把JList放到视口的显示区域里,而是加到了JScrollPane的其他层,自然就看不到内容了。

修正后的代码

把你添加JList的代码改成下面两种方式之一就行:

方式1:创建JScrollPane时直接传入JList

// 直接用JList初始化JScrollPane
JScrollPane standPane = new JScrollPane(vorlesungen);
JScrollPane profPane = new JScrollPane(vorlesungenProf);
JScrollPane semPane = new JScrollPane(vorlesungenSem);

JPanel cardHolder = new JPanel();
cardHolder.setLayout(new CardLayout());
cardHolder.add(standPane, "STANDARD");
cardHolder.add(profPane, "PROF");
cardHolder.add(semPane, "SEMESTER");

CardLayout cardLayout = (CardLayout)cardHolder.getLayout();
cardLayout.show(cardHolder, "STANDARD");
v.add(cardHolder, BorderLayout.CENTER);

方式2:用setViewportView()方法设置JList

JScrollPane standPane = new JScrollPane();
JScrollPane profPane = new JScrollPane();
JScrollPane semPane = new JScrollPane();

// 用setViewportView替代add方法
standPane.setViewportView(vorlesungen);
profPane.setViewportView(vorlesungenProf);
semPane.setViewportView(vorlesungenSem);

JPanel cardHolder = new JPanel();
cardHolder.setLayout(new CardLayout());
cardHolder.add(standPane, "STANDARD");
cardHolder.add(profPane, "PROF");
cardHolder.add(semPane, "SEMESTER");

CardLayout cardLayout = (CardLayout)cardHolder.getLayout();
cardLayout.show(cardHolder, "STANDARD");
v.add(cardHolder, BorderLayout.CENTER);

额外检查点

  • 确保你的vorlesungen、vorlesungenProf、vorlesungenSem这几个JList已经正确设置了数据模型(比如DefaultListModel),不然就算显示了也是空的哦。
  • 确认容器v本身的布局是BorderLayout,不然BorderLayout.CENTER的约束可能不会生效。

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:12:30