SDSU CS 596 Java Programming
Fall Semester, 1998
Fonts, Components, Dialogs
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 21-Dec-98

Contents of Doc 31, Fonts, Components, Dialogs


Reference:

Graphic Java 1.2 Volume I: AWT 3 rd Edition, Geary, Chapters 4 (pp. 89-100), 12 (pp. 479-484), 13 - 15, 16 (pp. 582-595).


Listen Here!Q-dec3 3mins Doc 31, Fonts, Components, Dialogs Slide # 2

Fonts

Java supports multiple fonts. Here is an example of using different fonts in an AWT window.

import  java.awt.*;
class  FancyHello  extends  Frame  {
   public  FancyHello() {
      int  pointSize  =  36;
      setFont( new Font( "TimesRoman", Font.BOLD, pointSize ));
      setBackground( Color.white );
      setTitle( "Hi Mom" );
      setSize( 150,  150);
      show();
   }
   public  void  paint(  Graphics  display  ){
      int x  =  50;
      int y  =  60;
      display.setColor( Color.black );
      display.drawString(  "Hello", x, y );
      display.setFont( new Font("Symbol", Font.ITALIC, 12 ));
      x  =  50;
      y  =  100;
      display.drawString(  "World", x, y );
   }
   public  static  void  main( String  args[] ){
      new  FancyHello();
   }
}

Doc 31, Fonts, Components, Dialogs Slide # 3
Output


Listen Here!Q-dec3 3mins, Q-dec3 3mins Doc 31, Fonts, Components, Dialogs Slide # 4
Font Issues
What Fonts are Available?
The following code prints out what fonts are available in the JVM running the program. While the program does not open a window, it still needs access to a window manager.

import  java.awt.Toolkit;
class  WhatFonts {
   public  static  void  main( String  args[] ) {
      Toolkit  platformInfo = Toolkit.getDefaultToolkit();
      String[] availbleFonts = platformInfo.getFontList();
      for ( int index = 0; index < availbleFonts.length; index++ )
         System.out.println( availbleFonts[ index ]  );
   }
}

JDK 1.1 Standard Answer
Dialog
TimesRoman
Symbol
Helvetica
Courier


JDK 1.2 Standard Answer
The text states that the following fonts are supported in JDK1.2. However, JDK 1.2 should be able to access all the fonts installed on your system. The JDK 1.2 on my Macintosh computer accesses all the fonts on my machine.
Dialog
Monospaced
Courier
SansSerif
Helvetica
DialogInput
Serif
TimesRoman
ZapfDingbats

What Font Styles are Available?
The following styles are available for fonts in JDK 1.1 and 1.2.
Font.PLAIN, Font.BOLD, Font.ITALIC

These styles can be mixed as shown below.

new Font("Courier", Font.ITALIC + Font.BOLD, 12 )

Doc 31, Fonts, Components, Dialogs Slide # 5
Font Issues
How many pixels in a string?

Use FontMetrics to determine find the width of a string in a given font. The FontMetrics contains many methods to measure different aspects of text in a font.

import  java.awt.*;
class  TextSize  extends  Frame  {
   public  TextSize() {
      setTitle( "Text Size" );
      setSize( 300,  200);
      show();
   }
   public  void  paint(  Graphics  display  ){
      Font largeText = new Font( "TimesRoman", Font.BOLD, 24 );
      FontMetrics  largeTextSize;
      largeTextSize = display.getFontMetrics( largeText );
      display.setFont( largeText  );
      display.setColor( Color.black );
      int x  =  50;
      int y  =  90;
      display.drawString(  "Hello ", x, y );
      x = x + largeTextSize.stringWidth( "Hello " );
      display.drawString(  "World", x, y );
   }
   public  static  void  main( String  args[] ) {
      new  TextSize();
   }
}

Doc 31, Fonts, Components, Dialogs Slide # 6
Output

Doc 31, Fonts, Components, Dialogs Slide # 7

Components

All components are subclasses of Component. Thus, all components support ComponentEvents, FocusEvents, KeyEvents and MouseEvents. The following table shows the events that each component supports.
Component
Events
Meaning
Button
ActionEvent
Button clicked
Checkbox
ItemEvent
Item selected or deselected
CheckboxMenuItem
ItemEvent
Item selected or deselected
Choice
ItemEvent
Item selected or deselected
Component
ComponentEvent
Component moved, resized, hidden or shown

FocusEvent
Focus gained or lost

KeyEvent
Key pressed or released

MouseEvent
Mouse button pressed or released, mouse entered or left component, mouse moved or dragged
List
ActionEvent
List item doubled clicked

ItemEvent
List item selected or deselected
MenuItem
ActionEvent
Menu item selected
Scrollbar
AdjustmentEvent
User moved scrollbar
TextComponent
TextEvent
User changed text
TextField
ActionEvent
User finished editing text
Window
WindowEvent
Window opened, closed, iconified, deiconified, or close requested


Doc 31, Fonts, Components, Dialogs Slide # 8
Component Listeners
The following listeners are supported by all components in AWT.

Event Class
Listener Interface
Listener Methods
ComponentEvent
ComponentListener
componentHidden()
componentMoved()
componentResized()
componentShown()
FocusEvent
FocusListener
focusGained()
focusLost()
ItemEvent
ItemListener
itemStateChanged()
KeyEvent
KeyListener
keyPressed()
keyReleased()
keyTyped()
MouseEvent
MouseListener
mouseClicked()
mouseEntered()
mousePressed()
mouseReleased()

MouseMotionListener
mouseDragged()
mouseMoved()


Doc 31, Fonts, Components, Dialogs Slide # 9

Label

Label provides a way to display text on the screen. It does not support any events other that those supported by the Component class.

Label Constructors

Label()
Constructs an empty label.
Label(String)
Constructs a new label with the specified String of text.
Label(String, int)
Constructs a new label with the specified String of text and the specified alignment.


Label Constants

CENTERLEFTRIGHT

Some Label Methods

addNotify()
paramString()
getAlignment()
setAlignment(int)
getText()
setText(String)

Listen Here!Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 10
Label Example

class  LabelExample  extends Frame  {
      
   public LabelExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Label Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new GridLayout(5, 1) );
      
      add( new Label( "Hi Mom" ) );
      add( new Label( "Hi Dad", Label.CENTER  ) );
      add( new Label( "Good Bye", Label.RIGHT ) );
      add( new Label( "Good Luck", Label.LEFT ) );
      Font largeFont = new Font( "TimesRoman", Font.ITALIC, 24 );
      Label largeText = new Label( "Large Font" );
      largeText.setFont( largeFont );
      add( largeText );
      show();
   }   
   
   public  static  void  main( String  args[] ) {
      new  LabelExample(150, 100);
   }
}
Output

Doc 31, Fonts, Components, Dialogs Slide # 11

Button

Button supports the ActionEvent.
Component
Events
Meaning
Button
ActionEvent
Button clicked

Event Class
Listener Interface
Listener Methods
ActionEvent
ActionListener
actionPerformed()

We have seen buttons before. Here we set the font of a button.

class  ButtonTextExample  extends Frame  {
      
   public ButtonTextExample( int widthInPixels, int heightInPixels) {
      setTitle( "Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      Font largeFont = new Font( "TimesRoman", Font.ITALIC, 24 );
      Button largeText = new Button( "Large Font" );
      largeText.setFont( largeFont );
      add( largeText );
      show();
   }   
   
   public  static  void  main( String  args[] ) {
      new  ButtonTextExample(150, 100);
   }
}

Listen Here!Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 12

Checkbox

Checkbox supports the ItemEvent.
Component
Events
Meaning
Checkbox
ItemEvent
Item selected or deselected

Event Class
Listener Interface
Listener Methods
ItemEvent
ItemListener
itemStateChanged()

Checkbox Constructors

Checkbox()
Constructs a Checkbox with no label, no Checkbox group, and initialized to a false state.
Checkbox(String)
Constructs a Checkbox with the specified label, no Checkbox group, and initialized to a false state.
Checkbox(String, CheckboxGroup, boolean)
Constructs a Checkbox with the specified label, specified Checkbox group, and specified boolean state.

The next two slides show some basic features of Checkboxes.

Listen Here!Q-dec3 1min Doc 31, Fonts, Components, Dialogs Slide # 13
Checkbox Example
import java.awt.*;
import java.awt.event.*;
class CheckboxExample extends Frame {
   private Checkbox left = new Checkbox( "Left" );
   private Checkbox right = new Checkbox( "Right" );
      
   public CheckboxExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Checkbox Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      add( left );
      add( right );
      left.addItemListener( new LeftRightListener() );
      right.addItemListener( new LeftRightListener() );
      show();
   }
   private void reportChange( Checkbox selectedBox ) {
      System.out.print( selectedBox.getLabel() + " box changed " );
      System.out.println( "value is " + selectedBox.getState() ); 
   }
   class LeftRightListener implements ItemListener {
      public void itemStateChanged( ItemEvent event ) {
         System.out.println( "GetItemSelectable: " + event.getItemSelectable() );
         System.out.println( "GetItem: " + event.getItem() );
         if ( event.getStateChange() == ItemEvent.SELECTED )
            System.out.println( "Selected" );
         else
            System.out.println( "Deselected" );
         reportChange( (Checkbox) event.getItemSelectable() );
      }
   }

Listen Here!Q-dec3 1min Doc 31, Fonts, Components, Dialogs Slide # 14
Checkbox Example

   public  static  void  main( String  args[] ) { 
      new  CheckboxExample(200, 50);
   }
}
Output


Doc 31, Fonts, Components, Dialogs Slide # 15
Changing Checkbox Label

import java.awt.*;
import java.awt.event.*;
class  CheckboxToggleExample  extends Frame  {
   private Checkbox toggle = new Checkbox( "Off");
      
   public CheckboxToggleExample( int  widthInPixels, 
                                       int heightInPixels ) {
      setTitle( "Toggle Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      add( toggle );
      toggle.addItemListener( new ToggleListener() );
      show();
   }
   class ToggleListener implements ItemListener {
      public void itemStateChanged( ItemEvent event ) {
         Checkbox selected = (Checkbox) event.getItemSelectable();
         if ( selected.getState() == true )
            selected.setLabel( "On" );
         else if  ( selected.getState() == false )
            selected.setLabel( "Off" );
      }
   }
      
   public  static  void  main( String  args[] ){
      new  CheckboxToggleExample(200, 50);
   }
}

Doc 31, Fonts, Components, Dialogs Slide # 16
Output



Listen Here!Q-dec3 37secs Doc 31, Fonts, Components, Dialogs Slide # 17

Checkbox Groups - Radio buttons

Use the CheckboxGroup to create a group of radio buttons, only one of which can be selected at a time. CheckboxGroup is not a subclass of component.
import java.awt.*;
import java.awt.event.*;
class  RadioButton  extends Frame  {
   public RadioButton( int  widthInPixels, int heightInPixels ) {
      setTitle( "Radio Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      CheckboxGroup directions = new CheckboxGroup();
      add( new Checkbox( "Left", directions, false) );
      add( new Checkbox( "Right", directions, true));
      show( );
   }
   public  static  void  main( String  args[] ) {
      new  RadioButton(200, 50);
   }
}
Output



Some CheckboxGroup Methods
getSelectedCheckbox() 
setSelectedCheckbox(Checkbox) 
toString()

Listen Here!Q-dec3 44secs Doc 31, Fonts, Components, Dialogs Slide # 18

Choice - Drop-down Lists


Component
Events
Meaning
Choice
ItemEvent
Item selected or deselected

Event Class
Listener Interface
Listener Methods
ItemEvent
ItemListener
itemStateChanged()

Some Choice Methods
add(String)
addItem(String)
addItemListener(ItemListener)
removeItemListener(ItemListener)
getItem(int)
getItemCount()
getSelectedIndex() getSelectedItem()
getSelectedObjects()
insert(String, int)
paramString()
remove(int)
remove(String)
removeAll()
select(int)
select(String)


Listen Here!Q-dec3 5mins, Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 19
Choice Example
import java.awt.*;
import java.awt.event.*;
class  ChoiceBoxes  extends Frame  {
   Choice directions = new Choice();
   
   public ChoiceBoxes( int  widthInPixels, int heightInPixels ) {
      setTitle( "ChoiceBox Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      directions.addItem( "Left" );
      directions.addItem( "Right" );
      directions.addItem( "Up" );
      directions.addItem( "Down" );
      directions.addItemListener( new ChoiceListener() );
      add( directions );
      show();
   }
   class ChoiceListener implements ItemListener {
      int  count = 1;
      public void itemStateChanged( ItemEvent event ) {
         Choice selected = (Choice) event.getItemSelectable();
         int selectedIndex = selected.getSelectedIndex();
         String selectedText = selected.getSelectedItem();
         System.out.println( "Selected index: " +  selectedIndex);
         System.out.println( "Selected string: " + selectedText );
         selected.insert( String.valueOf( count++ ), selectedIndex );
         selected.remove( selectedText );
      }
   }
   public  static  void  main( String  args[] ) { new  ChoiceBoxes(200, 200); }
}

Doc 31, Fonts, Components, Dialogs Slide # 20
Choice Example ContinuedOutput


Listen Here!Q-dec3 39secs Doc 31, Fonts, Components, Dialogs Slide # 21

List

Component
Events
Meaning
List
ActionEvent
List item doubled clicked

ItemEvent
List item selected or deselected

Event Class
Listener Interface
Listener Methods
ActionEvent
ActionListener
actionPerformed()
ItemEvent
ItemListener
itemStateChanged()

List Constructors

List()
Creates a new scrolling list initialized with no visible Lines or multiple selections.
List(int, boolean)
Creates a new scrolling list initialized with the specified number of visible lines and a boolean stating whether multiple selections are allowed or not.

List Methods
add(String)
add(String, int)
addActionListener(ActionListener)
addItem(String)
addItem(String, int)
addItemListener(ItemListener)
addNotify()
delItem(int)
deselect(int)
getItem(int)
getItemCount()
getItems()
getMinimumSize()
getMinimumSize(int)
getPreferredSize()
getPreferredSize(int)
getRows()
getSelectedIndex()
getSelectedIndexes()
getSelectedItem()
getSelectedItems()
getSelectedObjects()
getVisibleIndex()
isIndexSelected(int)
isMultipleMode()
makeVisible(int)
paramString()
remove(int)
remove(String)
removeActionListener(ActionListener)
removeAll()
removeItemListener(ItemListener)
removeNotify()
replaceItem(String, int)
select(int)
setMultipleMode(boolean)

Listen Here!Q-dec3 1min Doc 31, Fonts, Components, Dialogs Slide # 22
List Example
import java.awt.*;
import java.awt.event.*;
class  ListExample  extends Frame  {
   public ListExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "List Box Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      boolean areMultipleSelectionsAllowed = false;
      int numberDisplayed = 4;
      List directions = new List( numberDisplayed, 
                        areMultipleSelectionsAllowed );
      directions.addItem( "Left" );
      directions.addItem( "Right" );
      directions.addItem( "Up" );
      directions.addItem( "Down" );
      directions.addItemListener( new ListListener() );
      add( directions );
      show();
   }

Listen Here!Q-dec3 3mins Doc 31, Fonts, Components, Dialogs Slide # 23
List Example

   class ListListener implements ItemListener {
      public void itemStateChanged( ItemEvent event ) {
         List selected = (List) event.getItemSelectable();
         int selectedIndex = selected.getSelectedIndex();
         String selectedText = selected.getSelectedItem();
         System.out.println( "Selected index: " +  selectedIndex);
         System.out.println( "Selected string: " + selectedText );
      }
   }
   public  static  void  main( String  args[] ) {
      new  ListExample(200, 100);
   }
}
Output


Listen Here!Q-dec3 2mins, Q-dec3 4mins Doc 31, Fonts, Components, Dialogs Slide # 24

TextArea

A TextArea is a scrollable region that users can enter text. A TextArea can contain multiple rows and columns of text. The number of characters that can fit on one row depends on the font, font size and number of columns.
Component
Events
Meaning
TextComponent
TextEvent
User changed text

Event Class
Listener Interface
Listener Methods
TextEvent
TextListener
textValueChanged()

TextArea Constructors

TextArea()
Constructs a new TextArea.
TextArea(int, int)
Constructs a new TextArea with the specified number of rows and columns.
TextArea(String)
Constructs a new TextArea with the specified text displayed.
TextArea(String, int, int)
Constructs a new TextArea with the specified text and number of rows and columns.

TextArea Methods
addNotify() 
append(String) 
getColumns() 
getMinimumSize() 
getMinimumSize(int, int) 
getPreferredSize() 
getPreferredSize(int, int) 
getRows() 
getScrollbarVisibility() 
insert(String, int) 
paramString() 
replaceRange(String, int, int) 
setColumns(int) 
setRows(int) 

Listen Here!Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 25
TextArea Example
import java.awt.*;
import java.awt.event.*;
class  TextAreas  extends Frame  {
   TextArea userInput;
   Button done = new Button( "Done Typing" );
      
   public TextAreas( int  widthInPixels, int heightInPixels ) {
      setTitle( "Text Area Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      
      int numberOfLines = 3;
      int numberOfColumns = 30;
      userInput = new TextArea( numberOfLines, numberOfColumns );
      add( userInput );
      add( done );
      
      done.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
               checkUserInput();
            }
         });
      show();
   }
   
   private void checkUserInput() {
      System.out.println( "You typed: " +  userInput.getText() );
      System.out.println( "Selected text>" + 
                         userInput.getSelectedText() +"<" );
      userInput.setText( "Hi Mom");
   }
   public  static  void  main( String  args[] ) {
      new  TextAreas(300, 150);
   }
}

Listen Here!Q-dec3 48secs Doc 31, Fonts, Components, Dialogs Slide # 26
Output





Doc 31, Fonts, Components, Dialogs Slide # 27

TextField

A TextField is a region that users can enter text. A TextField contains only one row of text. The number of characters that can be seen in a TextField depends on the font, font size and number of columns.

Component
Events
Meaning
TextComponent
TextEvent
User changed text
TextField
ActionEvent
User finished editing text

Event Class
Listener Interface
Listener Methods
ActionEvent
ActionListener
actionPerformed()
TextEvent
TextListener
textValueChanged()

TextField Constructors
TextField()
Constructs a new TextField.
TextField(int)
Constructs a new TextField initialized with the specified columns.
TextField(String)
Constructs a new TextField initialized with the specified text.
TextField(String, int)
Constructs a new TextField initialized with the specified text and columns.

Some TextField Methods
addActionListener(ActionListener)
removeActionListener(ActionListener)  
addNotify() 
echoCharIsSet() 
getColumns() 
getEchoChar() 
getMinimumSize() 
getMinimumSize(int) getPreferredSize() 
getPreferredSize(int) 
paramString() 
setColumns(int) 
setEchoChar(char) 

Doc 31, Fonts, Components, Dialogs Slide # 28
TextField Example
class  TextFieldExample  extends Frame  {
   TextField firstName;
   TextField lastName;
   Button done = new Button( "Done Typing" );
      
   public TextFieldExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Text Field Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new GridLayout(3, 1) );
      
      int numberOfColumns = 10;
      firstName = new TextField(  numberOfColumns );
      Panel first = new Panel( new FlowLayout() );
      first.add( new Label( "First name", Label.RIGHT ));
      first.add( firstName );
      
      lastName = new TextField(  numberOfColumns );
      Panel last = new Panel( new FlowLayout() );
      last.add( new Label( "Last name", Label.RIGHT ) );
      last.add( lastName );
      
      Panel buttons = 
         new Panel( new FlowLayout( FlowLayout.CENTER));
      buttons.add( done );
      
      add( first );
      add( last );
      add( buttons );
      

Doc 31, Fonts, Components, Dialogs Slide # 29
TextField Example Continued

      // Called when user hits the enter key
      firstName.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
               System.out.println( "Action Event " + 
                  event.getActionCommand() );
            }
         });
      // Called when button is pressed.
      done.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
               System.out.println("Your name is: " + 
                     firstName.getText() +" " + lastName.getText() );
            }
         });
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  TextFieldExample(300, 150);
   }
}



Listen Here!Q-dec3 1min Doc 31, Fonts, Components, Dialogs Slide # 30
Validating Input
This example shows how to validate data after the user has entered it in a TextField. The example would be the same for TextAreas. In my tests on the Macintosh MRJ JVM 2.1 EAR2, the code below does not validate the TextField when the user tabs out of a TextField.

import java.awt.*;
import java.awt.event.*;
class  TextValidationExample  extends Frame  {
   TextField height;
   TextField width;
      
   public TextValidationExample( int  widthInPixels, 
                                       int heightInPixels ) {
      setTitle( "Text Field Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new GridLayout(2, 1) );
      
      int numberOfColumns = 5;
      height = new TextField(  numberOfColumns );
      Panel heightPanel = new Panel( new FlowLayout() );
      heightPanel.add( new Label( "Window height", Label.RIGHT ));
      heightPanel.add( height );
      
      width = new TextField(  numberOfColumns );
      Panel widthPanel = new Panel( new FlowLayout() );
      widthPanel.add( new Label( "Window width", Label.RIGHT ) );
      widthPanel.add( width );
      
      add( heightPanel );
      add( widthPanel );

Listen Here!Q-dec3 5mins Doc 31, Fonts, Components, Dialogs Slide # 31
Validating Input Continued
The important details are done in the IntegerValidator class.
      IntegerValidator validator = new IntegerValidator();
      height.addActionListener( validator );
      height.addFocusListener( validator );
      width.addActionListener( validator );
      width.addFocusListener( validator );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  TextValidationExample(300, 150);
   }
}
class IntegerValidator extends FocusAdapter 
                           implements ActionListener {
                           
   public void actionPerformed( ActionEvent event ) {
      validate( (TextField) event.getSource() );
   }
   public void focusLost( ActionEvent event ) {
      validate( (TextField) event.getSource() );
   }
   
   private void validate( TextField field ) {
      try {
         Integer.parseInt( field.getText() );
      }
      catch (NumberFormatException error ) {
         Toolkit.getDefaultToolkit().beep();
         field.requestFocus();
         field.selectAll();
      }
   }
}

Doc 31, Fonts, Components, Dialogs Slide # 32
Validating Input - Output


Listen Here!Q-dec3 3mins Doc 31, Fonts, Components, Dialogs Slide # 33

ScrollPane

Java JDK 1.0 had only ScrollBars, which the programmer had to make operate. Java JDK 1.1 added the ScrollPane class. ScrollPane performs the scrolling for you. This example shows how to use the ScrollPane. DrawXCanvas is on the next slide.

import java.awt.*;
import java.awt.event.*;
class  ScrollPaneExample  extends Frame  {
   ScrollPane aScrollPane = new ScrollPane();
      
   public ScrollPaneExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Scroll Example" );
      setSize( widthInPixels, heightInPixels );
      
      aScrollPane.add( new DrawXCanvas() );
      add( BorderLayout.CENTER, aScrollPane );
      
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  ScrollPaneExample(300, 150);
   }
}

Listen Here!Q-dec3 48secs Doc 31, Fonts, Components, Dialogs Slide # 34
ScrollPane Continued

class DrawXCanvas extends Canvas{
   int width = 200;
   int height = 400;
   
   public void paint( Graphics drawOnMe ){
      drawOnMe.drawLine( 0, 0, width, height );
      drawOnMe.drawLine( width, 0, 0, height );
   }
      
   public Dimension preferredSize() {
      return new Dimension( width, height );
   }
   public Dimension minimumSize() {
      return preferredSize();
   }
}


Doc 31, Fonts, Components, Dialogs Slide # 35

Dialogs

Dialogs can be either modal or nonmodal.

Modal

A modal dialog blocks:


Dialog Constructors
Dialog(Frame parent)
Constructs an initially invisible Dialog with an empty title.
Dialog(Frame parent, boolean modal)
Constructs an initially invisible Dialog with an empty title. If modal is true, then block input from the parent frame when dialog is shown.
Dialog(Frame parent, String title )
Constructs an initially invisible Dialog with a title.
Dialog(Frame parent, String title, boolean modal)
Constructs an initially invisible Dialog with a title. If modal is true, then block input from the parent frame when dialog is shown.

Some Dialog Methods
getTitle()
isModal()
isResizable()
paramString()
setModal(boolean)
setResizable(boolean)
setTitle(String)
show()

Listen Here!Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 36
Dialog Example
On this slide, a LoginDialog class is defined. On the next slide, it is used.

import java.awt.*;
import java.awt.event.*;
class  LoginDialog  extends Dialog  {
   TextField password;
   Button done = new Button( "OK" );
      
   public LoginDialog( Frame owner ) {
      super( owner, "Log in", true );
      setSize( 200, 100 );
      setLocation( 50, 50 );
      setLayout( new GridLayout(2, 1) );
      
      int numberOfColumns = 10;
      password = new TextField( numberOfColumns );
      password.setEchoChar( '*' );
      Panel first = new Panel( new FlowLayout() );
      first.add( new Label( "Password", Label.RIGHT ));
      first.add( password );
      
      Panel buttons = 
         new Panel( new FlowLayout( FlowLayout.CENTER));
      buttons.add( done );
      
      add( first );      add( buttons );
      done.addActionListener( new ActionListener() {
            public void actionPerformed( ActionEvent event ) {
               setVisible(false);
            }
         });
   }
   public String getPassword() {   return password.getText(); }
}

Listen Here!Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 37
Dialog Example Continued

class  DialogExample  extends Frame  {
   public DialogExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Text Validation Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
            
      Button login = new Button( "Log in" );
      login.addActionListener( new Login() );
      add( login );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  DialogExample(100, 50);
   }
   
   class Login implements ActionListener {
      public  void actionPerformed( ActionEvent event ) {
         LoginDialog passwordDialog = 
               new LoginDialog( DialogExample.this );
         passwordDialog.show(  );
         System.out.println( "Password is: " + 
            passwordDialog.getPassword() );
      }
   }
}

Doc 31, Fonts, Components, Dialogs Slide # 38
Dialog Example Continued





Listen Here!S-dec2 3mins, Q-dec3 2mins Doc 31, Fonts, Components, Dialogs Slide # 39

FileDialog

AWT has a FileDialog class which allows the user to select a file. You can restrict the files that are shown in the FileDialog by using a FilenameFilter. The example below only lets the user select files ending in ".java". The example spans two slides.

import java.awt.*;
import java.awt.event.*;
class JavaFiles implements java.io.FilenameFilter {
   public boolean accept( java.io.File directory, String name ) {
      return name.endsWith( ".java" );
   }
}
class  FileDialogExample  extends Frame  {
   public FileDialogExample( int widthInPixels, int heightInPixels ) {
      setTitle( "File Dialog Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
            
      Button file = new Button( "Select File" );
      file.addActionListener( new FileExample() );
      add( file );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  FileDialogExample(100, 50);
   }
   

Listen Here!S-dec2 4mins, Q-dec3 1min Doc 31, Fonts, Components, Dialogs Slide # 40
FileDialog Continued

The inner class FileExample shows how to start the FileDialog and how to determine which file the user selected and the directory that contains the selected file.

   class FileExample implements ActionListener {
      public  void actionPerformed( ActionEvent event ) {
         FileDialog files = 
            new FileDialog( FileDialogExample.this, "Select a File" );
         files.setFilenameFilter( new JavaFiles() );
         files.show(  );
         System.out.println( "Directory: " + files.getDirectory() );
         System.out.println( "File: " + files.getFile() );
      }
   }
}





Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 30-Nov-98