【问题标题】:How define the size and the location of a JPanel如何定义 JPanel 的大小和位置
【发布时间】:2020-06-20 16:50:52
【问题描述】:

我想开发一个可以显示计数器的代码。

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 swing jpanel jlabel


    【解决方案1】:

    Swing 默认使用布局管理器来排列组件。如果您希望提供绝对定位,您必须首先禁用默认布局管理器。这可以通过以下方式实现。

    public Compteur() {
        setLayout(null);
    

    但是我建议不要使用绝对布局,这些布局通常难以使​​用且难以维护。考虑阅读official documentation中的布局管理器

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-10-10
        • 2014-02-17
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 1970-01-01
        • 2014-10-03
        • 1970-01-01
        • 2021-01-16
        相关资源
        最近更新 更多