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

Slides:



Advertisements
Similar presentations
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Advertisements

Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Graphical User Interface (GUI) Programming III. Lecture Objectives Exploring more GUI programming elements in Java Using labels in GUIs Using colors to.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 14 Applets. 2 Knowledge Goals Understand the differing roles of applications and applets Understand how a browser operates Understand the role.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Graphical User Interfaces
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
Swing User Interface Components. In this class we will cover: Model-View-Controller Design Pattern Layout Management Text Input.
Building a Web Browser CS1316: Representing Structure and Behavior.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
GUI programming Graphical user interface-based programming.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
CIS Intro to JAVA Lecture Notes Set June-05 GUI Programming – Assignment 5 Notes.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Cs413_chapt02.ppt CS413 Advanced Swing Graphical User Interface Components Text: Advanced Java 2 Platform: Chapter 2 Abstract Windowing Toolkit (AWT) Library.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-2 ( Book Chapter 14) GUI and Event-Driven Programming.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
Copyright © Curt Hill More Widgets In Abstract Window Toolbox.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Creating a GUI Class An example of class design using inheritance and interfaces.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Frame Windows Application program, not applet Construct and show frame JFrame frame = new JFrame(); *** frame.show(); *** Set default close operation..
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Dept. of CSIE, National University of Tainan 10/21/2012 Working with Swing.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Graphical User Interface (GUI) Programming III
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Graphical user interface-based programming
Graphical User Interface
Presentation transcript:

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

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

Display After the user enters some text and hits Enter:

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);...

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

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

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...

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 a scroll pane.

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);

New Display

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

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

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

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

Document Class and Interface Hierarchy AbstractDocument PlainDocument DefaultStyledDocumen t HTMLDocument Document StyledDocumen t implements Used by JTextField and JTextArea Used by JEditorPane Used by JTextPane

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

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

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

Example Display

Loading From URLs ● Consider the following HTML file, called Test.html : A Test HTML Page A Test HTML Page Fruits Vegetables Drinks Apples Broccoli Milk Bananas Spinach Juice Oranges Carrots Soda Grapes Squash Lemons

Loading From URLs (cont'd) ● A file URL is of the form: – file: ● 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

System Class Properties ● Java maintains a list of system properties and their values, implemented as a hash table. Some of them: Property Value os.name Operating system name os.arch Operating system architecture os.version Operating system version file.separator ''/'' on Unix path.separator '':'' on Unix line.separator ''\n'' on Unix user.name User's account name user.home User's home directory user.dir User's current working directory Use Sytem.getProperty('' '') to retrieve a value

Example That Loads A File URL import 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);...

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

Example Output

Example That Loads A Network URL import java.io.*; import java.net.*;... editorPane = new JEditorPane(); editorPane.setEditable(false); try { url = new URL(" 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);...

Example Output

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