在javafx中设置字体

问题描述:

如何在java fx的表格视图中将字体设置为列。我有一个3列的表,我想为每个列设置不同的字体。另外,是否可以在运行时更改字体。请帮助一些示例代码。在javafx中设置字体

更改表列方式:

你应该使用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列使用本stlye 1,列2使用样式2

Supply a custom cell factory供给cells到你已申请已在CSS定义styleclasses。链接的文档包含应该为您提供足够信息的示例。

可以使用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文件