我有一个对象“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/