无法使用 ImageIcon 设置 jLabel 的位置
Trouble setting the location of a jLabel with ImageIcon
我是 Java 的新手,我在我的代码中遇到了一个奇怪的情况,我试图让一个 jPanel 在其中加载一个 ImageIcon,无论它是否位于左上角图像的大小。出于某种原因,我的代码在屏幕中间垂直显示图像,但水平左对齐。
最奇怪的是,当我使用消息框进行调试时,在消息框上单击“确定”后,图像会移动到我想要的角落。这仅在我取消注释 imo 完全不相关的行时有效,因为它告诉我绘制图像后 jLabel 的边界。
我的代码如下:
private void OpenWidefieldActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file;
file = fileChooser.getSelectedFile();
BufferedImage Image1 = null;
try {
Image1 = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(SMLMFrame.class.getName()).log(Level.SEVERE, null, ex);
}
int w = Image1.getWidth();
int h = Image1.getHeight();
ImageIcon imgIcon;
imgIcon = new ImageIcon(Image1);
jLabel1.setBounds(0, 0, w, h);
Rectangle r = jLabel1.getBounds();
jLabel1.setIcon(imgIcon);
r = jLabel1.getBounds();
//SMLMFrame.infoBox(r.toString(), "TITLE BAR MESSAGE");
jLabel1.setBounds(r);
所以基本上我的主要问题是将 jLabel 移到角落,但实际上我更感兴趣的是为什么最后打开信息框会移动它。
For some reason, my code displays the Image in the middle of the screen vertically but left-aligned horizontally.
Swing 使用布局管理器来定位组件。在不知道您使用的是哪个布局管理器的情况下,我们无法判断为什么会这样。
jLabel1.setBounds(r);
手动设置组件的边界可以临时改变组件的位置。但是,下次调用布局管理器时,组件的 size/location 将被重置。例如,尝试调整框架的大小,因为这会导致布局管理器被调用。
因此,您的问题的解决方案是使用合适的布局管理器。也许是左对齐的简单 FlowLayout
?
阅读 Layout Managers 上的 Swing 教程部分了解更多信息。
我是 Java 的新手,我在我的代码中遇到了一个奇怪的情况,我试图让一个 jPanel 在其中加载一个 ImageIcon,无论它是否位于左上角图像的大小。出于某种原因,我的代码在屏幕中间垂直显示图像,但水平左对齐。
最奇怪的是,当我使用消息框进行调试时,在消息框上单击“确定”后,图像会移动到我想要的角落。这仅在我取消注释 imo 完全不相关的行时有效,因为它告诉我绘制图像后 jLabel 的边界。
我的代码如下:
private void OpenWidefieldActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file;
file = fileChooser.getSelectedFile();
BufferedImage Image1 = null;
try {
Image1 = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(SMLMFrame.class.getName()).log(Level.SEVERE, null, ex);
}
int w = Image1.getWidth();
int h = Image1.getHeight();
ImageIcon imgIcon;
imgIcon = new ImageIcon(Image1);
jLabel1.setBounds(0, 0, w, h);
Rectangle r = jLabel1.getBounds();
jLabel1.setIcon(imgIcon);
r = jLabel1.getBounds();
//SMLMFrame.infoBox(r.toString(), "TITLE BAR MESSAGE");
jLabel1.setBounds(r);
所以基本上我的主要问题是将 jLabel 移到角落,但实际上我更感兴趣的是为什么最后打开信息框会移动它。
For some reason, my code displays the Image in the middle of the screen vertically but left-aligned horizontally.
Swing 使用布局管理器来定位组件。在不知道您使用的是哪个布局管理器的情况下,我们无法判断为什么会这样。
jLabel1.setBounds(r);
手动设置组件的边界可以临时改变组件的位置。但是,下次调用布局管理器时,组件的 size/location 将被重置。例如,尝试调整框架的大小,因为这会导致布局管理器被调用。
因此,您的问题的解决方案是使用合适的布局管理器。也许是左对齐的简单 FlowLayout
?
阅读 Layout Managers 上的 Swing 教程部分了解更多信息。