在javafx中,如何使事件处理程序中完成的方法影响代码的其余部分?
基本上我的代码是这样的:在javafx中,如何使事件处理程序中完成的方法影响代码的其余部分?,java,javafx,Java,Javafx,基本上我的代码是这样的: fileOpener.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(final ActionEvent e) { myFileList.add(openMusicTracks.showO
fileOpener.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent e) {
myFileList.add(openMusicTracks.showOpenDialog(window));
System.out.println(myFileList.getName(0)); //prints file name so I know this works
}
});
fileOpener.setOnAction(
新的EventHandler(){
@凌驾
公共无效句柄(最终操作事件e){
添加(openMusicTracks.showOpenDialog(窗口));
System.out.println(myFileList.getName(0));//打印文件名,所以我知道这是可行的
}
});
我希望add方法(在EventHandler内部)能够实际编辑其他地方的arraylist,以便稍后在中引用它时
ObservableList<String> playList = FXCollections.observableArrayList ();
for(int i = 0; i < myFileList.size(); i++) {
playList.add(i, myFileList.get(i).getName());
System.out.println(myFileList.getName(0)); //doesn't print the file name, so I know this doesn't work.
}
observeList playList=FXCollections.observearraylist();
对于(int i=0;i
arraylist不会为空。我该怎么做?我很抱歉,如果有一个更优雅的方式来表达这个,但我真的不知道如何研究这个,我已经尝试过了。谢谢。一个简单的示例演示了如何在方法之间共享ArrayList
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
public class Main extends Application {
private List<String> list = new ArrayList<>();
@Override
public void start(Stage primaryStage) {
Button add = new Button("Add");
Button display = new Button("Show");
// Add Items
add.setOnAction(event -> list.add("Item"));
// Display Items
display.setOnAction(e -> {
printAndClear();
});
VBox root = new VBox(10, add, display);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
private void printAndClear() {
list.forEach(System.out::println);
list.clear();
}
public static void main(String[] args) {
launch(args);
}
}
导入javafx.application.application;
导入javafx.geometry.Pos;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.layout.VBox;
导入javafx.stage.stage;
导入java.util.ArrayList;
导入java.util.List;
公共类主扩展应用程序{
私有列表=新的ArrayList();
@凌驾
公共无效开始(阶段primaryStage){
按钮添加=新按钮(“添加”);
按钮显示=新按钮(“显示”);
//添加项目
add.setOnAction(事件->列表.add(“项”));
//显示项目
显示设置操作(e->{
printAndClear();
});
VBox根=新的VBox(10,添加,显示);
根部设置对齐(位置中心);
场景=新场景(根,200200);
初级阶段。场景(场景);
primaryStage.show();
}
私有void printAndClear(){
list.forEach(System.out::println);
list.clear();
}
公共静态void main(字符串[]args){
发射(args);
}
}
您当前的代码有什么问题?只需让button的事件处理程序和for循环都可以访问arraylist。你到底不相信什么?抱歉,我按enter键以为它会给我另一行,但我该如何让它可以访问呢?arraylist是一个状态变量,如果帮助我添加了一个解决方案,那么它们都在同一个类中,这解释了我之前所说的。