oksuzlerOmer
oksuzlerOmer

Reputation: 135

Creating GUI components dynamically in java

So, we can create for example a button dynamically:

panel.add(new JButton("Button"));
validate();

But the question is, how do we make calls to those elements later? For example, how do I add an event listener to this button created above, like, 100 lines of code later?

Upvotes: 0

Views: 803

Answers (3)

Awais Syed
Awais Syed

Reputation: 51

Create a variable for your JButton:

JButton jButton = new JButton("Button");
panel.add(jButton);
validate();
/*
 *
 *
100 lines of code 
 *
 */

// add an event listener
jButton.addActionListener((ActionEvent) -> {
            // do something
        });

Upvotes: 1

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

In order to bind event listeners or other functionality into the button, you'd need to store a reference to it in a variable. So, instead of

panel.add(new JButton("Button"));

You could initialize the button with

JButton myButton = new JButton("Button");
panel.add(myButton);

and then later in your code

myButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
         // do something
     } 
});

Upvotes: 0

SleevelessJoe
SleevelessJoe

Reputation: 11

I've always created my buttons before adding to the panel like so

   private JPanel buttonPanel() { //button panel method containting 
        JPanel panel = new JPanel();
        JButton addButton = new JButton("Add");
        addButton.setToolTipText("Add Customer Data");
        JButton editButton = new JButton("Edit");
        editButton.setToolTipText("Edit selected Customer");
        JButton deleteButton = new JButton ("Delete");
        deleteButton.setToolTipText("Delete selected Customer");

        addButton.addActionListener((ActionEvent) -> {
            doAddButton();
        });
        editButton.addActionListener((ActionEvent) -> {
            doEditButton();
        });
        deleteButton.addActionListener((ActionEvent) -> {
            doDeleteButton();
        });

        panel.add(addButton);
        panel.add(editButton);
        panel.add(deleteButton);

        return panel;
    }

Allows you do something like this later on.

    private void doAddButton() { //provides action for add button
    CustomerForm customerForm = new CustomerForm(this, "Add Customer", true);
    customerForm.setLocationRelativeTo(this);
    customerForm.setVisible(true);
}

Upvotes: 1

Related Questions