Using Java's Swing, you'll often have to wrap elements in others to achieve the desired layout. These panel's elements does however need to be accessable by the super-panel (further called view), upon for example, form-submission.
Consider the following (simplified) example:
class AddUserView extends JPanel {
private JPanel elementWrapper = new JPanel();
private JPanel buttonWrapper = new JPanel();
private JTextField userNameField = new JTextField();
private JButton submitButton = new JButton("Submit");
public AddUserView() {
// .. add elements to the wrappers
elementWrapper.add(userNameField);
buttonWrapper.add(submitButton);
// .. add listeners etc
// Add the wrappers to the view
add(elementWrapper);
add(buttonWrapper);
}
}
This obviously works, however I believe that this is an ugly solution since now the view
owns all the elements, instead of the wrappers - which I find more appropriate. More on, now all (i.e) GridBagConstraints
has to be placed in the view.
One solution could of course be to place all the elements in the appropriate wrappers class, and then make it either public
+ final
, or create a bazillion getters & setters
.
However, I'm sure there is a more pretty OOP way to achieve this?