x和y坐标都为0为什么显示出来的字会在中间


package GUI1;

import javax.swing.*;
import java.awt.*;

public class test3 {
    public static void main(String[] args) {
        JFrame jframe=new JFrame("操作事件");
        jframe.setLocation(220,160);
        jframe.setSize(320,240);
        JButton jButton=new JButton("设置字体颜色");
        JPanel jPanel=new JPanel();
        JLabel jLabel=new JLabel("字体颜色");
        jLabel.setForeground(Color.red);
        jLabel.setOpaque(true);
        jLabel.setBackground(Color.black);
        jPanel.setBackground(Color.white);
        jframe.setLayout(null);
        jPanel.setLayout(null);
        jButton.setBounds(50,145,200,50);
        jLabel.setBounds(0,0,100,100);
        jPanel.setBounds(10,0,280,140);
        jframe.add(jPanel);
        jframe.add(jButton);
        jPanel.add(jLabel);
        jframe.setDefaultCloseOperation(3);
        jframe.setVisible(true);
    }
}

img


为什么 jLabel.setBounds(0,0,100,100);x和y坐标都为0为什么显示出来的字会在中间

基于Monster 组和GPT的调写:

如果要将JLabel放置在指定的位置,可以使用setBounds()方法将其大小和位置手动设置为所需的值。如果你不需要在JLabel中间显示文本,可以使用setHorizontalAlignment()和setVerticalAlignment()方法将文本对齐到左上角。

下面是一个修改后的示例代码:

import javax.swing.*;
import java.awt.*;

public class test3 {
    public static void main(String[] args) {
        JFrame jframe=new JFrame("操作事件");
        jframe.setLocation(220,160);
        jframe.setSize(320,240);
        JButton jButton=new JButton("设置字体颜色");
        JPanel jPanel=new JPanel();
        JLabel jLabel=new JLabel("字体颜色");
        jLabel.setForeground(Color.red);
        jLabel.setOpaque(true);
        jLabel.setBackground(Color.black);
        jPanel.setBackground(Color.white);
        jframe.setLayout(null);
        jPanel.setLayout(null);
        jButton.setBounds(50,145,200,50);
        jLabel.setBounds(0,0,100,20); // 将JLabel的大小设置为100x20,位置为(0, 0)
        jLabel.setHorizontalAlignment(SwingConstants.LEFT); // 左对齐文本
        jLabel.setVerticalAlignment(SwingConstants.TOP); // 上对齐文本
        jPanel.setBounds(10,0,280,140);
        jframe.add(jPanel);
        jframe.add(jButton);
        jPanel.add(jLabel);
        jframe.setDefaultCloseOperation(3);
        jframe.setVisible(true);
    }
}


img

位置不是一个xy就确定了,前面0 0是指定了初始位置,但是你的height太高了啊,而文字默认是在component的中心的,你把height调小就行了

这是一个Java代码片段,它尝试将一个JLabel的 bounds设置为0、0、100、100,这意味着该Label在水平和垂直方向上的坐标均为0。

当x和y坐标均为0时,JLabel的坐标系统默认会将其放置在整个窗口中,即其坐标为整个窗口的中心。因此,当x和y坐标均为0时,jLabel的 bounds设置为(0,0,100,100),它将被放置在中间位置。

如果你想要让JLabel在特定位置显示特定内容,你可以使用JLabel的setLocation()方法来指定其位置,或者使用setBounds()