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


Question

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
3
8/30/2012 2:51:35 PM

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;
}
2
9/1/2012 10:23:22 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon