CS 596 Java Programming Fall Semester, 1998 Fonts, Components, Dialogs |
||
---|---|---|
© 1998, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 21-Dec-98 |
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(); } }
Output
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 )
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(); } }
Output
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 MeaningButton
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
Component Listeners The following listeners are supported by all components in AWT.
Event Class Listener Interface Listener MethodsComponentEvent
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()
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()
CENTER | LEFT | RIGHT |
addNotify() |
paramString() |
getAlignment() |
setAlignment(int) |
getText() |
setText(String) |
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
Button
Button supports the ActionEvent.
Component Events MeaningButton
ActionEvent
Button clicked
Event Class Listener Interface Listener MethodsActionEvent
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); } }
Checkbox
Checkbox supports the ItemEvent.
Component Events MeaningCheckbox
ItemEvent
Item selected or deselected
Event Class Listener Interface Listener MethodsItemEvent
ItemListener
itemStateChanged()
Checkbox Constructors
Checkbox()
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() ); } }
Checkbox Example public static void main( String args[] ) { new CheckboxExample(200, 50); } }Output
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); } }
Output
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()
Choice - Drop-down Lists
Component Events MeaningChoice
ItemEvent
Item selected or deselected
Event Class Listener Interface Listener MethodsItemEvent
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)
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); } }
Choice Example ContinuedOutput
List
Component Events MeaningList
ActionEvent
List item doubled clicked
ItemEvent
List item selected or deselected
Event Class Listener Interface Listener MethodsActionEvent
ActionListener
actionPerformed()
ItemEvent
ItemListener
itemStateChanged()
List Constructors
List()
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) |
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(); }
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
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 MeaningTextComponent
TextEvent
User changed text
Event Class Listener Interface Listener MethodsTextEvent
TextListener
textValueChanged()
TextArea Constructors
TextArea()
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) |
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); } }
Output
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 MeaningTextComponent
TextEvent
User changed text
TextField
ActionEvent
User finished editing text
Event Class Listener Interface Listener MethodsActionEvent
ActionListener
actionPerformed()
TextEvent
TextListener
textValueChanged()
TextField Constructors TextField()
addActionListener(ActionListener) removeActionListener(ActionListener) addNotify() echoCharIsSet() getColumns() getEchoChar() getMinimumSize() |
getMinimumSize(int) getPreferredSize() getPreferredSize(int) paramString() setColumns(int) setEchoChar(char) |
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 );
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); } }
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 );
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(); } } }
Validating Input - Output
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); } }
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(); } }
Dialogs
Dialogs can be either modal or nonmodal.
Modal
A modal dialog blocks:
getTitle()
isModal() isResizable() |
paramString()
setModal(boolean) setResizable(boolean) |
setTitle(String)
show() |
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(); } }
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() ); } } }
Dialog Example Continued
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); }
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