1
\$\begingroup\$

The goal of this code is to move some JLabels from (JLabel[] pileone) off a JFrame when a button in JButton[] bpile1 (array of JButtons) is pressed and then disable the buttons that are at an index larger than the amount of JLabels on the screen, so that each clickable JButton has a Label it removes.

I am only allowed to use the very basic code that I have been taught in class (i.e. if statements (as below), loops (for, do, while), arrays, graphical objects, basic math commands).

public class pile1Listener implements ActionListener { // Event Handler
public void actionPerformed(ActionEvent e) {
    for (int i = 0; i < 3; i++) {
        if (e.getSource() == bpile1[i]) {
            for (int c = i; c > -1; c--) {
                pileone[pileoneno - c].setLocation(-100, -100);
            }
            pileoneno = pileoneno - (i + 1);
            total = total - (i + 1);
        }
        for (int x = 2; x > pileoneno; x--) {
            bpile1[x].setEnabled(false);
        }
    }
    changeturn();
    definewinner();
}
}

I want to make it more compact as there are two more ActionListeners, as seen below, which are essentially the same but there are different variables in place:

public class pile2Listener implements ActionListener { // Event Handler
public void actionPerformed(ActionEvent e) {
    for (int i = 0; i < 8; i++) {
        if (e.getSource() == bpile2[i]) {
            for (int c = (i); c > -1; c--) {
                piletwo[piletwono - c].setLocation(-100, -100);
            }
            piletwono = piletwono - (i + 1);
            total = total - (i + 1);
        }
        for (int x = 7; x > piletwono; x--) {
            bpile2[x].setEnabled(false);
        }
    }
    changeturn();
    definewinner();
}
}

Here is the other:

public class pile3Listener implements ActionListener { // Event Handler
public void actionPerformed(ActionEvent e) {
    for (int i = 0; i < 5; i++) {
        if (e.getSource() == bpile3[i]) {
            for (int c = (i); c > -1; c--) {
                pilethr[pilethrno - c].setLocation(-100, -100);
            }
            pilethrno = pilethrno - (i + 1);
            total = total - (i + 1);
        }
        for (int x = 4; x > pilethrno; x--) {
            bpile3[x].setEnabled(false);
        }
    }
    changeturn();
    definewinner();
}
}

I want to minimize duplication of code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.