04 July 2014

Layout mangers

Layout mangers
Layout manager is used to layout (or arrange) the GUI components inside a container.There are many layout managers , but the most frequently used are-
BorderLayout

A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is the default layout manager for every JFrame

java-border-layout-manager

FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row one after the other.

java-flow-layout-manager

GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

java-grid-bag-layout

Step 8) How about creating a chat frame like below.

java-swing-chat-frame


//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui{
public static void main(String args[]){
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
//Creating the MenuBar and adding components
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 =new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);
//Creating the panel at bottom and adding components
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10);// accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label);// Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
// Text Area at the Center
JTextArea ta = new JTextArea();
//Adding Components to the frame.
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.getContentPane().add(BorderLayout.NORTH,mb);
frame.getContentPane().add(BorderLayout.CENTER,ta);
frame.setVisible(true);
}
}

No comments:

Post a Comment