gpt4 book ai didi

java - 如何在方法之间传输字符串(Java)

转载 作者:行者123 更新时间:2023-12-02 09:39:11 25 4
gpt4 key购买 nike

本质上,我正在尝试收集字符串数据并在另一种方法中使用它。无论我尝试过什么似乎都不起作用。请检查我的代码并告诉我该怎么做。

  • 我尝试将该字符串声明为公共(public)字符串,但由于它位于方法中,所以我不能这样做。
  • 我的目标是将字符串“application_1”传输到button3的setOnAction方法。
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());

button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");

button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
String application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");

} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});

button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});

我希望代码能够使用该字符串

button3.setOnAction(e -> {
// code
});

最佳答案

应该有效:

@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());
String application_1 = "";

button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");

button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");

} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});

button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
System.out.println(application_1); //here you can use the variable

try {

Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});

关于java - 如何在方法之间传输字符串(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57235984/

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