2017-08-30 27 views
0

我想使剛剛textarea的和在舞臺上的一個按鈕,一個小的Java FX應用程序時,您在文本區域鍵入一些字符串,然後按提交它顯示在舞臺上的小桌子與結果每個詞有多少次出現。 所以我的問題是:是否映射是找到事件的最佳解決方案,即使我不知道找到事件以及如何將字符串從文本區域連接到映射的關鍵字。的JavaFX將textarea的值轉換成一個HashMap

public class Main extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Button btn = new Button(); 
     btn.setText("Word counting"); 
     TextArea txt=new TextArea(); 
     txt.setMaxSize(450, 200); 
     btn.setOnAction(new EventHandler<ActionEvent>() { 

      @Override 
      public void handle(ActionEvent event) { 

       primaryStage.hide(); 
       ShowResults.drugiProzor(); 
      } 
     }); 

     BorderPane root = new BorderPane(); 

     root.setTop(txt); 
     HBox hbox=new HBox(); 
     hbox.setPadding(new Insets(20,20,100,180)); 
     hbox.getChildren().add(btn); 
     root.setBottom(hbox); 


     Scene scene = new Scene(root, 450, 300); 

     primaryStage.setTitle("Word counting!"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     launch(args); 
    } 
} 

和第二類又是表視圖GUI類

public class ShowResults { 

    static Stage secondaryStage; 
    public static void drugiProzor() { 
     secondaryStage=new Stage(); 
     TableView table=new TableView(); 

     TableColumn column1=new TableColumn("Word"); 
     column1.setMinWidth(200); 


     TableColumn column2=new TableColumn("Number of occurencies"); 
     column2.setMinWidth(200); 


     table.getColumns().addAll(column1,column2); 

     StackPane pane=new StackPane(); 
     pane.getChildren().add(table); 
     Scene scene = new Scene(pane, 450, 300); 


     secondaryStage.setScene(scene); 
     secondaryStage.setTitle("Counting words"); 
     secondaryStage.show(); 
    } 
} 

和第三類shoyld是神奇在哪裏happends像這樣的類:

public class Logic { 

    public void logic() 

    } 
} 

回答

0

你可以這樣做

public Map<String, Long> countWordOccurences(String text) { 
    return Pattern.compile("\\s+") // regular expression matching 1 or more whitespace 
     .splitAsStream(text)  // split at regular expression and stream words between 
            // group by the words themselves and count each group: 
     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 
} 

檢查的Javadoc,看看每一步都做:PatternCollectors.groupingBy()Function

如果你想在不區分大小寫的方式來算,你可以用String::toLowerCase

.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting())); 

更換Function.identity()如果你想忽略標點符號,你可以添加

map(s -> s.replaceAll("[^a-zA-Z]","")) 

到流水線。

+0

謝謝你,你真是幫了我,這是可能以某種方式把裏面的tableview? – Pera

+0

@Pera嗯,是的,只需填寫表格視圖和來自地圖的數據即可。 –

+0

我設法把所有的結果只有一個行,我想有一個行一個單詞和/對不起occurencies的數量這一切,但我試圖完成tjis,我不是一個程序員,只有我知道db和提前 – Pera