0% found this document useful (0 votes)
30 views73 pages

File IOGUI

input ouptut gui

Uploaded by

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

File IOGUI

input ouptut gui

Uploaded by

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

Chapter 12

File Input
and Output

Animated Version
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 12 - 1
Chapter 12 Objectives

• After you have read and studied this chapter, you should
be able to
– Include a JFileChooser object in your program to let the user
specify a file.
– Write bytes to a file and read them back from the file, using
FileOutputStream and FileInputStream.
– Write values of primitive data types to a file and read them back
from the file, using DataOutputStream and DataInputStream.
– Write text data to a file and read them back from the file, using
PrintWriter and BufferedReader
– Read a text file using Scanner
– Write objects to a file and read them back from the file, using
ObjectOutputStream and ObjectInputStream

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 2
The File Class
• To operate on a file, we must first create a File object (from
java.io).

Opens the file sample.dat


File inFile = new File(“sample.dat”); in the current directory.

File inFile = new File Opens the file test.dat in


(“C:/SamplePrograms/test.dat”); the directory
C:\SamplePrograms
using the generic file
separator / and providing
the full pathname.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 3
Some File Methods
To see if inFile is
if ( inFile.exists( ) ) { associated to a real file
correctly.

if ( inFile.isFile() ) { To see if inFile is


associated to a file or
not. If false, it is a
directory.

File directory = new List the name of all files


File("C:/JavaPrograms/Ch12"); in the directory
C:\JavaProjects\Ch12
String filename[] = directory.list();

for (int i = 0; i < filename.length; i++) {


System.out.println(filename[i]);
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 4
The JFileChooser Class

• A javax.swing.JFileChooser object allows the


user to select a file.

JFileChooser chooser = new JFileChooser( );

chooser.showOpenDialog(null);

To start the listing from a specific directory:


JFileChooser chooser = new JFileChooser(“C:/JavaPrograms/Ch12");

chooser.showOpenDialog(null);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 5
Getting Info from JFileChooser

int status = chooser.showOpenDialog(null);


if (status == JFileChooser.APPROVE_OPTION) {
System.out.println("Open is clicked");

} else { //== JFileChooser.CANCEL_OPTION


System.out.println("Cancel is clicked");
}

File selectedFile = chooser.getSelectedFile();

File currentDirectory = chooser.getCurrentDirectory();

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 6
Applying a File Filter

• A file filter may be used to restrict the listing in


JFileChooser to only those files/directories that
meet the designated filtering criteria.
• To apply a file, we define a subclass of the
javax.swing.filechooser.FileFilter class and
provide the accept and getDescription methods.
public boolean accept(File file)
public String getDescription( )
• See the JavaFilter class that restricts the listing to
directories and Java source files.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 7
Low-Level File I/O

• To read data from or write data to a file, we must


create one of the Java stream objects and attach it
to the file.
• A stream is a sequence of data items, usually 8-bit
bytes.
• Java has two types of streams: an input stream
and an output stream.
• An input stream has a source form which the data
items come, and an output stream has a
destination to which the data items are going.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 12 - 8
Streams for Low-Level File I/O

• FileOutputStream and FileInputStream are two


stream objects that facilitate file access.
• FileOutputStream allows us to output a sequence
of bytes; values of data type byte.
• FileInputStream allows us to read in an array of
bytes.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 9
Sample: Low-Level File Output

//set up file and stream


File outFile = new File("sample1.data");

FileOutputStream
outStream = new FileOutputStream( outFile );

//data to save
byte[] byteArray = {10, 20, 30, 40,
50, 60, 70, 80};

//write data to the stream


outStream.write( byteArray );

//output done, so close the stream


outStream.close();

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 10
Sample: Low-Level File Input

//set up file and stream


File inFile = new File("sample1.data");
FileInputStream inStream = new FileInputStream(inFile);

//set up an array to read data in


int fileSize = (int)inFile.length();
byte[] byteArray = new byte[fileSize];

//read data in and display them


inStream.read(byteArray);
for (int i = 0; i < fileSize; i++) {
System.out.println(byteArray[i]);
}

//input done, so close the stream


inStream.close();

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 11
Streams for High-Level File I/O

• FileOutputStream and DataOutputStream are


used to output primitive data values
• FileInputStream and DataInputStream are used to
input primitive data values
• To read the data back correctly, we must know the
order of the data stored and their data types

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 12
Setting up DataOutputStream
• A standard sequence to set up a DataOutputStream object:
File outFile = new File( "sample2.data" );
FileOutputStream outFileStream = new FileOutputStream(outFile);
DataOutputStream outDataStream = new DataOutputSteam(outFileStream);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 13
Sample Output

import java.io.*;
class Ch12TestDataOutputStream {
public static void main (String[] args) throws IOException {

. . . //set up outDataStream

//write values of primitive data types to the stream


outDataStream.writeInt(987654321);
outDataStream.writeLong(11111111L);
outDataStream.writeFloat(22222222F);
outDataStream.writeDouble(3333333D);
outDataStream.writeChar('A');
outDataStream.writeBoolean(true);

//output done, so close the stream


outDataStream.close();
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 14
Setting up DataInputStream
• A standard sequence to set up a DataInputStream object:
File inFile = new File( "sample2.data" );
FileOutputStream inFileStream = new FileOutputStream(inFile);
DataOutputStream inDataStream = new DataOutputSteam(inFileStream);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 15
Sample Input

import java.io.*;
class Ch12TestDataInputStream {
public static void main (String[] args) throws IOException {

. . . //set up inDataStream

//read values back from the stream and display them


System.out.println(inDataStream.readInt());
System.out.println(inDataStream.readLong());
System.out.println(inDataStream.readFloat());
System.out.println(inDataStream.readDouble());
System.out.println(inDataStream.readChar());
System.out.println(inDataStream.readBoolean());

//input done, so close the stream


inDataStream.close();
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 16
Reading Data Back in Right Order
• The order of write and read operations must match in order
to read the stored primitive data back correctly.

outStream.writeInteger(…);
outStream.writeLong(…);
outStream.writeChar(…);
outStream.writeBoolean(…);

<integer>
<long>
<char>
<boolean>

inStream.readInteger(…);
inStream.readLong(…);
inStream.readChar(…);
inStream.readBoolean(…);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 17
Textfile Input and Output

• Instead of storing primitive data values as binary


data in a file, we can convert and store them as a
string data.
– This allows us to view the file content using any text
editor
• To output data as a string to file, we use a
PrintWriter object
• To input data from a textfile, we use FileReader
and BufferedReader classes
– From Java 5.0 (SDK 1.5), we can also use the Scanner
class for inputting textfiles

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 18
Sample Textfile Output
import java.io.*;
class Ch12TestPrintWriter {
public static void main (String[] args) throws IOException {

//set up file and stream


File outFile = new File("sample3.data");
FileOutputStream outFileStream
= new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);

//write values of primitive data types to the stream


outStream.println(987654321);
outStream.println("Hello, world.");
outStream.println(true);

//output done, so close the stream


outStream.close();
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 19
Sample Textfile Input
import java.io.*;
class Ch12TestBufferedReader {

public static void main (String[] args) throws IOException {

//set up file and stream


File inFile = new File("sample3.data");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
String str;

str = bufReader.readLine();
int i = Integer.parseInt(str);

//similar process for other data types

bufReader.close();
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 20
Sample Textfile Input with Scanner
import java.io.*;

class Ch12TestScanner {

public static void main (String[] args) throws IOException {

//open the Scanner


Scanner scanner = new Scanner(new File("sample3.data"));

//get integer
int i = scanner.nextInt();

//similar process for other data types

scanner.close();
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 21
Object File I/O

• It is possible to store objects just as easily as you store


primitive data values.
• We use ObjectOutputStream and ObjectInputStream to
save to and load objects from a file.
• To save objects from a given class, the class declaration
must include the phrase implements Serializable. For
example,
class Person implements Serializable {
. . .
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 22
Saving Objects
File outFile
= new File("objects.data");
FileOutputStream outFileStream
= new FileOutputStream(outFile);
ObjectOutputStream outObjectStream
= new ObjectOutputStream(outFileStream);

Person person = new Person("Mr. Espresso", 20, 'M');


outObjectStream.writeObject( person );

account1 = new Account();


bank1 = new Bank(); Could save objects
from the different
outObjectStream.writeObject( account1 ); classes.
outObjectStream.writeObject( bank1 );

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 23
Reading Objects
File inFile
= new File("objects.data");
FileInputStream inFileStream
= new FileInputStream(inFile);
ObjectInputStream inObjectStream
= new ObjectInputStream(inFileStream);

Person person Must type cast


to the correct
= (Person) inObjectStream.readObject( );
object type.

Account account1
= (Account) inObjectStream.readObject( ); Must read in the
Bank bank1 correct order.
= (Bank) inObjectStream.readObject( );

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 24
Saving and Loading Arrays
• Instead of processing array elements individually, it is
possible to save and load the whole array at once.

Person[] people = new Person[ N ];


//assume N already has a value

//build the people array


. . .
//save the array
outObjectStream.writeObject ( people );

//read the array


Person[ ] people = (Person[]) inObjectStream.readObject( );

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 25
Chapter 14
GUI and
Event-Driven
Programming

Animated Version
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 14 - 26
Objectives
• After you have read and studied this chapter, you should
be able to
– Define a subclass of JFrame to implement a customized frame
window.
– Write event-driven programs using Java's delegation-based event
model
– Arrange GUI objects on a window using layout managers and
nested panels
– Write GUI application programs using JButton, JLabel, ImageIcon,
JTextField, JTextArea, JCheckBox, JRadioButton, JComboBox,
JList, and JSlider objects from the javax.swing package
– Write GUI application programs with menus
– Write GUI application programs that process mouse events
Graphical User Interface

• In Java, GUI-based programs are implemented by


using classes from the javax.swing and java.awt
packages.

• The Swing classes provide greater compatibility


across different operating systems. They are fully
implemented in Java, and behave the same on
different operating systems.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 28
Sample GUI Objects

• Various GUI objects from the javax.swing


package.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 29
JOptionPane

• Using the JOptionPane class is a simple way to


display the result of a computation to the user or
receive an input from the user.
• We use the showMessageDialog class method for
output.
• We use the showInputDialog class method for
input. This method returns the input as a String
value so we need to perform type conversion for
input of other data types

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 30
Using JOptionPane for Output
import javax.swing.*;
. . .

JOptionPane.showMessageDialog( null, “I Love Java” );

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 31
Using JOptionPane for Output - 2
import javax.swing.*;
. . .

JOptionPane.showMessageDialog( null, “one\ntwo\nthree” );


//place newline \n to display multiple lines of output

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 32
JOptionPane for Input
import javax.swing.*;
. . .

String inputstr =

JOptionPane.showInputDialog( null, “What is your name?” );

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 33
Subclassing JFrame

• To create a customized frame window, we define


a subclass of the JFrame class.

• The JFrame class contains functionalities to


support features found in any frame window.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 34
Creating a Plain JFrame

import javax.swing.*;
class Ch7DefaultJFrame {
public static void main( String[] args ) {
JFrame defaultJFrame;
defaultJFrame = new JFrame();
defaultJFrame.setVisible(true);
}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 35
Creating a Subclass of JFrame

• To define a subclass of another class, we declare


the subclass with the reserved word extends.

import javax.swing.*;

class Ch7JFrameSubclass1 extends JFrame {


. . .
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 36
Customizing Ch14JFrameSubclass1

• An instance of Ch14JFrameSubclass1 will have the


following default characteristics:
– The title is set to My First Subclass.
– The program terminates when the close box is clicked.
– The size of the frame is 300 pixels wide by 200 pixels high.
– The frame is positioned at screen coordinate (150, 250).
• These properties are set inside the default
constructor.

Source File: Ch14JFrameSubclass1.java


Displaying Ch14JFrameSubclass1

• Here's how a Ch14JFrameSubclass1 frame


window will appear on the screen.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 38
The Content Pane of a Frame

• The content pane is where we put GUI objects


such as buttons, labels, scroll bars, and others.
• We access the content pane by calling the frame’s
getContentPane method.

This gray area is the


content pane of this
frame.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 39
Changing the Background Color

• Here's how we can change the background color


of a content pane to blue:
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLUE);

Source File:
Ch14JFrameSubclass2
.java

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 40
Placing GUI Objects on a Frame

• There are two ways to put GUI objects on the


content pane of a frame:
– Use a layout manager
• FlowLayout
• BorderLayout
• GridLayout
– Use absolute positioning
• null layout manager

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 41
Placing a Button
• A JButton object a GUI component that represents
a pushbutton.
• Here's an example of how we place a button with
FlowLayout.

contentPane.setLayout(
new FlowLayout());
okButton
= new JButton("OK");
cancelButton
= new JButton("CANCEL");
contentPane.add(okButton);
contentPane.add(cancelButton);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 42
Event Handling

• An action involving a GUI object, such as clicking


a button, is called an event.
• The mechanism to process events is called event
handling.
• The event-handling model of Java is based on the
concept known as the delegation-based event
model.
• With this model, event handling is implemented by
two types of objects:
– event source objects
– event listener objects

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 43
Event Source Objects

• An event source is a GUI object where an event


occurs. We say an event source generates events.
• Buttons, text boxes, list boxes, and menus are
common event sources in GUI-based applications.
• Although possible, we do not, under normal
circumstances, define our own event sources
when writing GUI-based applications.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 44
Event Listener Objects

• An event listener object is an object that includes a


method that gets executed in response to the
generated events.
• A listener must be associated, or registered, to a
source, so it can be notified when the source
generates events.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 45
Connecting Source and Listener

event source event listener

notify
JButton Handler

register

A listener must be registered to a event source. Once


registered, it will get notified when the event source
generates events.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 46
Event Types

• Registration and notification are specific to event types


• Mouse listener handles mouse events
• Item listener handles item selection events
• and so forth
• Among the different types of events, the action event is the
most common.
– Clicking on a button generates an action event
– Selecting a menu item generates an action event
– and so forth
• Action events are generated by action event sources and
handled by action event listeners.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 47
Handling Action Events

action event action event


source
actionPerformed
listener
JButton Button
Handler

addActionListener
JButton button = new JButton("OK");
ButtonHandler handler = new ButtonHandler( );

button.addActionListener(handler);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 48
ActionListener Interface

• When we call the addActionListener method of an event


source, we must pass an instance of a class that
implements the ActionListener interface.
• The ActionListener interface includes one method named
actionPerformed.
• A class that implements the ActionListener interface must
therefore provide the method body of actionPerformed.
• Since actionPerformed is the method that will be called
when an action event is generated, this is the place where
we put a code we want to be executed in response to the
generated events.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 49
The ButtonHandler Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ButtonHandler implements ActionListener {


. . .
public void actionPerformed(ActionEvent event) {
JButton clickedButton = (JButton) event.getSource();

JRootPane rootPane = clickedButton.getRootPane( );


Frame frame = (JFrame) rootPane.getParent();

frame.setTitle("You clicked " + clickedButton.getText());


}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 50
Container as Event Listener

• Instead of defining a separate event listener such


as ButtonHandler, it is much more common to
have an object that contains the event sources be
a listener.
– Example: We make this frame a listener of the action
events of the buttons it contains.
event listener
event source

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 51
Ch14JButtonFrameHandler

. . .
class Ch14JButtonFrameHandler extends JFrame
implements ActionListener {
. . .
public void actionPerformed(ActionEvent event) {
JButton clickedButton
= (JButton) event.getSource();

String buttonText = clickedButton.getText();

setTitle("You clicked " + buttonText);


}
}

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 52
GUI Classes for Handling Text

• The Swing GUI classes JLabel, JTextField, and


JTextArea deal with text.
• A JLabel object displays uneditable text (or image).
• A JTextField object allows the user to enter a single line of
text.
• A JTextArea object allows the user to enter multiple lines
of text. It can also be used for displaying multiple lines of
uneditable text.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 53
JTextField

• We use a JTextField object to accept a single line


to text from a user. An action event is generated
when the user presses the ENTER key.
• The getText method of JTextField is used to
retrieve the text that the user entered.

JTextField input = new JTextField( );


input.addActionListener(eventListener);
contentPane.add(input);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 54
JLabel

• We use a JLabel object to display a label.


• A label can be a text or an image.
• When creating an image label, we pass ImageIcon
object instead of a string.
JLabel textLabel = new JLabel("Please enter your name");
contentPane.add(textLabel);

JLabel imgLabel = new JLabel(new ImageIcon("cat.gif"));


contentPane.add(imgLabel);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 55
Ch14TextFrame2

JLabel
(with a text)
JLabel
(with an image)

JTextField

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 56
JTextArea
• We use a JTextArea object to display or allow the user to
enter multiple lines of text.
• The setText method assigns the text to a JTextArea,
replacing the current content.
• The append method appends the text to the current text.
JTextArea textArea
= new JTextArea( ); Hello
the lost world
. . .
textArea.setText("Hello\n");
textArea.append("the lost ");
textArea.append("world");
JTextArea

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 57
Ch14TextFrame3

• The state of a Ch14TextFrame3 window after six


words are entered.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 58
Adding Scroll Bars to JTextArea

• By default a JTextArea does not have any scroll


bars. To add scroll bars, we place a JTextArea in
a JScrollPane object.

JTextArea textArea = new JTextArea();


. . .
JScrollPane scrollText = new JScrollPane(textArea);
. . .
contentPane.add(scrollText);

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 59
Ch14TextFrame3 with Scroll Bars
• A sample Ch14TextFrame3 window when a
JScrollPane is used.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 60
Layout Managers

• The layout manager determines how the GUI


components are added to the container (such as
the content pane of a frame)
• Among the many different layout managers, the
common ones are
– FlowLayout (see Ch14FlowLayoutSample.java)
– BorderLayout (see Ch14BorderLayoutSample.java)
– GridLayout (see Ch14GridLayoutSample.java)

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 61
FlowLayout

• In using this layout, GUI components are placed in


left-to-right order.
– When the component does not fit on the same line, left-
to-right placement continues on the next line.
• As a default, components on each line are
centered.
• When the frame containing the component is
resized, the placement of components is adjusted
accordingly.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 62
FlowLayout Sample

This shows
the placement
of five buttons
by using
FlowLayout.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 63
BorderLayout

• This layout manager divides the container into five


regions: center, north, south, east, and west.
• The north and south regions expand or shrink in
height only
• The east and west regions expand or shrink in
width only
• The center region expands or shrinks on both
height and width.
• Not all regions have to be occupied.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 64
BorderLayout Sample

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 65
GridLayout

• This layout manager places GUI components on


equal-size N by M grids.
• Components are placed in top-to-bottom, left-to-
right order.
• The number of rows and columns remains the
same after the frame is resized, but the width and
height of each region will change.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 66
GridLayout Sample

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 67
Other Common GUI Components

• JCheckBox
– see Ch14JCheckBoxSample1.java and
Ch14JCheckBoxSample2.java
• JRadioButton
– see Ch14JRadioButtonSample.java
• JComboBox
– see Ch14JComboBoxSample.java
• JList
– see Ch14JListSample.java
• JSlider
– see Ch14JSliderSample.java

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 68
Menus

• The javax.swing package contains three menu-related


classes: JMenuBar, JMenu, and JMenuItem.
• JMenuBar is a bar where the menus are placed. There is
one menu bar per frame.
• JMenu (such as File or Edit) is a group of menu choices.
JMenuBar may include many JMenu objects.
• JMenuItem (such as Copy, Cut, or Paste) is an individual
menu choice in a JMenu object.
• Only the JMenuItem objects generate events.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 69
Menu Components
Edit View Help

JMenuBar File Edit View Help

JMenu
JMenuItem

separator

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 70
Sequence for Creating Menus

1. Create a JMenuBar object and attach it to a


frame.
2. Create a JMenu object.
3. Create JMenuItem objects and add them to the
JMenu object.
4. Attach the JMenu object to the JMenuBar object.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 14 - 71
Handling Mouse Events

• Mouse events include such user interactions as


– moving the mouse
– dragging the mouse (moving the mouse while the mouse button is
being pressed)
– clicking the mouse buttons.
• The MouseListener interface handles mouse button
– mouseClicked, mouseEntered, mouseExited, mousePressed, and
mouseReleased
• The MouseMotionListener interface handles mouse
movement
– mouseDragged and mouseMoved.
• See Ch14TrackMouseFrame and Ch14SketchPad
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. Chapter 14 - 72
Assignment # 5

• Create a word processing software like MS-Word


that can create a new file, open the existing file
and atleast 10 other features available in the MS-
Word using the Swings class.
– A nice and clean GUI interface for the software
– Back-end logic for added features.
– Implement the Exception Handling specially for opening
the files.

©The McGraw-Hill Companies, Inc. Permission


required for reproduction or display. Chapter 12 - 73

You might also like