java - 如何向对象添加 ImageIcon?

标签 java oop object imageicon

我有一个对象“Team”,其中包含一些分数变量、名称(字符串)和 Logo 。 Logo 的类型为 ImageIcon:

public class Team {

    public String name;
    public ImageIcon logo;
    public int points;
    public int plusGoals;
    public int minGoals;
    public int goalsTotal;


public Team (String name, ImageIcon logo, int points, int plusGoals, int minGoals, int goalsTotal){      

    this.name = name;
    this.logo = logo;
    this.points = points;
    this.plusGoals = plusGoals;
    this.minGoals = minGoals;
    goalsTotal = plusGoals - minGoals;

当我想创建一个新对象并输入对象属性的值时,我不知道如何添加 ImageIcon 路径。

所以:

Team Blabla = new Team("Blabla", ..., 0, 0, 0, 0);

我尝试过这些东西,但它们不起作用:

Team Blabla = new Team("Blabla", C:\\Users\\path.png, 0, 0, 0, 0);
Team Blabla = new Team("Blabla", "C:\\Users\\path.png", 0, 0, 0, 0);
Team Blabla = new Team("Blabla", ImageIcon("C:\\Users\\path.png"), 0, 0, 0, 0);

如何在这一行直接添加图片路径?

最佳答案

您可以进行如下修改:

public Team(String name, String location, int points, int plusGoals,
            int minGoals, int goalsTotal) {
        this.logo = new ImageIcon(location); // using ImageIcon(URL location)    
         }

Note: Here we are using ImagIcon class Constructor -> ImageIcon(URL location) which Creates an ImageIcon from the specified URL.

工作代码

import javax.swing.ImageIcon;

class Team {

    public String name;
    public ImageIcon logo;
    public int points;
    public int plusGoals;
    public int minGoals;
    public int goalsTotal;

    public Team(String name, String location, int points, int plusGoals,
            int minGoals, int goalsTotal) {
        this.logo = new ImageIcon(location); // using ImageIcon(URL location)

        this.name = name;

        this.points = points;
        this.plusGoals = plusGoals;
        this.minGoals = minGoals;
        goalsTotal = plusGoals - minGoals;
    }

    public void print() {
        System.out.println("\n" + name + "\n" + logo + "\n" + points + "\n"
                + plusGoals + "\n" + minGoals + "\n" + goalsTotal);

    }
}

public class imageicon {

    public static void main(String[] args) {

        Team obj = new Team("a", "C:\\Users\\path.png", 1, 2, 3, 4);
        obj.print();

    }
}

关于java - 如何向对象添加 ImageIcon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830928/

相关文章:

Java函数返回空字符串

java - 如何在vlcj中使用 "MediaPlayer"准备播放列表?

java - 使用继承和多态来解决一个常见的游戏问题

php - 我如何使用面向对象编程改进此代码?

python - 多态性的实际例子

javascript - 迭代存储在对象中的键值项

javascript - 好的Javascript代码

Java - 没有新实例的对象

java - Morphia 在 Spring 通过 log4j 登录

java - Caused by : org. postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication super 用户连接