0

i'm working on a java app for my school project. I need to display a list of "cards" in a container. If the number of card exced 3, the following cards will no be visible due to the size of the container : The list of cards in question:

https://i.stack.imgur.com/ZMhxj.png

So I'm trying to use a JScrollPane because it seems to be the solution. But I don't succed to make the Panel scrollable. Any idea ?

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, 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);

here is the method which display cards :

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();
}

Thanks for your help :)

camickr
  • 321,443
  • 19
  • 166
  • 288
Adrien
  • 1

1 Answers1

1

Don't use a null layout!.

Swing was designed to be used with layout managers.

In particular a JScrollPane will not work if you don't use layout managers.

Also, don't invoke updateUI(). If you add/remove components from a panel then you use:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint(); 

This will in turn invoke the layout manager.

Read the Swing tutorial on Layout Managers

camickr
  • 321,443
  • 19
  • 166
  • 288
  • In class we learn to use the null layout. I would like to keep using it, is there any way of making a panel scrollable with it ? – Adrien Mar 25 '21 at 12:31
  • Then you should take another class. As I stated earlier Swing was designed to be used with layout managers, so you should be learning the proper way to use Swing. You should NOT need to "unlearn" something. Any code you write would effectively be writing layout management code, so why not take advantage of the existing API instead of reinventing the wheel. – camickr Mar 25 '21 at 14:12