+ All Categories
Home > Documents > Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing...

Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing...

Date post: 17-Jan-2016
Category:
Upload: mariah-shaw
View: 218 times
Download: 0 times
Share this document with a friend
85
Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel Menus FileDialog Other Capabilities of the AWT
Transcript
Page 1: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

The Java Abstract Windowing ToolkitLayout and Layout ManagersComponentsPanelMenusFileDialogOther Capabilities of the AWT

Page 2: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 2

Graphical User InterfacesMany programs have graphical user interface (GUI)

Windows IconsMenusPointing device

Advantages of GUI programsLooks up-to-dateDesktop metaphorMost users are familiar with GUI programs

Sometimes called

the “W.I.M.P.”

interface

Page 3: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 3

Graphical User InterfacesDevelopment of GUI programs

Used to be very difficult and expensiveToday, visual development tools (like Visual Basic) make

GUI development much easier Just drag components onto the screen with mouse

Still expensive to develop cross-platform GUI appsPorting tools help a little

Java changes things Java GUI programs are source and object compatible

across platformsCan develop Java GUI programs with or without visual

development tools

Page 4: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 4

Layout and Layout ManagersTwo ways to design graphical user interface in Java

Visual development tool: drag and drop componets on the screen (like Visual Basic)•JBuilder•VisualAge for Java•Visual Café•Visual J++

Use Java’s layout managers

Page 5: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 5

Layout and Layout ManagersLayout manager

Automaticallyplacescomponents (buttons, text, ...) on the screen

Adjusts components if user resizes the window

This is the BorderLayoutlayout manager

Page 6: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 6

Layout and Layout ManagersJava’s AWT has several layout managers

predefinedFlowLayoutBorderLayoutGridLayoutGridBagLayoutothers...

Also possible to define additional layout managersDifferent layout managers place components on the

screen in different ways

Will look at thesethree in detail

Page 7: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 7

Layout and Layout ManagersFlowLayout

Simplest layout managerPuts components on window like word processor puts

words on a pageLeft-to-right, top-to-bottom

User Name: Password:

OK Cancel

User Name:

Password:

OK Cancel

Page 8: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 8

Layout and Layout ManagersFlowlayout layout manager adjusts componets

when window size changesAgain, just like a word processor

User Name: Password:

OK Cancel

User Name: Password:

OK Cancel

Page 9: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 9

Layout and Layout ManagersFrame

Window that knows how to resize itselfMoves around on the screen when draggedCan minimize, maximize

Page 10: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 10

Layout and Layout ManagersHow to use Flowlayout

Import AWT packageimport java.awt.*;

Define a new class as a subclass of Frameclass FlowLayoutExample extends Frame{ ...}

Constructor steps// Make title for framesuper("FlowLayout Example");

// Initialize layout managersetLayout(new FlowLayout(FlowLayout.CENTER));

// Put components on frameadd(new Button("Hello"));add(new Button("There"));add(new Button("How are you?"));

// Set size of frame and show itsetSize(200, 100);show();

Page 11: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 11

Layout and Layout Managers// Demonstrates how to use the FlowLayout layout manager.

import java.awt.*;

class FlowLayoutExample extends Frame{ // Constructor public FlowLayoutExample() { // Call the constructor for the Frame class with the title // for the window super("FlowLayout Example");

// Choose the layout manager and initialize it setLayout(new FlowLayout(FlowLayout.CENTER));

// Put components on the frame add(new Button("Hello")); add(new Button("There")); add(new Button("How are you?"));

// Set the size for the frame and display it setSize(200, 100); show(); }}

public class DemonstrateFlowLayout{ static public void main(String[] args) { new FlowLayoutExample(); }}

The whole

program

Page 12: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 12

Layout and Layout ManagersResizing frame rearranges components

Flowlayout layout manager arranges components like a word processor arranges words

Page 13: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 13

Layout and Layout ManagersBorderlayout

Divides frame into five areas: North, South, East, West, Center

Can put five components on frame

Page 14: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 14

Layout and Layout ManagersResizing Borderlayout frame

Height of North andSouth are fixed

Width of East andWest are fixed

Other dimensionsgrow to fill frame

Page 15: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 15

Layout and Layout ManagersBorderLayout Example

class BorderLayoutExample extends Frame{ // Constructor public BorderLayoutExample() { // Call the constructor for the Frame class with the title // for the window super("BorderLayout Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Put components on the frame add(new Button("North"), BorderLayout.NORTH); add(new Button("South"), BorderLayout.SOUTH); add(new Button("West"), BorderLayout.WEST); add(new Button("East"), BorderLayout.EAST); add(new Button("Center"), BorderLayout.CENTER);

// Set the size for the frame and display it pack(); show(); }}

Must specifylocation

pack()makesframe

small aspossible

Page 16: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 16

Layout and Layout ManagersGridLayout

Puts components into a matrix from left to right and from top to bottom

Specify size of matrix in instantiation of GridLayout object

Example: make a matrix with three rows and four columns

new GridLayout(3, 4)

Page 17: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 17

Layout and Layout ManagersResizing GridLayout frame

Page 18: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 18

Layout and Layout ManagersGridLayout example

class GridLayoutExample extends Frame{ // Constructor public GridLayoutExample() { // Call the constructor for the Frame class with the title // for the window super("GridLayout Example");

// Choose the layout manager and initialize it setLayout(new GridLayout(3, 4));

// Put components on the frame add(new Button("1")); add(new Button("2")); add(new Button("3")); add(new Button("4")); add(new Button("5")); add(new Button("6")); add(new Button("7")); add(new Button("8")); add(new Button("9")); add(new Button("0"));

// Set the size for the frame and display it pack(); show(); }}

Page 19: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 19

ComponentsComponent: controls that appear on frame

ButtonsLabelsListsText fieldsOthers

Uses of componentsDisplay information (labels)Collect information (text fields, lists)Control program (buttons, menus)

Page 20: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 20

Components: LabelLabel component: put text on frame

class LabelExample extends Frame{ // Constructor public LabelExample() { // Call the constructor for the Frame class with the title // for the window super("Label Example");

// Choose the layout manager and initialize it setLayout(new FlowLayout(FlowLayout.LEFT));

// Put components on the frame add(new Label("First name: ")); add(new TextField(10)); add(new Label("Last name: ")); add(new TextField(15)); add(new Label("Major: ")); add(new TextField("Computer Science"));

// Set the size for the frame and display it setSize(250, 150); show(); }}

Page 21: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 21

Components: ButtonButton component: give user control

Put on frame same as any other componentMust also tell program what to do when button pressed

Event-driven programmingProgram responds to events (such as button pushes)Older style: program has complete control

To connect event (button push) to actionDefine listener object, link to buttonListener object responds when button pushedSame listener object can handle several events

Listener object for button pushesMust be from class that implements ActionListenerMust have actionPerformed() method

Page 22: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 22

Components: ButtonExample with one button

Will have Listener object be the same as the frame (With larger programs, better to separate Listener from

the frame)import java.awt.*;import java.awt.event.*;

class ButtonExample extends Frame implements ActionListener{ ...}

Define the button, assign to variableButton myButton = new Button("Press Me!");

Need the variable, so can link the button to the listener in the constructor (next slide)

Necessary forbuttons

Page 23: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 23

Components: ButtonExample with one button (continued)

Constructor puts button on frame, links to listener (which is this object)

// Constructorpublic ButtonExample(){ // Call the constructor for the Frame class with the title // for the window super("Button Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Put components on the frame add(myButton, BorderLayout.CENTER);

// Register the button with its listener object myButton.addActionListener(this);

// Set the size for the frame and display it setSize(200, 100); show();}

Link button tolistener

Page 24: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 24

Components: ButtonExample with one button (continued)

Write actionPerformed() method in this classactionPerformed() responds when button pushed

// actionPerformed: Display "Button pressed" in the command when the// window user pressed the button.public void actionPerformed(ActionEvent event){ System.out.println("Button pressed");}

actionPerformed() method can do anything when button pushedOpen or close fileDisplay a messageQuit the program ...

Page 25: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 25

Components: Buttonclass ButtonExample extends Frame implements ActionListener{ Button myButton = new Button("Press Me!");

// Constructor public ButtonExample() { // Call the constructor for the Frame class with the title // for the window super("Button Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Put components on the frame add(myButton, BorderLayout.CENTER);

// Register the button with its listener object myButton.addActionListener(this);

// Set the size for the frame and display it setSize(200, 100); show(); }

// actionPerformed: Display "Button pressed" in the command // window when the user presses the button public void actionPerformed(ActionEvent event) { System.out.println("Button pressed"); }}

Button pressedButton pressedButton pressed

Page 26: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 26

Components: More than 1 ButtonWhen more than one button

Each button has its own listener, orOne listener can handle several buttons

If one listener & several buttonsListener must be able to tell which button was pressedListener can use getSource() method -- returns component

that caused the event// actionPerformed: Distinguish between yesButton and noButton, and// display a corresponding message in the command// window for eachpublic void actionPerformed(ActionEvent event){ if (event.getSource() == yesButton) { System.out.println("You pressed yes"); } else { System.out.println("You pressed no"); }}

Page 27: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 27

Components: More than 1 Button// Demonstrates one way to distinguish between two buttons in an// actionPerformed() method

import java.awt.*;import java.awt.event.*;

class TwoButtonsExample extends Frame implements ActionListener{ Button yesButton = new Button("Yes"); Button noButton = new Button("No"); Label myLabel = new Label();

// Constructor public TwoButtonsExample() { // Call the constructor for the Frame class with the title // for the window super("Two Button Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Put components on the frame add(yesButton, BorderLayout.WEST); add(noButton, BorderLayout.EAST); add(myLabel, BorderLayout.SOUTH);

// Register the buttons with the listener object yesButton.addActionListener(this); noButton.addActionListener(this);

// Set the size for the frame and display it setSize(200, 100); show(); }

Page 28: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 28

Components: More than 1 Button // actionPerformed: Distinguish between yesButton and noButton, // and display a corresponding message for each public void actionPerformed(ActionEvent event) { if (event.getSource() == yesButton) { myLabel.setText("You pressed yes"); } else { myLabel.setText("You pressed no"); } }}

public class DemonstrateTwoButtons{ static public void main(String[] args) { new TwoButtonsExample(); }}

Page 29: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 29

Components: CheckboxCheckbox good for getting yes/no responses

Often used for option dialogsExample from JBuilder

Each checkbox can be independent of others, or can be linked to others

Page 30: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 30

Components: Checkbox// Demonstration of how to use check box components.

import java.awt.*;import java.awt.event.*;

class CheckBoxExample extends Frame implements ActionListener{ Checkbox airCondCheckBox = new Checkbox("A/C"); Checkbox cruiseCheckBox = new Checkbox("Cruise"); Button costButton = new Button("Compute Cost"); Label costLabel = new Label();

// Constructor CheckBoxExample() { // Call the constructor for the Frame class with the title // for the window super("Car Cost");

// Choose the layout manager and initialize it setLayout(new GridLayout(4, 1));

// Put components on the frame add(airCondCheckBox); add(cruiseCheckBox); add(costButton); add(costLabel);

// Register the buttons with the listener object costButton.addActionListener(this);

// Set the size for the frame and display it setSize(150, 100); show(); }

Page 31: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 31

Components: Checkbox // actionPerformed: Compute the cost of the automobile based // on the options the user has selected public void actionPerformed(ActionEvent event) { double cost = 15000.0; if (cruiseCheckBox.getState()) { cost = cost + 1000.0; } if (airCondCheckBox.getState()) { cost = cost + 1500.0; } costLabel.setText("Cost: " + cost); }}

public class DemonstrateCheckBox{ static public void main(String[] args) { new CheckBoxExample(); }}

Page 32: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 32

Components: CheckboxCheckbox groups

Can make a group of checkboxes mutually exclusive

If user clicks one, the othersgo blank

Often called “radio buttons”in other developmentenvironments

To put checkbox object in checkbox groupMake a CheckBoxGroup objectUse CheckboxGroup object in Checkbox constructor

Page 33: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 33

Components: CheckboxExample

Have CheckBoxGroup paymentGroupPut cash CheckBox component into that group

Checkbox cashCheckBox = new Checkbox("Cash", false, paymentGroup);

Checkbox constructor argumentsDescriptive text string true if that checkbox should be checked by defaultCheckBoxGroup object

Page 34: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 34

Components: Checkbox// Demonstration of how to use a check box group// for mutually exclusive check box components

import java.awt.*;import java.awt.event.*;

class CheckBoxExample extends Frame implements ActionListener{ TextField amountTextField = new TextField(10); CheckboxGroup paymentGroup = new CheckboxGroup(); Checkbox cashCheckBox = new Checkbox("Cash", false, paymentGroup); Checkbox checkCheckBox = new Checkbox("Check", false, paymentGroup); Checkbox creditCardCheckBox = new Checkbox("Credit card", false, paymentGroup); Button makePaymentButton = new Button("Make payment");

Page 35: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 35

Components: Checkbox // Constructor public CheckBoxExample() { // Call the constructor for the Frame class with the title // for the window super("Payment");

// Choose the layout manager and initialize it setLayout(new GridLayout(5, 2));

// Put components on the frame add(new Label("Amount")); add(amountTextField); add(new Label("Payment type")); add(cashCheckBox); add(new Label()); add(checkCheckBox); add(new Label()); add(creditCardCheckBox); add(makePaymentButton);

// Register the button with the listener object makePaymentButton.addActionListener(this);

// Set the size for the frame and display it setSize(250, 200); show(); }

Page 36: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 36

Components: Checkbox // actionPerformed: Compute the cost of the automobile based // on the options the user has selected public void actionPerformed(ActionEvent event) { if (cashCheckBox.getState()) { System.out.println("Cash payment"); } if (checkCheckBox.getState()) { System.out.println("Check payment"); } if (creditCardCheckBox.getState()) { System.out.println("Credit card payment"); } }}

public class DemonstrateCheckBoxGroup{ static public void main(String[] args) { new CheckBoxExample(); }}

Page 37: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 37

Components: ChoiceAllows user to pick from a list that’s normally hidden

User presses arrow button to see optionsUser then clicks on desired option

Page 38: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 38

Components: Choice// Demonstration of how to use a choice component

import java.awt.*;import java.awt.event.*;class ChoiceExample extends Frame implements ActionListener{ Button submitButton = new Button("Submit"); Choice browserChoice = new Choice(); Label resultLabel = new Label();

// Constructor public ChoiceExample() { // Call the constructor for the Frame class with window title super("Choice Example");

// Choose the layout manager and initialize it setLayout(new GridLayout(1, 3));

// Add choices to the choice component browserChoice.add("Netscape"); browserChoice.add("Internet Explorer"); browserChoice.add("HotJava");

// Put components on the frame add(browserChoice); add(submitButton); add(resultLabel);

// Register the button with the listener object submitButton.addActionListener(this);

// Set the size for the frame and display it pack(); show(); }

Page 39: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 39

Components: Choice // actionPerformed: Display the selected browser name from // the choice component public void actionPerformed(ActionEvent event) { resultLabel.setText( browserChoice.getSelectedItem()); }}

public class DemonstrateChoice{ static public void main(String[] args) { new ChoiceExample(); }}

Page 40: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 40

Components: TextFieldAllows user to type one line of text

Allows user to enter anythingRetrieve text from the field with getText() method

Page 41: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 41

Components: TextField// Demonstrates the use of text field components

import java.awt.*;import java.awt.event.*;

class TextFieldExample extends Frame implements ActionListener{ TextField firstNameText = new TextField(15); TextField lastNameText = new TextField(20); TextField majorText = new TextField("CompSci");

Button submitButton = new Button("Submit"); Label resultLabel = new Label();

// Constructor public TextFieldExample() { // Call the constructor for the Frame class with window title super("TextField Example");

// Choose the layout manager and initialize it setLayout(new GridLayout(4, 2));

Page 42: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 42

Components: TextField // Put components on the frame add(new Label("First name: ")); add(firstNameText); add(new Label("Last name: ")); add(lastNameText); add(new Label("Major: ")); add(majorText); add(submitButton); add(resultLabel);

// Register the button with the listener object submitButton.addActionListener(this);

// Set the size for the frame and display it pack(); show(); }

// actionPerformed: Display the first name, last name, and name // of major from the three text field areas public void actionPerformed(ActionEvent event) { resultLabel.setText(firstNameText.getText() + " " + lastNameText.getText() + " " + majorText.getText()); }}

public class DemonstrateTextField{ static public void main(String[] args) { new TextFieldExample(); }}

Page 43: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 43

Components: TextAreaLike TextField, but allows user to type more than

one line

Page 44: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 44

Components: TextArea// Demonstration of a TextArea component

import java.awt.*;import java.awt.event.*;class TextAreaExample extends Frame implements ActionListener{ TextArea nameAndAddressTextArea = new TextArea(); Button submitButton = new Button("Submit");

// Constructor public TextAreaExample() { // Call the constructor for the Frame class with window title super("TextArea Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Put components on the frame add(new Label("Name and address"), BorderLayout.WEST); add(nameAndAddressTextArea, BorderLayout.CENTER); add(submitButton, BorderLayout.SOUTH);

Page 45: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 45

Components: TextArea // Register the button with the listener object submitButton.addActionListener(this);

// Set the size for the frame and display it pack(); show(); }

// actionPerformed: Display the contents of the TextArea // component in the command window public void actionPerformed(ActionEvent event) { System.out.println(nameAndAddressTextArea.getText()); }}

public class DemonstrateTextArea{ static public void main(String[] args) { new TextAreaExample(); }}

Page 46: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 46

Components: TextAreaTextArea methods

Method Parameters Description

append() String Append the string to the end of the text in thetext area.

getText() none Return the contents of the text area as a string.

insert() String, int Insert the string into the text in the text areastarting at the given position (position starts at 0in the text).

setText() String Change the contents of the text area to the givenstring.

replaceRange() String, int, int Replace text in the text area between the givenpositions.

Page 47: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 47

Components: TextAreaExample of using TextArea methods

Page 48: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 48

Components: TextArea// Demonstration of the append(), insert(), and// replaceRange() methods of the TextArea class.

import java.awt.*;import java.awt.event.*;import java.text.*;

class TextAreaExample2 extends Frame implements ActionListener{ TextArea aTextArea = new TextArea(); TextField someTextTextField = new TextField(30); TextField firstPositionTextField = new TextField(); TextField secondPositionTextField = new TextField(); Button insertButton = new Button("Insert"); Button appendButton = new Button("Append"); Button replaceButton = new Button("Replace"); Button exitButton = new Button("Exit");

Page 49: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 49

Components: TextArea // Constructor public TextAreaExample2() { // Call the constructor for the Frame class with the title // for the window super("TextArea Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Make a panel for data entry and buttons Panel controlPanel = new Panel(new GridLayout(5, 2));

// Put control components on the panel controlPanel.add(new Label("Text")); controlPanel.add(someTextTextField); controlPanel.add(new Label("Position 1")); controlPanel.add(firstPositionTextField); controlPanel.add(new Label("Position 2")); controlPanel.add(secondPositionTextField); controlPanel.add(insertButton); controlPanel.add(appendButton); controlPanel.add(replaceButton); controlPanel.add(exitButton);

Page 50: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 50

Components: TextArea // Put components on the frame add(aTextArea, BorderLayout.CENTER); add(controlPanel, BorderLayout.SOUTH);

// Register the buttons with the listener object insertButton.addActionListener(this); appendButton.addActionListener(this); replaceButton.addActionListener(this); exitButton.addActionListener(this);

// Set the size for the frame and display it pack(); show(); }

// actionPerformed: Handle the event for the associated button // press public void actionPerformed(ActionEvent event) { // Close the program if exitButton pressed if (event.getSource() == exitButton) { setVisible(false); dispose(); System.exit(0); }

Page 51: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 51

Components: TextArea // Replace aTextArea between the positions given in // firstPosition and secondPosition with the contents of // someTextTextField else { // Convert the number in the secondPosition text field // to an integer int secondPosition = formatter.parse( secondPositionTextField.getText()).intValue(); aTextArea.replaceRange( someTextTextField.getText(), firstPosition, secondPosition); } }

// Ignore any ParseExceptions catch (ParseException e) {} } }}

public class DemonstrateTextArea2{ static public void main(String[] args) { new TextAreaExample2(); }}

Page 52: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 52

PanelPanel

Container that can hold other compoents (including panels)

Like a miniature frame -- can put components on it, but no title or border

Can put panel on a frame, then put other components in the panel

One frame can have several panelsEach panel can have its own layout manager, which can

be different from frame’s layout manager

Page 53: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 53

PanelTwo panels on a BorderLayout frame

F ra m e isB o rd e rL a yo u t

T o p p a n e l isG r id L a yo u t

B o tto m p a n e lis F lo wL a yo u t

Page 54: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 54

Panel// Demonstration of how to use panels

import java.awt.*;

class PanelExample extends Frame{ public PanelExample() { // Constructor super("Panel Example");

// Define a panel for the South area, and add its button // components Panel buttonPanel = new Panel(new FlowLayout()); buttonPanel.add(new Button("Mail")); buttonPanel.add(new Button("News")); buttonPanel.add(new Button("WWW"));

// Define a panel for the North area, and add its label and // text field components Panel loginPanel = new Panel(new GridLayout(2, 2)); loginPanel.add(new Label("Login: ")); loginPanel.add(new TextField(15)); loginPanel.add(new Label("Password: ")); loginPanel.add(new TextField("********"));

// Choose the layout manager for the frame and initialize it setLayout(new BorderLayout());

Page 55: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 55

Panel

// Put components on the frame add(loginPanel, BorderLayout.NORTH); add(new TextArea(), BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH);

// Set the size for the frame and display it setSize(300, 300); show(); }}

public class DemonstratePanel{ static public void main(String[] args) { new PanelExample(); }}

Page 56: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 56

MenusCommon feature in most GUI programs

Program can have many commands, arranged hierarchically

Menu doesn’t take much screen space

Page 57: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 57

MenusHow to make a menu

Make a MenuBar object, add to frameMenuBar mb = new MenuBar();setMenuBar(mb);

Make top-level Menu objects, add to MenuBar objectMenu fileMenu = new Menu("File");mb.add(fileMenu);

Make MenuItem objects, add to Menu objectMenuItem openMenuItem = new MenuItem("Open");fileMenu.add(openMenuItem);

Add listener object to each MenuItem objectexitMenuItem.addActionListener(this);

Page 58: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 58

Menus// Demonstration of menus (also shows the// recommended way to exit a Java GUI application)

import java.awt.*;import java.awt.event.*;

class MenuExample extends Frame implements ActionListener{ Menu fileMenu = new Menu("File"); Menu editMenu = new Menu("Edit"); MenuItem openMenuItem = new MenuItem("Open"); MenuItem saveMenuItem = new MenuItem("Save"); MenuItem exitMenuItem = new MenuItem("Exit"); MenuItem copyMenuItem = new MenuItem("Copy"); MenuItem cutMenuItem = new MenuItem("Cut"); MenuItem pasteMenuItem = new MenuItem("Paste");

Page 59: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 59

Menus // Constructor public MenuExample() { // Call the constructor for the Frame class with the title // for the window super("Menu Example");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Define a menu bar object and add it to frame MenuBar mb = new MenuBar(); setMenuBar(mb);

// Add menus to menu bar mb.add(fileMenu); mb.add(editMenu);

// Add menu items to menus fileMenu.add(openMenuItem); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); editMenu.add(copyMenuItem); editMenu.add(cutMenuItem); editMenu.add(pasteMenuItem);

// Add listener for menu items exitMenuItem.addActionListener(this); // (add others here ...)

// Set the size for the frame and display it setSize(200, 200); show(); }

Page 60: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 60

Menus // actionPerformed: Handle events for the menu. This example // only shows how to handle the exit menu // item. Other menu items could be handled // in a similar way. public void actionPerformed(ActionEvent event) { if (event.getSource() == exitMenuItem) { setVisible(false); dispose(); System.exit(0); } }}

public class DemonstrateMenu{ static public void main(String[] args) { new MenuExample(); }}

Page 61: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 61

FileDialogUse FileDialog to open, save files

Purpose: Get file name from userWindows “Open” file dialog

Page 62: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 62

FileDialogPlatform independent

Uses native dialog for computer running programWindows “Save As” file dialog

Page 63: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 63

FileDialogHow to use FileDialog to get file name from user

Make a FileDialog objectFileDialog openDialog = new FileDialog(this, "Open", FileDialog.LOAD);

•First parameter: parent frame (waits while dialog displayed)•Second parameter: title on dialog•Third parameter: FileDialog.OPEN or FileDialog.SAVE

Display the dialog// Display the dialog and get the filename from the useropenDialog.setVisible(true);

Hide the dialog after user picks a file// Hide the dialog so it does not cover the application,// but is still available so we can get the filenameopenDialog.setVisible(false);

•Don’t delete or dispose of dialog until after getting file name

Page 64: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 64

FileDialogGet filename with getFile(), getDirectory()

// Check whether user canceled the loadif (openDialog.getFile() == null){ System.out.println("User canceled the load");}else{ // Display the full filename in the command window System.out.println("Open file " + openDialog.getDirectory() + openDialog.getFile());}

Can dispose of dialog, garbage collect it, or leave hidden// Optional stepopenDialog.dispose();

Directory and file names vary between platformsWindows: c:\My Documents\Programs\Program1.javaUnix: /usr/users/smith/programs/Program1.javaVAX: [smith.programs]Program1.java

Page 65: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 65

FileDialogExample Program

Page 66: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 66

FileDialog// Demonstrates the use of FileDialog

import java.io.*;import java.awt.*;import java.awt.event.*;

class FileDialogExample extends Frame implements ActionListener{ // Interface variables Button openButton = new Button("Open"); Button saveButton = new Button("Save");

// Constructor public FileDialogExample() { // Call the constructor for the Frame class with the title // for the window super("FileDialog Example");

// Choose the layout manager and initialize it setLayout(new GridLayout(1, 2));

// Add components to frame add(openButton); add(saveButton);

Page 67: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 67

FileDialog // Add listener for buttons openButton.addActionListener(this); saveButton.addActionListener(this);

// Set the size for the frame and display it setSize(200, 100); show(); }

// actionPerformed: Detect the event (Open, or Save) // display either a load file dialog or a // save file dialog. Display the name of the // file that the user has selected in the // command window. public void actionPerformed(ActionEvent event) { if (event.getSource() == openButton) { FileDialog openDialog = new FileDialog(this, "Open", FileDialog.LOAD);

// Display the dialog and get the filename from the user openDialog.setVisible(true);

// Hide the dialog so it does not cover the application, // but is still available so we can get the filename openDialog.setVisible(false);

Page 68: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 68

FileDialog // Check whether user canceled the load if (openDialog.getFile() == null) { System.out.println("User canceled the load"); } else { // Display the full filename in the command window System.out.println("Open file " + openDialog.getDirectory() + openDialog.getFile()); } } else if (event.getSource() == saveButton) { FileDialog saveDialog = new FileDialog(this, "Save", FileDialog.SAVE);

// Display the dialog and get the filename from the user saveDialog.setVisible(true);

// Hide the dialog so it does not cover the application, // but is still available so we can get the filename saveDialog.setVisible(false);

Page 69: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 69

FileDialog // Check whether user canceled the save if (saveDialog.getFile() == null) { System.out.println("User canceled the save"); } else { // Display the full filename in the command window System.out.println("Save file " + saveDialog.getDirectory() + saveDialog.getFile()); } } }}

public class DemonstrateFileDialog{ static public void main(String[] args) { new FileDialogExample(); }}

Page 70: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 70

SimpleEditorDesign a simple editor around FileDialog and

TextAreaCan only open and

save files -- no cut, copy, paste (except using keyboard commands)

Has a toolbar forfrequent commands

Also has a menusystem

Page 71: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 71

SimpleEditor// This program is a simple editor that allows// the user to type in text and save it to a file. The user// can also load text from a file.//// The program has one menu with menu items Open, Save, and// Exit. It also has a "toolbar" across the top with buttons// for Open, Save, and Exit.//// It is a simple demonstration of TextArea, menus, and// file dialogs.

import java.io.*;import java.awt.*;import java.awt.event.*;

public class SimpleEditor extends Frame implements ActionListener{ // Interface variables Menu fileMenu = new Menu("File"); MenuItem openMenuItem = new MenuItem("Open"); MenuItem saveMenuItem = new MenuItem("Save"); MenuItem exitMenuItem = new MenuItem("Exit"); Button openButton = new Button("Open"); Button saveButton = new Button("Save"); Button exitButton = new Button("Exit"); TextArea editTextArea = new TextArea();

Page 72: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 72

SimpleEditor // Constructor public SimpleEditor() { // Call the constructor for the Frame class with the title // for the window super("Simple Editor");

// Choose the layout manager and initialize it setLayout(new BorderLayout());

// Define a menu bar object and add it to frame MenuBar mb = new MenuBar(); setMenuBar(mb);

// Add menu to menu bar mb.add(fileMenu);

// Add menu items to menu fileMenu.add(openMenuItem); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); fileMenu.add(exitMenuItem);

Page 73: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 73

SimpleEditor // Add listener for menu items openMenuItem.addActionListener(this); saveMenuItem.addActionListener(this); exitMenuItem.addActionListener(this);

// Make a "toolbar" panel out of the three buttons Panel toolbarPanel = new Panel(); toolbarPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); toolbarPanel.add(openButton); toolbarPanel.add(saveButton); toolbarPanel.add(exitButton);

// Add listener for buttons openButton.addActionListener(this); saveButton.addActionListener(this); exitButton.addActionListener(this);

// Add components to frame add(toolbarPanel, BorderLayout.NORTH); add(editTextArea, BorderLayout.CENTER);

// Set the size for the frame and display // it setSize(300, 300); show(); }

Page 74: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 74

SimpleEditor // actionPerformed: Detect the event (Open, Save, or Exit) // and handle the event. The Exit event is // handled within the method. The Open and // Save events are delegated to other // private methods in this class. public void actionPerformed(ActionEvent event) { if (event.getSource() == exitMenuItem || event.getSource() == exitButton) { setVisible(false); dispose(); System.exit(0); } else if (event.getSource() == openMenuItem || event.getSource() == openButton) { readTextFromFile(); } else if (event.getSource() == saveMenuItem || event.getSource() == saveButton) { saveTextToFile(); } }

Page 75: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 75

SimpleEditor // readTextFromFile: Ask the user for a filename, then open the file // and read its contents into the TextArea edit buffer. private void readTextFromFile() { try { // Initialize the file variable File inFile = new File(getLoadFileName());

// Create an input stream and attach it to the file BufferedReader fileInStream = new BufferedReader(new FileReader(inFile));

// Read from the file editTextArea.setText(""); String line = fileInStream.readLine(); while (line != null) { editTextArea.append(line + '\n'); line = fileInStream.readLine(); }

// Close the stream fileInStream.close(); } catch (java.io.IOException e) {} }

Page 76: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 76

SimpleEditor // saveTextToFile: Ask the user for a filename, then save the // contents of the TextArea edit buffer. // NOTE: This method saves the text with just linefeeds between // lines. Some programs require a carriage return along // with each line feed between lines so they can read the // file. This is common with Windows 95/98/NT programs. private void saveTextToFile() { try { // Initialize the output file variable File outFile = new File(getSaveFileName());

// Create a buffered output stream, wrapped by // PrintWriter, and attach it to the file PrintWriter fileOutStream = new PrintWriter(new BufferedWriter (new FileWriter(outFile)));

// Write the output to the file fileOutStream.println(editTextArea.getText());

// Close the output stream fileOutStream.close(); } catch (java.io.IOException e) {} }

Page 77: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 77

SimpleEditor // getLoadFileName: Display a file dialog for loading a file. // Return the full name of the file. private String getLoadFileName() { FileDialog openDialog = new FileDialog(this, "Open", FileDialog.LOAD);

// Display the dialog and get the filename from the user openDialog.setVisible(true);

// Hide the dialog so it does not cover the application, // but is still available so we can get the filename openDialog.setVisible(false);

// Return the full filename return openDialog.getDirectory() + openDialog.getFile(); }

Page 78: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 78

SimpleEditor // getSaveFileName: Display a file dialog for saving a file. // Return the full name of the file. private String getSaveFileName() { FileDialog saveDialog = new FileDialog(this, "Save", FileDialog.SAVE);

// Display the dialog and get the filename from the user saveDialog.setVisible(true);

// Hide the dialog so it does not cover the application, // but is still available so we can get the filename saveDialog.setVisible(false);

// Return the full filename return saveDialog.getDirectory() + saveDialog.getFile(); }

// main: Run an instance of the SimpleEditor // class. // NOTE: This technique of putting main () inside // the application class, rather than making a // separate class for it, is commonly used, // especially for testing classes. static public void main(String[] args) { new SimpleEditor(); }}

Page 79: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 79

Other Capabilities of AWTOther layout managers

CardLayout GridBagLayout

Scroll barsText formatting

Fonts Styles Weights Colors

Nested menus (submenus)

Other dialogs Confirmation of exit

Other listeners Keyboard presses Mouse movements Mouse clicks Changes to text

Can extend Layout managers Components

Many other features!

Page 80: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 80

Swing ComponentsJava 2 introduces Swing components, with

Pluggable look and feel: Microsoft Windows, Motif, Java, and others

Accessibility: designed for convertion into textual forms for screen readers (makes GUI programs more accessible to visually-impaired users)

Drag and drop: allow user to drag information from Java programs to other programs

Many more components

Page 81: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 81

Swing ComponentsSwing largely a superset of AWT

Most AWT components have counterparts in SwingSwing versions start with J, (JLabel, JButton, ...)

Doesn’t include layout managers or listenersMust use AWT versions of these

Example

Page 82: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 82

Swing ComponentsImport AWT and

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

Extend JFrameclass SwingExample extends JFrame implements ActionListener{}

Define Swing componentsJTextField firstNameTextField = new JTextField(20);JTextField lastNameTextField = new JTextField(20);JLabel fullNameLabel = new JLabel();JButton submitButton = new JButton("Press Me!");

Page 83: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 83

Swing ComponentsConstructor

// Constructorpublic SwingExample(){ // Call the constructor for the JFrame class with the title // for the window super("Swing Example");

// Get content pane for this frame Container contentPane = getContentPane();

// Choose the layout manager and initialize it contentPane.setLayout(new GridLayout(3, 2));

// Put components on the frame contentPane.add(new Label("First name: ")); contentPane.add(firstNameTextField); contentPane.add(new Label("Last name: ")); contentPane.add(lastNameTextField); contentPane.add(submitButton); contentPane.add(fullNameLabel);

// Register the button with its listener object submitButton.addActionListener(this); // Set the size for the frame and display it pack(); show();}

Add componentsto content pane

Create content pane

Page 84: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 84

Swing ComponentsactionPerformed()

method

// actionPerformed: Display "Button pressed" in the command // window when the user pressed the button public void actionPerformed(ActionEvent event) { fullNameLabel.setText(firstNameTextField.getText() + " " + lastNameTextField.getText()); }

Same as AWT version

Page 85: Programming and Problem Solving With Java Copyright 1999, James M. Slack The Java Abstract Windowing Toolkit Layout and Layout Managers Components Panel.

Programming and Problem Solving With Java 85

Swing ComponentsUse Swing components largely like AWTSwing components more flexible

Can make a round Swing buttonCan put an image on a button

GotchasDon’t mix AWT and Swing components -- AWT will

probably cover up Swing componentsDon’t put Swing components on a Frame -- use JFrameModify Swing components only in event handlers

(actionPerformed(), ...)


Recommended