0% found this document useful (0 votes)
9 views37 pages

"Global" Variables and References

Uploaded by

prathambhambi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views37 pages

"Global" Variables and References

Uploaded by

prathambhambi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

The best program structure for the

JFrame application Test.java


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

public class Test extends JFrame implements ActionListener {


// “global” variables and references
public static void main( String args[] ) {
Test app = new Test();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public Test() {
// constructor creates objects & organizes the frame window
}
public void actionPerformed(ActionEvent e) {
// code describing the actions
}
}

1
Layout Management

• ch.20 of Horstmann, 6th edition

• 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..

38 // place buttons in BorderLayout; order not important


39 container.add( buttons[ 0 ], BorderLayout.NORTH );
40 container.add( buttons[ 1 ], BorderLayout.SOUTH );
41 container.add( buttons[ 2 ], BorderLayout.EAST );
Place JButtons in regions
42 container.add( buttons[ 3 ], BorderLayout.WEST ); specified by BorderLayout
43 container.add( buttons[ 4 ], BorderLayout.CENTER );
44
45 setSize( 300, 200 );
46 setVisible( true );
47 }
48
49 // handle button events
50 public void actionPerformed( ActionEvent event ){
52 for ( int count = 0; count < buttons.length; count++ )
53
54 if ( event.getSource() == buttons[ count ] )
55 buttons[ count ].setVisible( false );
56 else When JButtons are “invisible,”
57 buttons[ count ].setVisible( true ); they are not displayed on screen,
58
59 // re-layout the content pane and BorderLayout rearranges
60 layout.layoutContainer( getContentPane() );
61 }
62
63 // execute application
64 public static void main( String args[] ) {
66 BorderLayoutDemo application = new BorderLayoutDemo();
68 application.setDefaultCloseOperation(
69 JFrame.EXIT_ON_CLOSE );
70 }
71 } // end class BorderLayoutDemo
BorderLayoutDemo.java Output
BorderLayout Notes

• The previous example illustrates what happens if


GUI components are missing in some cardinal
points.

• A common error for the beginners is to add more


than one GUI component to a cardinal point; that
will give a compilation error. To avoid this
situation the solution is to put the GUI
components on a panel, which is then added to the
container.

• In a JFrame the default layout manager is


BorderLayout. See BLDemo.java which uses this
default layout manager.

• Test.java shows the use of BorderLayout for the


example with textfields.
13
Test.java using BorderLayout
import javax.swing.*; // For button use a no-name event listener
import java.awt.*; plainButton.addActionListener(
import java.awt.event.*; new ActionListener () {
public void actionPerformed( ActionEvent event ){
public class Test extends JFrame { JOptionPane.showMessageDialog( null,"You pressed: " +
private JLabel label; event.getActionCommand()
private JTextField t1, t2; }
private JPasswordField p1; }
private JButton plainButton; );
setSize( 275, 100 );
public Test() { setVisible( true );
super( "Testing GUI Components" ); } // end of constructor
Container container = getContentPane();
container.setLayout( new BorderLayout(5,5) ); // inner class for textfield event handling
label = new JLabel( "Testing JLabel" ); private class TextFieldHandler implements ActionListener {
label.setToolTipText( "Label with text" ); public void actionPerformed( ActionEvent event ){
container.add( label , BorderLayout.NORTH); String s = "";
t1 = new JTextField( 10 ); if (event.getSource() == t1)
t2 = new JTextField( "Enter text here" ); s = "textfield 1 has: " + event.getActionCommand() ;
container.add( t1, BorderLayout.EAST ); else if (event.getSource() == t2)
container.add( t2, BorderLayout.WEST ); s = "textfield 2 has: " + event.getActionCommand() ;
p1 = new JPasswordField( 10 ); else if (event.getSource() == p1)
container.add( p1, BorderLayout.SOUTH ); s = "password field has: " + event.getActionCommand() ;
plainButton = new JButton( "Plain Button" ); JOptionPane.showMessageDialog( null, s );
container.add( plainButton, BorderLayout.CENTER ); }
}

// 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);
...

The Grid Layout


16
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Sum2 extends JFrame implements ActionListener{


JTextField t1, t2, t3;
JButton b;

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 class CardDeck extends JFrame implements ActionListener {


private CardLayout cardManager;
private JPanel deck;
private JButton controls[];
private String names[] = { "First card", "Next card", "Previous card", "Last card" };

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 ?

• The answer is very simple – you


have to declare GLOBAL all the
variables and the GUI references
containing that information.
• In the CardDeck program these
GLOBAL variables and references
are declared immediately below
the class CardDeck declaration.
Important Note for Assignment 2

• Assignment 2 will have a class


similar to class CardDeck except
that various “card panels”
contain GUI objects with action.
• The best approach to this kind of
code is to make all GUI
references with action class
references using a single
actionPerformed() method.
Example 1 : Game

• The Window in the next slide corresponds to a guessing


game JFrame. When the user types using the letter
buttons, those letters appear in the textfield at the top of
the screen.
• If the user entered “OOP” by clicking the OK button at the
bottom of the window the text changes into “You got it!”.
• For any other text by clicking the OK button the textfield
will display “Try again”.
• The Clear button is used to clear the content of the
textfield.
Game - continue
This figure shows an applet implementation. We have
to write a frame implementation.
Game Solution

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

public class Game extends JFrame implements ActionListener {


private JPanel centre, bottom;
private JButton alphaButtons[];
private JButton ok, clear;
private JTextField text;
public final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main( String args[] ) {


Game app = new Game();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

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 void actionPerformed(ActionEvent e) {


if (e.getSource() == clear)
text.setText("");
else if (e.getSource() == ok){
if (text.getText().equals("OOP")){
text.setText("You Got It!");
}else{
text.setText("Try Again");
}
}
else {
for (int i = 0; i < ALPHABET.length() ; i++ ){
if (e.getSource() == alphaButtons[i]) {
text.setText(text.getText() + e.getActionCommand());
} // end if
} // end for
} // end else
} // end actionPerformed()

} // end class Game


Example 2: Marks Processing
• Write the Java frame and the class Student for the
marks processing of a number of students.
• The user starts by entering the results of a large number
of students into an array of 20 Student objects. The
constructor of the Student class has two parameters: the
name of the student and an integer mark.
• For each student the user enters the name and the mark
in the two textfields and then clicks on the “Enter
student data” button.
• After finishing the data entry the user clicks on the
other two buttons to produce the class average
(truncated as an integer) and the name of the student
with the highest mark. For these operations one uses the
array of Student objects and the methods getName()
and getMark() of the Student class. The results are
posted on the applet as shown on the next slide.
Marks Processing (II)
This figure shows an applet implementation. We
have to write a frame implementation.
import java.awt.*;
import java.awt.event.*; Marks
import javax.swing.*;
Processing Solution
public class MarksProc extends JFrame implements ActionListener {
JTextField t1, t2; JLabel l3, l4; JButton b1, b2, b3;
String best=""; int sum=0, count=0, oldmark=0;
Student st[];

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

public static void main( String args[] ) {


MarksProc app = new MarksProc();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end of class MarksProc

class Student{
private String name;
private int mark;

public Student (String n, int m) { name=n; mark=m; }


public String getName() { return name; }
public int getMark() { return mark; }
}
Example 3: Objects Sorting

• 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.*;

public class ObjectsSort extends JFrame implements ActionListener{

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 );
}
}

// sort elements of array with marks in descending order


public void bubbleSort( Student array2[] ) {
// loop to control number of passes
for ( int pass = 1; pass < stCount; pass++ ) {
// loop to control number of comparisons
for ( int element = 0; element < stCount - 1; element++ ) {
// compare side-by-side elements and swap them if first element is greater than second
element
if ( array2[ element ].getMark() < array2[ element + 1 ].getMark() )
swap( array2, element, element + 1 );
}
}
}
Objects Sorting Solution (III)
// swap two elements of an array.. we swap references only
public void swap( Student array3[], int first, int second ) {
Student hold; // temporary holding reference for swap
hold = array3[ first ];
array3[ first ] = array3[ second ];
array3[ second ] = hold;
}

public static void main( String args[] ) {


ObjectsSort app = new ObjectsSort();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end of class ObjectsSort

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";
}
}

You might also like