Sunday, May 25, 2008

Layout management, how simple can it be?

Trying to teach Java to a 14 year old, and after working on some problems such as: Solving a quadratric equation, checking if a number is prime, we have so far changed the data inside the program, recompiled it and ran again....
We are reaching the point where we want to be able to enter the data in a fashionable way! Meaning time to address the "GUI" problem. While it is straightforward to create a frame and add components to it, it is tricky to layout the components inside the frame.
Here are some examples using the layout manager as little as possible (I am keeping this subject for way later...).
In the first example, we simply add some components to the panel used by the frame (FlowLayout is used by default)
In the second example, we use the GridLayout class to order the components.
In the third example, the components in a row are first added to a panel which is then added to the overall panel.

import javax.swing.*;

public class Test {

public static void main(String[] args) {
JFrame frame = new JFrame();

JPanel panel = new JPanel();

JLabel l = new JLabel("label:");
JTextField f = new JTextField(10);
JButton b = new JButton("Calc");

panel.add(l);
panel.add(f);
panel.add(b);

frame.getContentPane().add(panel);

frame.setSize(300, 300);
frame.setVisible(true);

}

}


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

public class Test2 {

public static void main(String[] args) {
JFrame frame = new JFrame();

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4,2));

JLabel l1 = new JLabel("label:");
JTextField f1 = new JTextField(10);
panel.add(l1);
panel.add(f1);

JLabel l2 = new JLabel("label:");
JTextField f2 = new JTextField(10);
panel.add(l2);
panel.add(f2);

JLabel l3 = new JLabel("label:");
JTextField f3 = new JTextField(10);
panel.add(l3);
panel.add(f3);

JButton b = new JButton("Calc");
panel.add(b);

frame.getContentPane().add(panel);

frame.setSize(300, 300);
frame.setVisible(true);

}

}


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

public class Test3 {

public static void main(String[] args) {
JFrame frame = new JFrame();

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4,1));

JLabel l1 = new JLabel("label:");
JTextField f1 = new JTextField(10);
JPanel panel1 = new JPanel();
panel1.add(l1);
panel1.add(f1);
panel.add(panel1);

JLabel l2 = new JLabel("label:");
JTextField f2 = new JTextField(10);
JPanel panel2 = new JPanel();
panel2.add(l2);
panel2.add(f2);
panel.add(panel2);

JLabel l3 = new JLabel("label:");
JTextField f3 = new JTextField(10);
JPanel panel3 = new JPanel();
panel3.add(l3);
panel3.add(f3);
panel.add(panel3);

JButton b = new JButton("Calc");
JPanel panel4 = new JPanel();
panel4.add(b);
panel.add(panel4);

frame.getContentPane().add(panel);

frame.setSize(300, 300);
frame.setVisible(true);

}

}

by Pascal Ledru

0 comments: