我有对象' Team'带有一些得分变量,名称(String)和徽标。徽标的类型为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);
如何直接在此行添加图片路径?
答案 0 :(得分:1)
您可以进行如下修改:
public Team(String name, String location, int points, int plusGoals,
int minGoals, int goalsTotal) {
this.logo = new ImageIcon(location); // using ImageIcon(URL location)
}
注意:我们使用ImagIcon类构造函数 - > ImageIcon(网址),用于根据指定的网址创建ImageIcon。
工作代码
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();
}
}