问题描述
我正在为我的学校项目开发 Java 应用程序。我需要在容器中显示“卡片”列表。如果卡片数量超过 3,由于容器的大小,以下卡片将不可见: 有问题的卡片列表:
所以我尝试使用 JScrollPane,因为它似乎是解决方案。 但我没有成功使面板可滚动。有什么想法吗?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class FenetrePrincipale extends JFrame implements ActionListener,MouseListener{
LinkedList<Carte> cartesFidelite; //Liste des cartes de fidélités
JPanel conteneurCarte;
JPanel monConteneurMain;
JScrollPane scrollPane;
public FenetrePrincipale(LinkedList<Carte> c){
cartesFidelite=c; //List of cards
//Window
setTitle("Gestionnaire de cartes");
setBounds(0,1195,722);
setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
//CONTAINER Main
containerMain = new JPanel();
containerMain.setLayout(null);
containerMain.setBackground(Color.white);
//CONTAINER List of cards
conteneurCarte = new JPanel();
conteneurCarte.setLayout(null);
conteneurCarte.setBackground(new Color(242,242,242));
conteneurCarte.setBorder(BorderFactory.createLineBorder(new Color(199,199,199)));
scrollPane = new JScrollPane(conteneurCarte);
scrollPane.setBounds(34,90,377,550);
containerMain.add(scrollPane);
public void refreshListCard (){
conteneurCarte.removeAll();
int i = 0;
for(Carte e : cartesFidelite){
e.setLocation(15,(15+i*(172+15)));
conteneurCarte.add(e);
e.addMouseListener(this);
i++;
}
conteneurCarte.updateUI();
}
感谢您的帮助:)
解决方法
不要使用空布局!
Swing 旨在与布局管理器一起使用。
特别是如果您不使用布局管理器,JScrollPane 将无法工作。
另外,不要调用updateUI()。如果您从面板中添加/删除组件,则使用:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
这将依次调用布局管理器。
阅读 Layout Managers 上的 Swing 教程