user3275222
user3275222

Reputation: 223

Which Layout to use and how?

I want to design a simple form, having 5 components:

2 labels, 1 test field, 1 password text field, and 1 button. I want to have a label, and right to it the text field.

One line down (or more, a nice looking space should be seen) I want the second label, with the passwordtextfield to it's right.

In a third line below that, in the middle, I want the button.

I am trying to do this without WindowsBuilder or any assisting tool, however, I am a newbie in Java.

package HR;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;


import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JFormattedTextField;
import javax.swing.JButton;

import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SignIn extends JFrame
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public SignIn()
    {
        this.setTitle("HR SYSTEM LOGIN SCREEN");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(100, 100, 308, 179);
        JPanel contentPane = new JPanel();
        this.getContentPane().add(contentPane);

        JLabel userName = new JLabel("User Name");
        contentPane.add(userName);

        JLabel password = new JLabel("Password");
        contentPane.add(password);

        JFormattedTextField userText = new JFormattedTextField();
        contentPane.add(userText);

        JPasswordField passwordText = new JPasswordField();
        contentPane.add(passwordText);

        JButton signButton = new JButton("Sign In");
        contentPane.add(signButton);



    }

}

Upvotes: 1

Views: 1101

Answers (5)

splungebob
splungebob

Reputation: 5415

GridBagLayout does have a steeper learning curve vs. the other standard LayoutManagers, but once you get the hang of it, it's quite easy to hand-code a GUI like this in just a couple of minutes:

package swing;

import java.awt.*;
import javax.swing.*;

public class LoginWithGridBagDemo implements Runnable
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new LoginWithGridBagDemo());
  }

  public void run()
  {
    JLabel userLabel = new JLabel("User Name");
    JLabel passLabel = new JLabel("Password");
    JTextField userText = new JTextField(20);
    JPasswordField passText = new JPasswordField(20);
    JButton loginButton = new JButton("Login");

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.insets = new Insets(4,4,4,4);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.NONE;
    panel.add(userLabel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(userText, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.NONE;
    panel.add(passLabel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(passText, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridwidth = 2;
    panel.add(loginButton, gbc);

    JFrame f = new JFrame("Login");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(panel));
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

Further, anyone who uses GridBagLayout on a somewhat regular basis winds up writing helper methods/classes that can simplify the above code and make GUI generation even simpler. For those interested, here's a post that shows you what I did to make my GBL life easier.

Don't buy into the hate. It's a very powerful LayoutManager.

Upvotes: 1

rob
rob

Reputation: 6247

I would go ahead and use WindowBuilder or some other visual GUI builder for your initial layout. You can then examine the generated code and play with it to see how it works.

I haven't used GroupLayout much, but I prefer GridBagLayout. GridBag is confusing at first, but once you get the hang of it, it's not too bad. Your layouts will be easier to maintain if you use relative positioning instead of absolute.

MiGLayout is another nice layout and it's easier to pick up than GridBagLayout, but it also is not perfect (or at least, it wasn't a couple years ago when I last used it). When I've used it to lay out more complex panels by hand, it was at least as verbose as GridBagLayout.

If you want to tweak the layout by hand, WindowBuilder is actually pretty good about letting you switch between WYSIWYG editing and hand-coding. It never hurts to commit a somewhat-working version of your GUI to your repository (git, mercurial, cvs, svn, etc.) before you start tweaking it by hand, just in case so you can easily compare your modified code with the original code. (If you're not already using a version control system, start using one right now. If I had to recommend one, I'd say go with git, but any distributed version control system will be better than what you're doing right now, and one that has good integration with your IDE and/or other parts of your workflow will save you even more time and frustration.)

And keep in mind that sometimes it's useful to use nested layouts; you don't necessarily have to stick with just one.

Upvotes: 2

Anthony Accioly
Anthony Accioly

Reputation: 22461

With WindowsBuilder I would use GroupLayout (standard API), MigLayout(Third Party) or JGoodies FormLayout (Third Party). All of them are well supported and will do what you want. If you plan to do write UI code by hand (Why?) MigLayout is a good choice.

WindowsBuilder Documentation and strong points:

  • GroupLayout: Very flexible layout manager designed to be used by GUI Builders. One popular combination for swing development is Netbeans Swing GUI Builder (Matisse) and GroupLayout (but WindowsBuilder also does a fantastic Job). For a long time as a Java Developer, before WindowsBuilder Pro was acquired by Google and made free I used to keep a Netbeans Window Open just for building the UI :). The layout uses hierarchical groups plus sizing and anchoring policies, bearing large resemblance to the way things are done in Delphi.
  • MigLayout: Gone a long way since its first release. Gained momentum as "the most versatile and flexible Swing and SWT Layout Manager for Java" (quoting WindowsBuilder Documentation). It is easy to use with a GUI Builder or manually. Uses string constants or API checked constraints.
  • JGoodies FormLayout: Once was an unofficial standard for building Swing Forms. It is a flexible and precise UI Manager that can combined with JGoodies Looks for a very good cross-platform experience. It can also be used manually, but really shines when combined with Smart GUI editors like IntelliJ IDEA Swing GUI Designer (WindowsBuilder is also ok). It uses a grid layout system with string descriptions and component builders to make everything straightforward.

My personal opinion:

I'm new! I Don't know what to use: Go with GroupLayout, it is standard and will not require third part jar files. Just fight the urge to manually edit UI code (seriously!).

But I want to edit UI code by hand: Ok, go with MigLayout, good components, lot of easy to grasp string constants.

When I've opened my application in a different OS the UI wasn't rendered properly: Go with JGoodies combo and follow the development guidelines, also follow UI Builder hints to add gaps and additional empty space and constraints everywhere. It may look like a waste in your machine, but once you are dealing with a different OS running a different Desktop Environment using a different DPI for fonts, UI will still be usable because of your extra effort.

Upvotes: 3

Oliver Watkins
Oliver Watkins

Reputation: 13509

You basically have a 3 x 2 grid, and in four of those cells you are displaying something. The fifth element is stretched across two cells.

I would use Gridbaglayout to position these five elements. Through careful use of GridBaylayoutConstraints you can adjust the stretching behaviour of the components. ie. The text fields should stretch max. and the labels should have no stretching.

I would also add uniform insets to all the components as they are being added (preferably 5px in all directions).

Heres a tutorial : http://blue-walrus.com/2011/12/gridbaglayout-tutorial/

Upvotes: 1

tr4pt
tr4pt

Reputation: 317

to place all your things like you wish I would use a gridbaglayout. but that is complex and not that easy to handle, so in your case a normal gridlayout would be sufficient

http://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html

Upvotes: 0

Related Questions