如何定义JPanel的大小和位置

问题描述 投票:0回答:1

我想开发一个允许显示计数器的代码。

位于JLabel(compte)中的计数器本身在JPanel(panneau)中本身显示良好,但我无法定义其大小和位置。

这是我的程序的两类代码:

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();
    }
}
java jpanel jlabel
1个回答
0
投票

为了使组件在JFrame上具有绝对位置,JFrame必须具有null的内部布局(据我所知)。

© www.soinside.com 2019 - 2024. All rights reserved.