I have two arrays with button-objects:
this.rightButtons = new JButton[MAX_RBUTTONS];
this.wrongButtons = new JButton[MAX_WBUTTONS];
And I add properties (color, etc.) to each one of these by:
private void preferences(String buttonType, int num) {
if (buttonType.equalsIgnoreCase("right")) {
this.rightButtons[num] = new JButton("");
this.rightButtons[num].setToolTipText("gg");
this.rightButtons[num].setPreferredSize(new Dimension(40, 40));
this.rightButtons[num].setBackground(Color.LIGHT_GRAY);
this.rightButtons[num].setOpaque(true);
this.add(this.rightButtons[num]);
} else if (buttonType.equalsIgnoreCase("wrong")) {
this.wrongButtons[num] = new JButton("");
this.wrongButtons[num].setToolTipText("gg");
this.wrongButtons[num].setPreferredSize(new Dimension(40, 40));
this.wrongButtons[num].setBackground(Color.LIGHT_GRAY);
this.wrongButtons[num].setOpaque(true);
this.add(this.wrongButtons[num]);
}
As you see, they have the same properties. Is there a way to change this code to a shorter one? The only thing that changes is this.wrongButtons
and this.rightButtons
(name of array).
Yes, it's very simple - everything about the button is the same apart from where you're storing it. So create it, then store it:
private void preferences(String buttonType, int num) {
JButton button = new JButton("");
button.setToolTipText("gg");
button.setPreferredSize(new Dimension(40, 40));
button.setBackground(Color.LIGHT_GRAY)
button.setOpaque(true);
add(button);
JButton[] array = buttonType.equalsIgnoreCase("right")
? rightButtons : wrongButtons;
array[num] = button;
}
(This assumes every button type is either "right" or "wrong".)
Personally I'd advise using lists instead of arrays, by the way...
See more on this question at Stackoverflow