我想知道如何获得JLabel图像名称而不是整个路径,我尝试使用
jLabel.getIcon();
但它使用整个路径而不仅仅是名称(即name,berries.png)。当我使用getIcon()时,结果是:
文件:/ C:/Users/lolne/Desktop/FCaWfD%20-%20Desktop%20Updated%20Version/build/classes/resources/quiz/berries.png
我只希望找到berries.png的结尾部分。我正在使用此代码作为学校作业的食物网页游戏,这是使用它的代码:
public void checkResults(){
JLabel[] consumers = {
consumer1,
consumer2,
consumer3,
consumer4,
consumer5,
};
switch(RandomNumber.randomNumber){
case 1:
if(producer.getIcon().equals(producers[0])){
correct++;
}else{
producer.setBorder(BorderFactory.createLineBorder(Color.RED));
}
for(int i = 0; i < 5; i++){
if(consumers[i].getIcon().equals(consumers1.get(i))){
correct++;
}else{
consumers[i].setBorder(BorderFactory.createLineBorder(Color.RED));
}
}
break;
case 2:
if(producer.getIcon().equals(producers[1])){
correct++;
}else{
producer.setBorder(BorderFactory.createLineBorder(Color.RED));
}
for(int i = 0; i < 5; i++){
if(consumers[i].getIcon().equals(consumers2.get(i))){
correct++;
}else{
consumers[i].setBorder(BorderFactory.createLineBorder(Color.RED));
}
}
break;
case 3:
if(producer.getIcon().equals(producers[2])){
correct++;
}else{
producer.setBorder(BorderFactory.createLineBorder(Color.RED));
}
for(int i = 0; i < 5; i++){
if(consumers[i].getIcon().equals(consumers3.get(i))){
correct++;
}else{
consumers[i].setBorder(BorderFactory.createLineBorder(Color.RED));
}
}
break;
}
}
总而言之,我的问题是,“我如何获得图像本身的名称,而不是图像的整个路径”
答案 0 :(得分:1)
您可以使用file getName()方法来获取文件的名称
File file = new File("C:/Users/lolne/Desktop/FCaWfD%20-%20Desktop%20Updated%20Version/build/classes/resources/quiz/berries.png");
System.out.println(file.getName());
将输出
berries.png