29
Using Text Components JTextComponent JTextTextField JEditorPane JTextPane JPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Embed Size (px)

Citation preview

Page 1: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Using Text Components

JTextComponent

JTextTextField JEditorPane

JTextPaneJPasswordField

JTextArea

Text Controls

Plain Text Areas

Styled Text Areas

Page 2: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Text Controls

● Also called text fields● Can display and edit one line of text at a time● Respond to action events, typically the user

typing the Enter key● Used to get a small amount of textual information

from the user● JPasswordField is an extension of JTextField that does not display typed text

Page 3: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Text Field Example

● Display a labeled text field with the following behavior:– User enters text followed by the Enter key– If the entered text is not ''quit'', the text is

highlighted (selected) and then nothing is done● Subsequent typing in the field will cause the highlighted

text to be erased

– If the entered text is ''quit'', the program exits

Page 4: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Display

After the user enters some text and hits Enter:

Page 5: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Text Field Code

... JLabel label = new JLabel("Enter a command:"); JTextField textField = new JTextField(20); textField.setPreferredSize(new Dimension(50,20)); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String command = textField.getText(); if (command.equals("quit")) { frame.dispose(); // frame is top-level System.exit(0); // JFrame } else { textField.selectAll(); } } }); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(label); panel.add(textField); frame.getContentPane().add(panel); frame.setVisible(true); ...

Page 6: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Notes On The Code● The argument to the JTextField constructor is

a preferred size for the visible area; the length of the string entered is not limited

● As with buttons, text fields are action-based● The action listener is created using a constructor

for an anonymous class that extends the action listener interface

● The getText method returns the entered string● The selectAll method highlights the string● The label and text field are put into a JPanel first;

otherwise the text field would fill the frame

Page 7: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Plain Text Areas

● JTextArea can display and edit multiple lines of text

● Text can be displayed in any font, but all of the text is in the same font

● Use a text area to allow the user to enter unformatted text of any length

● Also can be used to display unformatted help information

Page 8: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

JTextArea Example

... JTextArea textArea = new JTextArea( "This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." ); textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true);

JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(textArea); frame.getContentPane().add(panel); // frame is the top-level frame.setVisible(true); // JFrame ...

Page 9: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example Display

Note that a default text area width was used,and that the text does not fit in the frame.

It needs to have its text displayed within ascroll pane.

Page 10: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

JTextArea Example Modified

textArea = new JTextArea( "This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." ); textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true);

JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(200, 150));

panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(areaScrollPane); frame.getContentPane().add(panel); frame.setVisible(true);

Page 11: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

New Display

Page 12: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Styled Text Areas

● JEditorPane and JTextPane objects can display text in multiple fonts

● Some allow embedded images and even embedded components

● Require more up-front programming to set up and use

● Exception: JEditorPane can be easily used to display formatted text from a URL

Page 13: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Digression: The Model-View Approach to Software Architecture

● Like most Swing components, the text components use a model-view approach– The model is the data about the underlying component– The view is a presentation of the data

● E.g., underlying a JButton is a ButtonModel object that has:– whether it is enabled– whether it is selected– whether it is pressed– what its keyboard mnemonic is

Page 14: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

The Model-View Approach to Software Architecture (cont'd)

● Why separate the model from its view?– So that different Look-and-Feels can be created for

the same data– If you need the data for some processing, it is much

more efficient to get it directly from the model than from the component that is presenting it

● All JTextComponent classes provide views of their associated models, called documents

Page 15: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Documents● Each document is an instance of a class that

implements the Document interface● A document must provide the following services

for a text component:– Contain the text– Provide support for text editing– Notify listeners of changes to the text– Manage a position within the text– Allow retrieval of information like text length, and of

sub-portions of the text

Page 16: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Document Class and Interface Hierarchy

AbstractDocument

PlainDocument DefaultStyledDocument

HTMLDocument

Document

StyledDocument

implements

implements

implements

Used by JTextFieldand JTextArea

Used by JEditorPane

Used byJTextPane

Page 17: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

The JEditorPane Class● JEditorPane is the foundation for Swing's

styled text components● A JEditorPane object becomes an editor for

the type of content it is given:– text/plain: plain text– text/html: Hypertext Markup Language– text/rtf: Rich Text Format

● Uses an instance of the EditorKit class to accomplish editing tasks

● Can be used to display uneditable URLs

Page 18: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Loading Content into a JEditorPane

● setText: initializes the component from a String

● read: initializes the component from a Reader● setPage: initializes the component from a URL ● Besides using these methods, similar loading can

be accomplished using constructors

Page 19: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

JEditorPane Example

JFrame frame = ... // make top-level window

editorPane = new JEditorPane( "text/plain", "Here is a string of text\n" + "initialized in the constructor.\n" + "Note that we gave the type\n" + "\"text/plain\" as the first argument.");

JScrollPane editorScrollPane = new JScrollPane(editorPane); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(300, 300));

JPanel panel = ... // make panel to hold editorPane and // add panel to frame

Page 20: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example Display

Page 21: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Loading From URLs● Consider the following HTML file, called Test.html:

<html><head><title>A Test HTML Page</title></head><body><h1>A Test HTML Page</h1>

<center><table border><tr><th> Fruits <th> Vegetables <th> Drinks </tr><tr><td> Apples <td> Broccoli <td> Milk </tr><tr><td> Bananas <td> Spinach <td> Juice </tr><tr><td> Oranges <td> Carrots <td> Soda </tr><tr><td> Grapes <td> Squash <td> </tr><tr><td> Lemons <td> <td> </tr></table></center>

</body></html>

Page 22: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Loading From URLs (cont'd)

● A file URL is of the form:– file:<directory><separator><filename>

● There is a URL class constructor that takes a string representing a file URL specification as an argument

● We could code the specification directly:– new URL(''file:/home/cs/tcolburn.../Test.html'')

● Or we can use the System class to build the specification

Page 23: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

System Class Properties● Java maintains a list of system properties and

their values, implemented as a hash table. Some of them:

Property Valueos.name Operating system nameos.arch Operating system architectureos.version Operating system versionfile.separator ''/'' on Unixpath.separator '':'' on Unixline.separator ''\n'' on Unixuser.name User's account nameuser.home User's home directoryuser.dir User's current working directory

Use Sytem.getProperty(''<property>'') to retrieve a value

Page 24: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example That Loads A File URLimport java.io.*;import java.net.*; ... editorPane = new JEditorPane(); editorPane.setEditable(false); try { url = new URL("file:" + System.getProperty("user.dir") + System.getProperty("file.separator") + "Test.html"); editorPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); } catch (Exception e) { System.err.println("Couldn't create URL: " + url); }

JScrollPane editorScrollPane = new JScrollPane(editorPane); ... panel = new JPanel(); ... panel.add(editorScrollPane); frame.getContentPane().add(panel); frame.setVisible(true); ...

Page 25: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Notes On The Example

● The URL class is in the java.net package● setEditable(false) is used to keep the

HTML document from being edited● new URL(...) can throw an exception if the

file URL specification is malformed● setPage(url) can throw an exception if the

URL argument cannot be read for some reason

Page 26: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example Output

Page 27: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example That Loads A Network URLimport java.io.*;import java.net.*; ... editorPane = new JEditorPane(); editorPane.setEditable(false); try { url = new URL("http://www.d.umn.edu/~tcolburn/hours.html"); editorPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); } catch (Exception e) { System.err.println("Couldn't create URL: " + url); }

JScrollPane editorScrollPane = new JScrollPane(editorPane); ... panel = new JPanel(); ... panel.add(editorScrollPane); frame.getContentPane().add(panel); frame.setVisible(true); ...

Page 28: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

Example Output

Page 29: Using Text Components JTextComponent JTextTextFieldJEditorPane JTextPaneJPasswordField JTextArea Text Controls Plain Text Areas Styled Text Areas

The JTextPane Class

● The JTextPane class extends JEditorPane● A text pane inherits the capabilities of an editor

pane but insists that its document be a styled document

● You can embed images and components in a text pane

● You can embed images in an editor pane too, but only by including them in an HTML or RTF file