为什么我不能改变图标的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();
}
}
在使用setBounds添加控件之前取消JFrame的布局设置
this.setLayout(null);
不能设置x &JLabel
的y坐标,因为JFrame
使用其默认的BorderLayout布局管理器,该管理器根据布局实现安排其组件。
setBounds
仅在使用绝对定位(或null
布局)时有效,应避免使用此选项(!)。
看起来您正在尝试将JLabel
定位在框架(0, 0
)的左上角。要做到这一点,您可以:
- 左对齐标签
- 在
PAGE_START
位置添加标签
这将是:
CL = new JLabel(new ImageIcon(...), JLabel.LEFT);
this.getContentPane().add(CL, BorderLayout.PAGE_START);