【问题标题】:Why cant I move JLabel Icon?为什么我不能移动 JLabel 图标?
【发布时间】:2013-01-18 06:19:28
【问题描述】:

为什么我不能更改图标的 x 和 y 坐标?我真正需要的只是将图像添加到屏幕上。我什至需要使用 JLabel 吗?

package bit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class BIT extends JFrame
{
    JLabel CL;

    public BIT()
    {
        CL = new JLabel(new ImageIcon(this.getClass().getResource("final-image.jpg")));
        CL.setBounds(0,0,100,100);

        this.getContentPane().add(CL);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(5,5,1000,500);
        this.setResizable(false);
        this.setVisible(true);
    }
    public static void main(String[] args) 
    {
        new BIT();
    }
}

【问题讨论】:

  • 您能更具体地说明您要做什么吗?

标签: java swing icons jlabel


【解决方案1】:

在使用 setBounds 添加控件之前取消设置 JFrame 的布局

this.setLayout(null);

【讨论】:

    【解决方案2】:

    您不能设置 JLabel 的 x 和 y 坐标,因为 JFrame 正在使用其默认的 BorderLayout 布局管理器,该管理器根据布局实现排列其组件。

    setBounds 仅在使用绝对定位(或null 布局)和this option should be avoided(!) 时有效。

    您似乎正试图将JLabel 定位在框架的左上角 (0, 0)。为此,您可以:

    • 标签左对齐
    • PAGE_START位置添加标签

    这将是:

    CL = new JLabel(new ImageIcon(...), JLabel.LEFT);
    this.getContentPane().add(CL, BorderLayout.PAGE_START);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 2015-04-30
      • 2020-04-02
      • 1970-01-01
      • 2011-04-07
      • 2019-09-06
      • 1970-01-01
      相关资源
      最近更新 更多