简体   繁体   中英

How can I use a FontAwesome icon in a TreeView cell in JavaFX?

I was reading the TreeView examples in the Oracle docs which showed them adding image icons to the cells. I want to use FontAwesome icons instead of images. I have the FA stylesheet applied to my FXML file and I have a separate button that uses an FA icon, so I know that works. My FontAwesome class properties simply return the unicode for whichever icon you choose. My app does not display the icon in the TreeView cell at all. What am I doing wrong?

private final Node serverIcon = new Label(FontAwesome.SERVER);
private final Node dbIcon = new Label(FontAwesome.DATABASE);

TreeItem<String> root = new TreeItem<>("Available Connections");
        root.setExpanded(true);
        connTree.setCellFactory(tree -> {
            TreeCell<String> cell = new TreeCell<String>() {
                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty) ;
                    if (empty) {
                        setText(null);
                    } else {
                        setText(item);
                    }
                }
            };
            cell.setOnMouseClicked(event -> {
                if (!cell.isEmpty()) {
                    TreeItem<String> treeItem = cell.getTreeItem();
                    this.selectedServer = cell.getText();
                }
            });
            return cell;
        });
        for(Connection conn: conns){
            TreeItem<String> item = new TreeItem<String>(conn.host);
            item.setGraphic(serverIcon);
            root.getChildren().add(item);
        }
        connTree.setRoot(root);

I would advise you to check out http://fxexperience.com/controlsfx/ It has ControlsFX embed into the jar.

You can than use it either in java code or directly in your FXML.

FXML Example:

<Button fx:id="btGamePage" maxHeight="15.0" mnemonicParsing="false" prefHeight="4.0" onAction="#viewGame" snapToPixel="false" styleClass="first" text="" HBox.hgrow="NEVER">
<graphic>
   <Glyph fontFamily="FontAwesome" icon="LINK"/>  
</graphic> </Button>

Here's an example for how to add an icon to a TreeView as a TreeItem :

final var glyph = FontAwesomeIcon.valueOf( "BOOKMARK" );
final var icon = FontAwesomeIconFactory.get().createIcon( glyph, "1.2em" );
final var item = new TreeItem<>( "Item Description", icon );
tree.getRoot().getChildren().add( item );

Where tree is the TreeView instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM