简体   繁体   English

如何定义 JPanel 的大小和位置

[英]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. JLabel(compte)中的计数器本身在JPanel(panneau)中显示得很好,但我无法定义它的大小和位置。

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

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

Swing uses a layout manager by default to arrange components. Swing 默认使用布局管理器来排列组件。 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考虑阅读官方文档中的布局管理器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM