Credits

Saturday, May 14, 2011

Java's Border Layout Manager

We can practically arrange the size and placement of components on our GUI container like a frame or panel. There  are several layout managers and for content pane, the default or active layout manager is a Border Layout that makes use of  5 regions: NORTH, CENTER, SOUTH, WEST and EAST.

Border Layout Manager is quite useful if the components on certain regions have different settings or properties.

Unlike the previous sample on GUI that uses Flow Layout Manager, the  program was revised to include Border Layout and Flow Layout to arrange the components.

[+/-] show/hide


/*adding of components to frame with panels in a border layout*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GUILoginBorderLayout extends JFrame implements ActionListener{

String name;
JLabel title = new JLabel("Login Form", JLabel.CENTER);
JLabel loginLbl= new JLabel ("Login ");
JLabel pwLbl= new JLabel ("Password");
JTextField loginField=new JTextField(15);
JTextField pwField = new JTextField(15);

JButton loginBtn = new JButton("Login");
JButton cancelBtn = new JButton("Cancel");

JPanel npanel = new JPanel ();
JPanel cpanel = new JPanel ();
JPanel spanel = new JPanel ();

public GUILoginBorderLayout(){
super("Login Form");
setSize(280,180);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BorderLayout flo=new BorderLayout();
setLayout(flo);

npanel.add(title);
add(npanel,BorderLayout.NORTH);

loginBtn.addActionListener(this);
cancelBtn.addActionListener(this);

cpanel.add(loginLbl);
cpanel.add(loginField);
cpanel.add(pwLbl);
cpanel.add(pwField);

add(cpanel,BorderLayout.CENTER);

spanel.setLayout(new FlowLayout());  // to center the login and cancel button inside the panel
spanel.add(loginBtn);
spanel.add(cancelBtn);
add(spanel,BorderLayout.SOUTH);

setVisible(true);
}

public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
boolean flag = false;
name= loginField.getText();
if (source==loginBtn)
{if (loginField.getText().equals("STI") && pwField.getText().equals("STI"))
flag = true;
msgForm myMessage = new msgForm(flag,name);}

else if (source==cancelBtn)
System.exit(0);


}

public static void main (String args[]){
GUILoginBorderLayout myFrame=new GUILoginBorderLayout();
}
}


class msgForm extends JFrame {
JLabel msg = new JLabel(" ",JLabel.CENTER);


public msgForm(boolean myflag, String xname) {
setSize(200,100);

FlowLayout xflo=new FlowLayout();
if (myflag==true)
msg.setText("Welcome,"+xname);
else
msg.setText("Invalid login/password.");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
add(msg);
setVisible(true);

}
}

AddThis