JBealzy
JBealzy

Reputation: 35

(Java) Creating multiple(26) buttons with ActionListeners without repeating code

I'm creating a program with a button for each letter of the alphabet. When clicked, a word is shown in one JLabel and an image in another. The word is also stored in a list. I'm wondering if there's a way to do this without repeating a block similar to this 26 times.

    JButton btnA = new JButton("A");
        btnA.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                lblImages.setText("");
                lblImages.setIcon(newImageIcon(image);
                lblWord.setText("Apple");
                words.add(lblWord.getText());
            }
        });
    btnA.setFocusable(false);
    panel.add(btnA);

Upvotes: 1

Views: 76

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

Start by defining a reusable ActionListener. To make it easier, I'm also using a "word" delegate, which will actually perform the required functionality instead of exposing a bunch of components to the ActionListener

WordActionListener

public class WordActionListener implements ActionListener {

    private String word;
    private WordListener listener

    public WordActionListener(String work, WordListener listener) {
        this.word = word;
        this.listener = listener;
    }

    public void actionPerformed(ActionEvent e) {
        listener.addWord(word);
    }
}

WordListener

public interface WordListener {
    public void addWord(String word);
}

Implementation....

Your UI, which is been used to display the content will need to implement the WordListener interface

public class ... extends ... implements WordListener {
    //...

    public void addWord(String word) {
        lblImages.setText("");
        lblImages.setIcon(newImageIcon(image);
        lblWord.setText("Apple");
        words.add(lblWord.getText());
    }
}

When constructing your buttons, you will need a list of words...

private String[] listOfWords = String[] {"Apple", ..., "Zebra"};

Then you can just loop over them...

for (char c = 'A'; c <= 'Z'; c++) {
    JButton btn = new JButton(Character.toString(c));
    btn.addActionListener(new WordActionListener(listOfWords[c - 'A'], this);
    btn.setFocusable(false);
    panel.add(btn);
}

or some such thing

Upvotes: 2

Related Questions