【发布时间】:2018-04-19 11:21:55
【问题描述】:
我在做什么:
我有一段代码,我在其中获取可运行路径并将其设置为按钮单击时的标签以进行测试,以便在运行时成功获取运行的 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 ...”行卡住了,也没有抛出异常。
感谢以后的任何帮助。 :-)
【问题讨论】:
-
您是否尝试过远程调试以查看实际发生的情况?
-
嗨吉姆,对不起,我不知道远程调试。 :-(