2016-02-03 18 views
-1

基本上我的代碼是這樣的:在javafx中,如何使事件處理程序中的方法影響其餘代碼?

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 
        } 
       }); 

我想add方法(這是事件處理程序的內部)真正用於其他地方編輯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. 
     } 

數組列表不會爲空。我該怎麼做呢?我很抱歉,如果有更好的方式來說這個,但我真的不知道如何研究這個,我試過了。謝謝。

+1

您當前的代碼有什麼問題?只需讓你的數組列表可以訪問按鈕的事件處理程序和for循環。 – ItachiUchiha

+0

我不相信 –

+0

你不相信什麼? – ItachiUchiha

回答

0

一個簡單的例子,說明如何在方法之間共享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); 
    } 
} 
相關問題