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

Java/Swing GUI code/layout, am I doing this wrong?

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

Problem

I've never done Java GUI's before. After much trouble I've gotten my GUI to look how I want, however it feels as if my code is very inefficient, as if I'm going about this the wrong way?

//main panels
private JPanel westPanel = new JPanel(new BorderLayout());
private JPanel eastPanel = new JPanel(new BorderLayout());

//door panels
private JPanel doorsPanel = new JPanel(new BorderLayout());
private JPanel doorsGrid = new JPanel(new GridBagLayout());
private JPanel doorButtons = new JPanel(new FlowLayout());

//light panels
private JPanel lightsPanel = new JPanel(new BorderLayout());
private JPanel lightsGrid = new JPanel(new GridBagLayout());
private JPanel lightTimerGrid = new JPanel(new GridBagLayout());
private JPanel lightButtons = new JPanel(new FlowLayout());

//list panels
private JPanel listPanel = new JPanel(new BorderLayout());
private JPanel listButtons = new JPanel(new GridBagLayout());
private JLabel itemDesc = new JLabel("Item Name - Item Price");
private JLabel totalPrice = new JLabel("Total Price: ");

doorsPanel.setBorder(BorderFactory.createTitledBorder("Manage Doors: "));
doorsPanel.add(doorsGrid, BorderLayout.NORTH);
doorsPanel.add(doorButtons, BorderLayout.SOUTH);

lightsPanel.setBorder(BorderFactory.createTitledBorder("Manage Lights: "));
lightsPanel.add(lightsGrid, BorderLayout.NORTH);
lightsPanel.add(lightButtons, BorderLayout.SOUTH);
lightsPanel.add(lightTimerGrid, BorderLayout.CENTER);

listPanel.setBorder(BorderFactory.createTitledBorder("Manage Shopping List: "));
listPanel.add(listButtons, BorderLayout.EAST);

westPanel.add(doorsPanel, BorderLayout.NORTH);
westPanel.add(lightsPanel, BorderLayout.CENTER);

eastPanel.add(listPanel, BorderLayout.SOUTH);

add(westPanel, BorderLayout.WEST);
add(eastPanel, BorderLayout.EAST);

Solution

Your code seems perfectly fine!

However...

If all of this code is in the same block (e.g., a constructor or a layout builder method), I would recommend that you break up the layout code into smaller functions. That will improve readability and code structure a bit.

Also, you should definately familiarize yourself with some GUI builders for Java (in my case it was WindowBuilder for Eclipse). Writing layout code by hand can be a pain and a source of bugs that you won't be able to resolve easily.

Context

StackExchange Code Review Q#24660, answer score: 2

Revisions (0)

No revisions yet.