首页 > 解决方案 > JLabel,如何设置坐标

问题描述

我想通过在特定位置使用坐标来放置 JLabel。但相反,标签出现在我的窗口顶部的中间。请告诉我我做错了什么。

类 PaintPanel 扩展 JPanel {

private Color color = Color.RED;
private GeneralPath path;
Graphics2D graphics2D;
ArrayList<PathToDraw> generalPathToDraws;



public PaintPanel() {
    path = new GeneralPath();
    ArrayList<Object> generalPathToDraws = new ArrayList<>();
    //path.moveTo(564, 278);
}

//add multiplay general pathes to drowing
public void addMultiplayPathesAndDrowThem(ArrayList<PathToDraw> ptd){

    generalPathToDraws = ptd;
    updateGraphics();
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    graphics2D = (Graphics2D) g;


    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    JLabel A_label = new JLabel("B");
    A_label.setLocation(300, 300);
    A_label.setForeground(Color.red);
    add(A_label);

它看起来如何

标签: javaswingjlabel

解决方案


如果你想使用“setLocation”,你的面板布局应该是“null”

public static class MainPanel extends JPanel{
    public MainPanel() {
        this.setLayout(null);
        JLabel A_label = new JLabel("B");

        A_label.setBounds(100, 100, 10, 10);//set location & size
        //Or
        //A_label.setSize(10, 10);
        //A_label.setLocation(100, 100);

        A_label.setForeground(Color.red);
        this.add(A_label);
    }
}

推荐阅读