关于label.setIcon(new ImageIcon("xxx.jpg"));无法显示问题

来源:互联网 发布:mac os 10.13.1 重装 编辑:程序博客网 时间:2024/06/01 10:20

运行课本实例发现的问题如题。


代码:

package ksxt;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class ClientWindow extends JFrame{
   ClientLogin clientLogin;          
   GetTestFile getTestFile;          
   ClientTestArea clientTestArea; 
   JLabel label=null;     
   JTabbedPane tabbedPane;
   public ClientWindow(){
     setTitle("标准化考试系统(客户端)");
     label=new JLabel();
     label.setText(getTitle());
     label.setForeground(Color.orange);
     label.setFont(new Font("隶书",Font.BOLD,22));
     label.setIcon(new ImageIcon("welcome.jpg"));
     label.setHorizontalTextPosition(SwingConstants.CENTER);
     label.setBackground(Color.green); 
     tabbedPane=new JTabbedPane(JTabbedPane.LEFT);
     clientLogin=new ClientLogin();
     getTestFile=new GetTestFile(); 
     clientTestArea=new ClientTestArea();
     tabbedPane.add("系统标题",label); 
     tabbedPane.add("登录",clientLogin);
     tabbedPane.add("选择试卷",getTestFile);
     tabbedPane.add("答卷",clientTestArea);
     add(tabbedPane,BorderLayout.CENTER);
     validate();
     setVisible(true);
     setBounds(100,50,460,280);
     setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
     addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e){
                      int n=JOptionPane.showConfirmDialog(null,"确认退出吗?","确认对话框",
                                               JOptionPane.YES_NO_OPTION );
                      if(n==JOptionPane.YES_OPTION)  
                         System.exit(0);
                    }});
     validate();   
   }
   public static void main(String args[]){
      new ClientWindow();
   }
}


自然认为welcome.jpg文件只要与当前类文件在同一目录下即可,其实所谓相对路径的起点是工程的根目录

如图所示,此时运行ksxt应用程序,welcome.jpg在此ksxt目录下是无法显示的。Test2017java才是相对路径的起点,故修改方式可以是:

①在Test2017java文件夹下copy一个welcome.jpg文件

②将label.setIcon(new ImageIcon("welcome.jpg"));改为

label.setIcon(new ImageIcon("src/ksxt/welcome.jpg"));

或者是label.setIcon(new ImageIcon("./src/ksxt/welcome.jpg"));


参考资料:http://www.doc88.com/p-5015902363089.html


原创粉丝点击