2017-06-07 34 views

回答

1

不知道這是你在找什麼...

Button node = new Button(); 
node.getStyleClass().add("my-new-style-class"); 

.my-new-style-class { 
    -fx-padding: 5; 
} 
+0

不,我想在代碼中定義樣式類,而不是css文件。 – user2858883

0

的想法是創建一個臨時文件stlyesheet,裏面寫入新的樣式類,樣式表添加到列表並添加新的樣式類。

這裏是一個工作示例:

Button button = new Button("My Text"); 

button.setOnAction(e -> { 

    try { 
     // Create a new tempfile that will be removed as the application exits 
     File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css"); 
     tempStyleClass.deleteOnExit(); 

     // Write the stlye-class inside 
     try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) { 
      printWriter.println(".temp-style { -fx-text-fill: red; }"); 
     } 

     // Add the style-sheet and the style-class to the node 
     button.getStylesheets().add(tempStyleClass.toURI().toString()); 
     button.getStyleClass().add("temp-style"); 

    } catch (IOException e1) { 
     e1.printStackTrace(); 
    } 
}); 
相關問題