gpt4 book ai didi

java - 从导出的 jar 获取路径不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:21 24 4
gpt4 key购买 nike

我在做什么:
我有一段代码,其中我获取可运行路径并将其设置为单击按钮时的标签以进行测试,以便在运行时成功获取正在运行的 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...”行被卡住了,也没有抛出异常。

感谢将来的任何帮助。 :-)

最佳答案

我拿了你的代码来检查你的问题,但代码对我来说工作正常。生成的 jar 显示标签中的路径。

enter image description here

我认为你的问题不是编码问题。

关于java - 从导出的 jar 获取路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47151472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com