4

I have a button on my interface that is disabled by default. I want it to become enabled when the user selects a row in my TableView and becomes disabled again when the user clicks elsewhere. What is the simplest way to do this?

UB-
  • 123
  • 3
  • 12

2 Answers2

10

Seems like a perfect place to use JavaFX Bindings:

TableView<String> tableView = new TableView<>(tableData);

TableColumn<String, String> column1 = new TableColumn<>();

Button button = new Button("Button");
button.disableProperty().bind(Bindings.isEmpty(tableView.getSelectionModel().getSelectedItems()));

This example disables the Button when the user has selected nothing or cleared his selection and becomes enabled as soon as at least one row is being selected.

eckig
  • 10,964
  • 4
  • 38
  • 52
  • It is working fine for me. Remember: This is not a focus listener. You actually have to clear the selection to disable the Button. – eckig Jan 26 '15 at 06:10
0

add a focus listener to your tableView object, and on focus set button.enable = true; on lost focus then button.enable = false;

the code will look a bit like

class myClass implements FocusListener
{
    TableView.addFocusListener(this);

    public void focusGained(FocusEvent e) {
        button.enable=true;
    }

    public void focusLost(FocusEvent e) {
        button.enable=false;
    }


}

Focus listener toturial

bakriawad
  • 345
  • 2
  • 10
  • I tried this but it won't accept .addFocusListener saying the classic "cannot find symbol". Might be worth mentioning that the tableview is not of a generic type. – UB- Jan 26 '15 at 21:15
  • Doing a bit of research I saw that javafx doesn't have a addFocusListener method. Does this have anything to do with it? – UB- Jan 26 '15 at 21:29
  • http://stackoverflow.com/questions/16549296/how-perform-task-on-javafx-textfield-at-onfocus-and-outfocus , also check the Javafx binding from the second answer – bakriawad Jan 27 '15 at 17:04