A bad strategy is also the addButtonToFrame()
method.
It hard codes the number of buttons, their names, and everything. This way if you want to add one more button (for any reason) you have to write one more (custom) line of code to this method.
The right way here is to make an addButtonToFrame(ArrayList <Button> buttons)
method. You pass an ArrayList
of (as many as you please) buttons in this method. Then add them in the panel, given the objects have been created with Dimension parameter.
But again, this is kind of making a new layout manager, and java has some really nice layout managers. In other words you are reinventing the wheel. That is not always bad (it is a good practice), but to make a good manager you have to spend time and (as I said) there are good managers.
Example:
class ButtonExample{
ArrayList <JButton> buttons = new ArrayList<JButton>();
ActionListener beh = new ButtonEventHandler() //this is a custom class that contains actionPerformed() method
createButtons(){
for (int i = 0; i < buttons.size(); i++)
buttons.get(i) = new JButton();
}
addListeners(){
for (int i = 0; i < buttons.size(); i++)
buttons.get(i).addActionListener(beh);
}
}
The ArrayList is a kind of array without standard size. It is implemented using some nice tricks (that there is no need to know to use it) and you can access its objects with get() method (instead of [] operator like in regular arrays)
The addListeners() and createButtons() methods are dummies just to see how ArrayLists work. You can pass them as parameters in other methods the way you pass any regular object.