Search code examples
javaswingjpaneljlabel

How define the size and the location of a JPanel


I want to develop a code which allows to display a counter.

The counter, which is in a JLabel (compte), itself in a JPanel (panneau) is displayed well but I can't define its size and position.

Here are the codes of the two classes of my program:

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Compteur compteur = new Compteur();
        compteur.setVisible(true);
    }
}
package com.company;

import javafx.scene.layout.Border;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Compteur extends JFrame implements ActionListener {
    private int cpt = 0;
    JButton boutonPlus = new JButton("+");
    JButton boutonMoins = new JButton("-");
    JPanel paneau = new JPanel();
    JLabel compte = new JLabel();


    public Compteur() {
        setSize(1700, 900);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        boutonMoins.setBounds(100, 100, 100, 30);
        boutonPlus.setBounds(250, 100, 100, 30);
        LineBorder lineBorder = new LineBorder(Color.BLACK, 1);
        compte.setBorder(lineBorder);
        this.add(boutonMoins);
        this.add(boutonPlus);
        paneau.add(compte);
        this.add(paneau);
        AfficherCompteur();
        boutonMoins.addActionListener(this);
        boutonPlus.addActionListener(this);
        this.pack();
    }

    private void AfficherCompteur() {
        compte.setText(String.valueOf(cpt));

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == boutonMoins) {
            try {
                cpt--;

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if(e.getSource()==boutonPlus) {
            try {
                cpt++;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        AfficherCompteur();
    }
}

Solution

  • Swing uses a layout manager by default to arrange components. If you wish to provide absolute positioning you must first disable the default layout manager. This can be achieved by the following.

    public Compteur() {
        setLayout(null);
    

    However I would recommend against absolute layouts, these are generally hard to work with and difficult to maintain. Consider reading up on layout managers in the official documentation