且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JLabel定位不起作用

更新时间:2023-01-08 14:09:47

以最小尺寸(如果可调整大小,则具有更大的宽度和高度)提供ASCII艺术作品或GUI预期布局的简单图形-以显示额外的应该使用空间.我可以从当前的描述中猜出这是***的.

Provide ASCII art or a simple drawing of the intended layout of the GUI at minimum size, and if resizable, with more width and height - to show how the extra space should be used. This is the best I can guess the requirement from the current description.

它显示了如何在标签的左侧和顶部(通过使用EmptyBorder)在红色面板中填充20像素,在蓝色面板中填充100 x 30.

It shows how to pad the left and top of the label (by using an EmptyBorder) by 20 pixels in the red panel, and by 100 x 30 in the blue panel.

阅读代码中的注释以获取更多提示,并检查Java Docs是否使用了与原始源代码不同的任何方法.

Read the comments in the code for further tips, and check the Java Docs for any methods used that are different to the original source code.

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

public class Start extends JFrame {

    public Start() {
        super();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(2, 1));

        JPanel panel1 = new JPanel(new FlowLayout(SwingConstants.LEADING));
        panel1.setBorder(new LineBorder(Color.RED, 4));
        add(panel1);
        JLabel label1 = new JLabel("HELLO!", SwingConstants.LEADING);
        //label1.setBounds(20,20,100,20);

        // to provide a 20 x 20 offset, an empty border will do nicely.
        label1.setBorder(new EmptyBorder(20, 20, 0, 0));

        // Did you actually check the Java Docs for these methods? 
        // They do not do what you seem to think they do.
        //label1.SetAlignmentX(20);
        //label1.SetAlignmentY(20);
        panel1.add(label1);

        JPanel panel2 = new JPanel(new FlowLayout(SwingConstants.LEADING));
        panel2.setBorder(new LineBorder(Color.BLUE, 4));
        add(panel2);
        JLabel label2 = new JLabel("HELLO!", SwingConstants.LEADING);
        label2.setBorder(new EmptyBorder(30, 100, 30, 100));
        panel2.add(label2);

        pack();
    }

    public static void main(String[] args) {
        Start frame = new Start();
        frame.setVisible(true);
    }
}