HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Readable code with many components (Swing)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readablewithcomponentsswingmanycode

Problem

Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?

package newpackage.view;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class UserPanel extends JPanel{

    private JLabel idLbl;
    private JLabel nameLbl;
    private JLabel passwordLbl;
    private JRadioButton adminRad;
    private JRadioButton userRad;
    private JTextField idFld;
    private JTextField nameFld;
    private JPasswordField passwordFld;
    private JButton submitBtn;

    public UserPanel() {
        setLayout(new GridLayout(4,2));
        idLbl = new JLabel("ID");
        nameLbl = new JLabel("Name");
        passwordLbl = new JLabel("Password");
        adminRad = new JRadioButton("Admin");
        userRad = new JRadioButton("User");
        idFld = new JTextField();
        nameFld = new JTextField();
        passwordFld = new JPasswordField();
        submitBtn = new JButton("Submit");
        add(idLbl);
        add(idFld);
        add(nameLbl);
        add(nameFld);
        add(passwordLbl);
        add(passwordFld);
        add(adminRad);
        add(userRad);
        add(submitBtn);
    }
}

Solution

Try to NOT add each UI component in Class fields. Keep then local if possible, as close to usage as possible. Too much class fields does not make class easy readable - as reader think that all of them are do matter.

JLabel and other components, content(text) of which will never be changed, are good candidates to be declared as local variable or without variable at all:

add(new JLabel("text"));

Context

StackExchange Code Review Q#19401, answer score: 4

Revisions (0)

No revisions yet.