简体   繁体   English

Java 带有 ImageIcon 的构造函数

[英]Java Constructor with ImageIcon

I created a small program that inserts an ImageIcon (resized in another class) into a JLabel through a constructor I am struggling to return the icon in the JLabel我创建了一个小程序,通过构造函数将 ImageIcon(在另一个类中调整大小)插入 JLabel 我正在努力返回 JLabel 中的图标

Here's my code:这是我的代码:

Main Class :主要 Class

        traforma imageObj = new traforma("image1.png"); //traforma is another class

        ImageIcon Icon11 = new ImageIcon(imageObj.Icon11);

         imageLabel.setIcon(Icon11);  //Here he gives me error, he can't find my ' Icon11 '

traforma Class :变形 Class

public class traforma {


    public  traforma(String image) {
        ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
        Image image = Icon1.getImage(); 
        Image newimg = image.getScaledInstance(470, 360,  java.awt.Image.SCALE_SMOOTH);
        ImageIcon Icon11 = new ImageIcon(newimg);

    }
    Object Icon11 = this.Icon11; // i guess the problem is here


}

I am new to Java, Hope I have been clear我是 Java 的新手,希望我已经清楚了

This code makes no sense:这段代码没有意义:

Object Icon11 = this.Icon11;

The problem is, that the variable "Icon11" that you initialized within the method is not used anywhere.问题是,您在方法中初始化的变量“Icon11”没有在任何地方使用。 After method completed, it will be thrown away.方法完成后,将被丢弃。 What you can do, is to assign the created icon object to the member variable, not to the local variable.您可以做的是将创建的图标 object 分配给成员变量,而不是分配给局部变量。

Thy style of your code is not perfect: the usage of lower and upper case, the usage of ImageIcon instead of directly loading image, etc. But if we keep it as close to your code as possible and try to do minimal changes, the working code may look as follows:你的代码风格并不完美:大小写的使用,ImageIcon 的使用而不是直接加载图像等。但是如果我们尽可能地接近你的代码并尝试做最小的改变,那么工作代码可能如下所示:

public class traforma {

    public  traforma(String image) {
        ImageIcon Icon1 = new ImageIcon(getClass().getClassLoader().getResource(image));
        Image image = Icon1.getImage(); 
        Image newimg = image.getScaledInstance(470, 360,  java.awt.Image.SCALE_SMOOTH);
        this.Icon11 = new ImageIcon(newimg);
    }

    public ImageIcon Icon11;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM