Question

I'm now implementing a tray game, in which i use some JButton to represent the tray. But the tray makes 7x7, so to implement the action listener it's not so fun. I have a code like this now :

public void actionPerformed(ActionEvent ae) 
    {
        if (ae.getSource() == Bouton11)
            {
                this.PosePion(1, 1, Bouton11);
            }
            else if (ae.getSource() == Bouton21)
            {
                this.PosePion(2, 1, Bouton21);
            }
            else if (ae.getSource() == Bouton31)
            {
                this.PosePion(3, 1, Bouton31);
            }
            ......
    }

How can i reduce this sort of code please ? :/

Thank you :)

Was it helpful?

Solution

Make your own listener type. Your type should implement ActionListener (and thus the actionPerformed method), and be constructed with three parameters: the button and the two integers. The reason why you need these three parameters is so that you can pass them to the PosePion method (which should be capitalized posePion, by the way).

For example:

class PoseActionListener implements ActionListener {

    private JButton button;
    private int a, b;

    public PoseActionListener(JButton btn, int a, int b) {
        this.button = btn;
        this.a = a;
        this.b = b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        posePion(a, b, btn);
    }
}

Then:

button11.addActionListener(new PoseActionListener(button11, 1, 1);
button12.addActionListener(new PoseActionListener(button12, 1, 2);

Or, even better, create all buttons at once:

for (int i=1; i<=7; i++) {
    for (int j=1; j<=7; j++) {
        JButton btn = new JButton("Button " + i + ", " + j);
        // store the button in an array if you want
        btn.addActionListener(new PoseActionListener(btn, i, j);
    }
}

OTHER TIPS

Place your JButtons in a 2D, 7x7 array when they are created.

Then in the listener method, loop through the array to determine which JButton was clicked. Your looping indexes will help you determine what to pass to PosePion.

I would suggest that you learn the Sun Java coding conventions. Your code is hard to read.

I would consider having an individual ActionListener for each instance rather than one for all.

I'd also recommend a data structure and Command implementation to cut down on the mindless repetition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top