2012-04-13 636 views
3

如何在java fx的表格視圖中將字體設置爲列。我有一個3列的表,我想爲每個列設置不同的字體。另外,是否可以在運行時更改字體。請幫助一些示例代碼。在javafx中設置字體

回答

13

更改表列方式:

你應該使用TableColumn#setCellFactory()定製電池項目的渲染。
例如,數據模型,像這樣Person class

// init code vs.. 
TableColumn firstNameCol = new TableColumn("First Name"); 
firstNameCol.setMinWidth(100); 
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName")); 
firstNameCol.setCellFactory(getCustomCellFactory("green")); 

TableColumn lastNameCol = new TableColumn("Last Name"); 
lastNameCol.setMinWidth(100); 
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName")); 
lastNameCol.setCellFactory(getCustomCellFactory("red")); 

table.setItems(data); 
table.getColumns().addAll(firstNameCol, lastNameCol); 

// scene create code vs.. 

和共用getCustomCellFactory()方法:

private Callback<TableColumn<Person, String>, TableCell<Person, String>> getCustomCellFactory(final String color) { 
     return new Callback<TableColumn<Person, String>, TableCell<Person, String>>() { 

      @Override 
      public TableCell<Person, String> call(TableColumn<Person, String> param) { 
       TableCell<Person, String> cell = new TableCell<Person, String>() { 

        @Override 
        public void updateItem(final String item, boolean empty) { 
         if (item != null) { 
          setText(item); 
          setStyle("-fx-text-fill: " + color + ";"); 
         } 
        } 
       }; 
       return cell; 
      } 
     }; 
    } 

更改表列標題樣式:

TableView像的JavaFX的其他控制使用與jfxrt.jar捆綁在一起的名爲caspian.css的內置樣式表。請參閱answer of "JavaFX 2 and CSS classes"
要更改列字體樣式您可以覆蓋默認的樣式或自它:
重寫:

.table-view .column-header{ 
    -fx-text-fill: -fx-selection-bar-text; 
    -fx-font-size: 16; 
    -fx-font-family: "Arial"; 
} 

定製:

#my-custom .table-view .column-header { 
    -fx-text-fill: red; 
    -fx-font-size: 26; 
    -fx-font-family: "Arial"; 
} 

重寫特效全部TableView S IN的應用程序。所以,如果你喜歡,一旦你定義多個樣式自定義的話,你可以在運行時爲應用自定義樣式任何的tableview,

myTableView.setId("my-custom"); 
... 
// Apply another style at runtime 
myTableView.setId("my-custom2"); 

要看到如何定義和加載樣式表文件,應用程序,檢查出post of "JavaFX How to set scene background image"

但是,應用不同的樣式到不同的列需要更多的努力,我認爲。

+0

感謝您的答覆。這很有幫助。上述樣式適用於表格的所有列標題。是否可以申請每一欄。在您的示例中.table-view .column-header { }適用於所有列標題。我的問題是什麼風格(語法)來指定第1列使用這個stlye 1,第2列使用樣式2 ...。 – user1332356 2012-04-16 18:23:34

+0

我完全誤解了你的問題,我的道歉:)。同時我假設你已經做到了,但我編輯了我的答案以供將來參考。 – 2012-05-22 08:37:02

-1

什麼風格(語法)指定爲第1列使用本stlye 1,列2使用樣式2

Supply a custom cell factory供給cells到你已申請已在CSS定義styleclasses。鏈接的文檔包含應該爲您提供足夠信息的示例。

0

可以使用FXML或CSS文件中設置字體顏色......

# .mainFxmlClass { 
-fx-font-family:nyala,Tahoma,Arial,Helvetica,sans-serif; 
-fx-font-size:1.13em; 
} 

.label{ 
-fx-font-size:1.3em; 
    } 

,並調用和使用.lable或.mainFxmlClass在FXML文件