3

I'm a newbie in Java/JavaFX (I began yesterday evening). I'm building a dynamic GUI (crud) reading off a MySQL database.

  • I managed to display the data in a table and add a button next to each row.
  • Since the number of buttons is variable, I want to define only a common eventhandler.

The problem is that whenever I use event.getSource() (it's an ActionEvent) and display it, I get something like "Button[id=0, styleClass=button].

Question 1: Is there any way I could put the id in a variable? I can't get it out of the object.

As far as I know, I have to use the id, since I can't do something like this "if(event.getSource() == somebutton) {...}" since every generated button had the same variable name.

Now, this is the loop (inside a method called make_buttons) that builds the buttons. n_buttons is the number of buttons I want to build.

for(int counter = 0; counter < n_buttons; counter++){
        String newtext = new String("btn"+counter);
        Button btn = new Button();
        btn.setText(newtext);
        btn.setId(Integer.toString(counter));
        btn.setOnAction(myHandler);
        grid.add(btn,0,counter);
    }

Note that I'm placing the buttons on a gridpane one on top of the other.

Before that part I have my handler:

    final EventHandler<ActionEvent> myHandler = new EventHandler<ActionEvent>(){

    public void handle(final ActionEvent event) {
        Object new_output = event.getSource();
        System.out.println(new_output);
        event.consume();
        }
    };

Question 2: so, how can I differentiate which button fired the event in my particular case?

I know quite a few programming languages (Matlab, R, Python, C, Assembly, etc... but I'm a hobbyist), but it's the first time I'm working with GUI elements (except web languages and ActionScript 3). In actionscript I could just do something like event.getCurrentTarget and the use it exactly as if it were the object itself to read the id, properties, etc.

I looked everywhere and couldn't find anything (maybe my terminology was a bit approximative...).

1 Answer 1

6

If I understand your question correcty, you can simply access the clicked button in you handle method with the following code:

Object source = event.getSource();
if (source instanceof Button) { //should always be true in your example
    Button clickedBtn = (Button) source; // that's the button that was clicked
    System.out.println(clickedBtn.getId()); // prints the id of the button
}
Sign up to request clarification or add additional context in comments.

1 Comment

You got it!!! I tried to cast it too, but without the parentheses... Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.