How to retrieve data from JButton?

Alan Robinson :

I'm looking to create JButton controls from a loop then use an event handler to pull relevant information and manipulate that further using SQL commands.

However I cannot access the component name or component text fields of the created button objects.

try {
    String SQL = "SELECT * FROM Products";
    ResultSet rs = GetDB.AccessDatabse(SQL);

    while(rs.next()){
        JButton btn = new JButton();
        btn.setText(rs.getString("ProductName"));
        btn.setName(rs.getString("ProductName"));
        System.out.println(btn.getName()); 
        btn.addActionListener(this);
        add(btn);
                    }
    }   
 catch (SQLException ex) {System.out.println("GUI Creation Error");}    
}

    @Override
    public void actionPerformed(ActionEvent ae){
        System.out.println(this.getName()); 
    }

I would expect the button name to be set to the SQL Query result, but when attempting to print the result it displays "frame0" for each button.

The Text area of each button is working

ItFreak :

You are calling getName() on this, which is not the button, it is your this-context which is your JFrame.

You need to parse the source of the ActionEvent.

Here I made some quick code which could do what you want:

actionPerformed(ActionEvent e) { 
  if(e.getSource() instanceof JButton) {
    //Casting here is safe after the if condition
    JButton b = (JButton) e.getSource();
    System.out.println(b.getText());
  } else {
    System.out.println("Something other than a JButton was clicked");
  }
}  

What I do: I check if the action source is a JButton and then cast it to a new local variable and then get the text of this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157811&siteId=1