简体   繁体   中英

How do i change the JavaFX TableCell color when it is selected?

Well, I created a custom TableCell for my TableView. This custom TableCell contains a Link and opens the browser when clicked. Everything is working fine, what I want to do is change the text color of this TableCell when it is selected... This is what I am trying to do:

    callback = new Callback<TableColumn, TableCell>(){
        @Override
        public TableCell call(TableColumn param) {
            return new TableCell<Test, String>(){
                EventHandler handler = new EventHandler<MouseEvent>() {
                    final AM_RSS_FX RSS = AM_RSS_FX.this;
                    @Override
                    public void handle(MouseEvent param) {
                        try {
                            java.awt.Desktop.getDesktop().browse(new URI(RSS.link));
                        } catch (IOException | URISyntaxException ex) {
                            Logger.getLogger(AM_RSS_FX.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                };
                @Override
                public void updateItem(String item, boolean empty){
                    super.updateItem(item, empty);
                    if(!isEmpty()){
                        final AM_RSS_FX RSS = AM_RSS_FX.this;
                        this.setTextFill(Color.BLUE);
                        setText(item);
                        RSS.link = this.getText();
                        this.addEventHandler(MouseEvent.MOUSE_CLICKED, handler);
                    }
                }

                @Override
                public void updateSelected(boolean arg0){
                    super.updateSelected(arg0);
                    if(isSelected()){
                        this.setTextFill(Color.AQUA);
                    }
                }

            };
        }
    };

I don't know which method i need to Override =/ I tried to Override the updateSelected, but didn't worked =/

Can someone help me?

1- You are adding a mouse event handler on TableCell instance and that event is firing when you click on it. However the table cell is still not being selected. Instead the table row cell selection is being fired. To enable cell selection do:

table.getSelectionModel().setCellSelectionEnabled(true);

2- No need to override updateSelected() to manage style, instead use CSS selectors from caspian.css:

.table-cell:selected {
    -fx-background-color: lightgreen;
    -fx-text-fill: green;
}

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