我在做什么:
我有一段代码,我在其中获取可运行路径并将其设置为按钮单击上的标签以进行测试,以便在运行时成功获取正在运行的jar路径。
问题:
当通过eclipse调试或运行模式运行时,我在标签中获取路径,但是当我将代码导出到jar文件时,按钮单击时没有发生任何事情。
代码:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestProject extends JFrame {
private JPanel contentPane;
static JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestProject frame = new TestProject();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestProject() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
setContentPane(contentPane);
lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getJarFileRunningPath();
}
});
contentPane.add(btnNewButton, BorderLayout.SOUTH);
}
public static String getJarFileRunningPath()
{
String currentPath = null;
try
{
File currentFilePath = new File(TestProject.class.getProtectionDomain().
getCodeSource().getLocation().toURI().getPath());
currentPath = currentFilePath.getAbsolutePath();
lblNewLabel.setText(currentPath);
}
catch (URISyntaxException e)
{
}
return currentPath;
}
}
更新:
我发现不知何故“File currentFilePath = new File ...”行被卡住了,而不是抛出异常。
感谢将来的任何帮助。 :-)