"Global" Variables and References
"Global" Variables and References
1
Layout Management
• Layout managers
– Provided for arranging GUI components
– Provide basic layout capabilities
– Processes layout details
– Programmer can concentrate on basic “look and feel”
– Interface LayoutManager
• Using panels
• Examples
2
Layout managers.
3
FlowLayout
• FlowLayout
– Most basic layout manager
– GUI components placed in container from left to right
– Layout changes when the user modifies the dimensions of
the window
– Not accepted in practical applications containing more than
one GUI component
4
1 // FlowLayoutDemo.java
2 // Demonstrating FlowLayout alignments.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class FlowLayoutDemo extends JFrame {
12 private JButton leftButton, centerButton, rightButton;
13 private Container container;
14 private FlowLayout layout;
15
16 // set up GUI and register button listeners
17 public FlowLayoutDemo()
18 {
19 super( "FlowLayout Demo" );
20
21 layout = new FlowLayout();
22
23 // get content pane and set its layout Set layout as FlowLayout
24 container = getContentPane();
25 container.setLayout( layout );
26
27 // set up leftButton and register listener
28 leftButton = new JButton( "Left" );
29
30 leftButton.addActionListener(
31
32 // anonymous inner class
33 new ActionListener() {
34
35 // process leftButton event
Continue..
36 public void actionPerformed( ActionEvent event )
37 {
38 layout.setAlignment( FlowLayout.LEFT );
39
40 // re-align attached components
41 layout.layoutContainer( container ); When user presses
42 } left JButton, left
43 align components
44 } // end anonymous inner class
45
46 ); // end call to addActionListener
47
48 container.add( leftButton );
49
50 // set up centerButton and register listener
51 centerButton = new JButton( "Center" );
52
53 centerButton.addActionListener(
54
55 // anonymous inner class
56 new ActionListener() {
57
58 // process centerButton event
59 public void actionPerformed( ActionEvent event ) When user presses
60 { center JButton,
61 layout.setAlignment( FlowLayout.CENTER );
62 center components
63 // re-align attached components
64 layout.layoutContainer( container );
65 }
66 }
67 );
68
69 container.add( centerButton );
70
Continue..
71 // set up rightButton and register listener
72 rightButton = new JButton( "Right" );
73
74 rightButton.addActionListener(
75
76 // anonymous inner class
77 new ActionListener() {
78
79 // process rightButton event
80 public void actionPerformed( ActionEvent event ) When user presses
81 {
82 layout.setAlignment( FlowLayout.RIGHT ); right JButton,
83 right components
84 // re-align attached components
85 layout.layoutContainer( container );
86 }
87 }
88 );
89
90 container.add( rightButton );
91
92 setSize( 300, 75 );
93 setVisible( true );
94 }
95
96 // execute application
97 public static void main( String args[] )
98 {
99 FlowLayoutDemo application = new FlowLayoutDemo();
100
101 application.setDefaultCloseOperation(
102 JFrame.EXIT_ON_CLOSE );
103 }
104
105 } // end class FlowLayoutDemo
FlowLayoutDemo.java
BorderLayout
• BorderLayout
– Arranges components into five regions
• NORTH (top of container)
• SOUTH (bottom of container)
• EAST (left of container)
• WEST (right of container)
• CENTER (center of container)
9
1 // BorderLayoutDemo.java
2 // Demonstrating BorderLayout.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class BorderLayoutDemo extends JFrame
12 implements ActionListener {
13
14 private JButton buttons[];
15 private String names[] = { "Hide North", "Hide South",
16 "Hide East", "Hide West", "Hide Center" };
17 private BorderLayout layout;
18
19 // set up GUI and event handling
20 public BorderLayoutDemo()
21 {
22 super( "BorderLayout Demo" );
23
24 layout = new BorderLayout( 5, 5 );
25
26 // get content pane and set its layout
27 Container container = getContentPane(); Set layout as BorderLayout with
28 container.setLayout( layout ); 5-pixel horizontal and vertical gaps
29
30 // instantiate button objects
31 buttons = new JButton[ names.length ];
33 for ( int count = 0; count < names.length; count++ ) {
34 buttons[ count ] = new JButton( names[ count ] );
35 buttons[ count ].addActionListener( this );
}
Continue..
// Create instances of inner classes for event handling public static void main( String args[] ) {
// the event listeners Test application = new Test();
TextFieldHandler h1 = new TextFieldHandler (); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Registers the event listeners with the event sources
t1.addActionListener( h1 ); } // end class Test
t2.addActionListener( h1 );
p1.addActionListener( h1 );
GridLayout
• GridLayout
– Divides container into a grid of specified rows and columns
– Components are added starting at top-left cell
• Proceed left-to-fight until row is full
– In GridLayout the size of all GUI components becomes
equal !
15
Grid Layout
Components are placed in boxes in a simple table
arrangement. You must specify the size (rows and
columns) of the grid.
Then add components which will be placed from the
upper left, across, then down.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9);
buttonPanel.add(button4);
...
public static void main( String args[] ) { Sum2 app = new Sum2();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
public Sum2(){
Container c=getContentPane();
c.setLayout(new GridLayout(2,2));
t1=new JTextField(10); c.add(t1);
t2=new JTextField(10); c.add(t2);
t3=new JTextField(10); c.add(t3);
b=new JButton("Calculate the sum"); c.add(b);
b.addActionListener(this);
setSize(275,100); setVisible(true);
}
public void actionPerformed(ActionEvent e){
String s1=t1.getText();
double i1=Double.parseDouble(s1);
String s2=t2.getText();
double i2=Double.parseDouble(s2);
t3.setText("sum="+(i1+i2));
}
}
17
Panels
• Panel
– Helps organize components
– Class JPanel is a JComponent subclass
– May have components (and other panels) added to them
– This is the solution to add several GUI components to one
cardinal point.
– The next example PanetDemo.java illustrates how to put a
row of 5 buttons to the SOUTH of the container
18
1 // PanelDemo.java
2 // Using a JPanel to help lay out components.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class PanelDemo extends JFrame {
12 private JPanel buttonPanel;
13 private JButton buttons[];
14
15 // set up GUI
16 public PanelDemo()
17 {
18 super( "Panel Demo" );
19
20 // get content pane
21 Container container = getContentPane();
22
23 // create buttons array
24 buttons = new JButton[ 5 ];
25
26 // set up panel and set its layout
27 buttonPanel = new JPanel(); Create JPanel to hold JButtons
28 buttonPanel.setLayout(
29 new GridLayout( 1, buttons.length ) );
30
31 // create and add buttons
32 for ( int count = 0; count < buttons.length; count++ ) {
33 buttons[ count ] =
34 new JButton( "Button " + ( count + 1 ) );
35 buttonPanel.add( buttons[ count ] ); Add JButtons to JPanel
36 }
37
38 container.add( buttonPanel, BorderLayout.SOUTH );
39
40 setSize( 425, 150 );
41 setVisible( true ); Add JPanel to SOUTH
42 } region of Container
43
44 // execute application
45 public static void main( String args[] )
46 {
47 PanelDemo application = new PanelDemo();
48
49 application.setDefaultCloseOperation(
50 JFrame.EXIT_ON_CLOSE );
51 }
52
53 } // end class PanelDemo
CardLayout
• CardLayout
– Has the concept of deck of Cards
– Each card can have totally different layout
– Various buttons are used to navigate between cards
Programs:
- CardDeck.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public CardDeck() {
super( "CardLayout " );
Container container = getContentPane();
// create the JPanel with CardLayout
deck = new JPanel();
cardManager = new CardLayout();
deck.setLayout( cardManager );
// add cards to JPanel deck
deck.add( card1Panel(), "c1" );
deck.add( card2Panel(), "c2" );
deck.add( card3Panel(), "c3" );
// create and layout buttons that will control deck
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout( 2, 2 ) );
controls = new JButton[ names.length ];
for ( int count = 0; count < controls.length; count++ ) {
controls[ count ] = new JButton( names[ count ] );
controls[ count ].addActionListener( this );
buttons.add( controls[ count ] );
}
// add JPanel deck and JPanel buttons to the applet
container.add( buttons, BorderLayout.WEST );
container.add( deck, BorderLayout.EAST );
setSize( 450, 200 );
setVisible( true );
} // end constructor
Continue..
public JPanel card1Panel(){
JLabel label1 = new JLabel( "card one", SwingConstants.CENTER );
JPanel card1 = new JPanel(); card1.add( label1 ); return card1;
}
public JPanel card2Panel(){
JLabel label2 = new JLabel( "card two", SwingConstants.CENTER );
JPanel card2 = new JPanel(); card2.setBackground( Color.yellow );
card2.add( label2 ); return card2;
}
public JPanel card3Panel(){
JLabel label3 = new JLabel( "card three" );
JPanel card3 = new JPanel();
card3.setLayout( new BorderLayout() );
card3.add( new JButton( "North" ), BorderLayout.NORTH);
card3.add( new JButton( "West" ), BorderLayout.WEST );
card3.add( new JButton( "East" ), BorderLayout.EAST );
card3.add( new JButton( "South" ), BorderLayout.SOUTH);
card3.add( label3, BorderLayout.CENTER );
return card3;
}
// handle button events by switching cards
public void actionPerformed( ActionEvent event ) {
if ( event.getSource() == controls[ 0 ] )
cardManager.first( deck ); // show first card
else if ( event.getSource() == controls[ 1 ] )
cardManager.next( deck ); // show next card
else if ( event.getSource() == controls[ 2 ] )
cardManager.previous( deck ); // show previous card
else if ( event.getSource() == controls[ 3 ] )
cardManager.last( deck ); // show last card
}
} // end class
How can you pass info between cards ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public Game() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
text = new JTextField();
content.add(text, BorderLayout.NORTH);
centre = new JPanel(new GridLayout(6,5));
alphaButtons = new JButton[ALPHABET.length()];
for (int i = 0; i < ALPHABET.length(); i++ ){
alphaButtons[i] = new JButton(ALPHABET.charAt(i) + "");
alphaButtons[i].addActionListener(this);
centre.add(alphaButtons[i]);
}
Game Solution (II)
content.add(centre, BorderLayout.CENTER);
ok = new JButton("OK");
clear = new JButton("CLEAR");
ok.addActionListener(this);
clear.addActionListener(this);
bottom = new JPanel(new GridLayout(1,2));
bottom.add(ok);
bottom.add(clear);
content.add(bottom, BorderLayout.SOUTH);
setSize(500,400);
setVisible(true);
}
public MarksProc() {
st = new Student[20];
Container c = this.getContentPane();
JPanel p1 = new JPanel();
b1 = new JButton("Enter Student data");
b2 = new JButton("Calculate class average");
b3 = new JButton("Show student with highest mark");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
p1.setLayout(new GridLayout(3,1));
p1.add(b1); p1.add(b2); p1.add(b3);
c.add(p1, BorderLayout.WEST);
JPanel p2 = new JPanel();
JLabel l1 = new JLabel ("Enter student name");
t1 = new JTextField (10);
JLabel l2 = new JLabel ("Enter student mark");
t2 = new JTextField (10);
l3 = new JLabel();
l4 = new JLabel();
JLabel l5 = new JLabel(" ");
JLabel l6 = new JLabel(" ");
p2.setLayout(new GridLayout(4,2));
p2.add(l1); p2.add(t1); p2.add(l2); p2.add(t2); p2.add(l3);
p2.add(l5); p2.add(l4); p2.add(l6);
c.add(p2, BorderLayout.EAST);
setSize(500,400);
setVisible(true);
}
Marks Processing Solution(II)
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b1){
String name = t1.getText();
int mark = Integer.parseInt(t2.getText());
st[count++] = new Student(name, mark);
}
else if (e.getSource()==b2){
for (int j=0; j<count; j++)
sum += st[j].getMark();
l3.setText("Class average is "+sum/count);
}
else if (e.getSource()==b3){
for (int j=0; j<count; j++)
if (st[j].getMark()>oldmark) {
oldmark=st[j].getMark();
best = st[j].getName();
}
l4.setText("Best student is "+best);
} // end of last else/if
} // end of actionPerformed
class Student{
private String name;
private int mark;
• Write the Java frame and the class Student for the
marks processing of a number of students.
• The user starts by entering the name and mark in two
textfields provided by the applet and he clicks on the
button “Enter student data”. This will create a new
object of Student type which will be added to an array
of 10 Student references. The textfields, labels and
buttons are on a panel at the top of the applet.
• After finishing the data entry the user clicks on the
button “Display Students” which will display on the
text area available at the bottom of the applet all the
content of the array of students with the marks in
descending order. The content of each array element is
produced by the method toString() of the Student class.
import java.awt.*; Objects Sorting Solution
import java.awt.event.*;
import javax.swing.*;
JTextArea outputArea;
JLabel l1, l2;
JTextField t1, t2;
JButton b1, b2;
Student s, array[];
int stCount=0;
public ObjectsSort() {
outputArea = new JTextArea(10,15);
l1=new JLabel("Enter student name");
l2=new JLabel("Enter student’s mark");
t1= new JTextField(10);
t2= new JTextField(10);
JPanel p1=new JPanel();
b1= new JButton("Enter student data");
b2= new JButton("Display students");
array = new Student [10];
Container container = getContentPane();
b1.addActionListener(this);
b2.addActionListener(this);
p1.setLayout(new GridLayout( 3, 2 ) );
p1.add(l1); p1.add(t1);
p1.add(l2); p1.add(t2);
p1.add(b1); p1.add(b2);
container.add( p1, BorderLayout.NORTH);
container.add( new JScrollPane(outputArea), BorderLayout.CENTER );
setSize(500,400);
setVisible(true);
}
Objects Sorting Solution (II)
public void actionPerformed(ActionEvent e){
String s1="", s2="";
if (e.getSource()==b1){
s1=t1.getText();
s2=t2.getText();
int mark= Integer.parseInt(s2);
array[stCount++] = new Student (s1, mark);
t1.setText("");
t2.setText("");
}
else if (e.getSource()==b2) {
String output = "Student records with marks in descending order:\n";
bubbleSort( array ); // sort array
// append sorted\ array values to String output
for ( int counter = 0; counter < stCount; counter++ )
output +=array[counter].toString();
outputArea.setText( output );
}
}
class Student {
private String name;
private int mark;
public Student (String n, int m){
name=n;
mark=m;
}
public int getMark() {
return mark;
}
public String getName() {
return name;
}
public String toString() {
return name + " has " + mark + "\n";
}
}