Week 9 Examples GUI - Layout - Examples
Week 9 Examples GUI - Layout - Examples
Layout Examples
Flow Layout
• Components placed from left to right in order
added
– When a row is filled, a new row is started
• Lines can be centered, left-justified or right
justified (see FlowLayout constructor)
• Add layout as below:
– JPanel p1=new JPanel();
– p1.setLayout(new FlowLayout (FlowLayout.CENTER)); //center justified
Border Layout
• Divides container in 5 portions :
– NORTH SOUTH, EAST, WEST and CENTER.
– Also called PAGE_START, PAGE_END, LINE_START, LINE_END and
CENTER.
• The center area gets as much of the available space as possible.
• The other areas expand only as much as necessary to fill all
available space
• Specify the component's location as one of the arguments to
the add method.
– JPanel p1=new JPanel();
– P1.add(anyComponent, BorderLayout.LINE_END)
GridLayout
• Components are placed in grid pattern
• Number of rows & columns specified in
constructor
• Grid is filled left-to-right, then top-to- bottom
– JPanel p1=new JPanel();int row=2,col=5;
– p1.setLayout(new GridLayout(row,col,gap,gap));
public class GridExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Demo");
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
JButton btn3 = new JButton("Button 3");
JButton btn4 = new JButton("Button 4");
JButton btn5 = new JButton("Button 5");
// create grid layout with 3 rows , 2 columns with horizontal // and vertical gap set to 10
JPanel panel = new JPanel(new GridLayout(3,2,10,10));
// add buttons to the panel
panel.add(btn1); panel.add(btn2);
panel.add(btn3); panel.add(btn4);
panel.add(btn5);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,150);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
class GridLayoutTest extends JFrame{
GridLayoutTest(){
setTitle("GridLayout Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel myPane=new JPanel();
myPane.setLayout(new GridLayout(2,1));
myPane.add(getFieldPanel());
myPane.add(getButtonPanel());
setVisible(true);
this.getContentPane().add(myPane);
this.pack();
}
public static void main(String[] a) {
new GridLayoutTest();
}
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new GridLayout(4,2));
p.setBorder(BorderFactory.createTitledBorder("Details"));
p.add(new JLabel("Name:",SwingConstants.RIGHT));
p.add(new JTextField(16));
p.add(new JLabel("System:",SwingConstants.RIGHT));
Box Layout
• BoxLayout either stacks its components on top
of each other or places them in a row
– JPanel p1=new JPanel();
– //contentpane, layout type X_AXIS or Y_AXIS
– p1.setLayout(new BoxLayout (p1,BoxLayout.Y_AXIS));
Look and Feel
• The architecture of Swing is designed with
changeable "look and feel" (L&F) of your
application's GUI
• "Look" refers to the appearance of GUI
widgets (more formally, JComponents) and
"feel" refers to the way the widgets behave.