Text in java gui

How to draw text using GUI in Java

Following example demonstrates how to draw text drawString(), setFont() methods of Graphics class.

import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel < public void paint(Graphics g) < Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g2.setFont(font); g2.drawString("Text", 40, 120); >public static void main(String[] args) < JFrame f = new JFrame(); f.getContentPane().add(new Main()); f.setSize(300, 200); f.setVisible(true); >>

Result

The above code sample will produce the following result.

Text is displayed in a frame.

The following is an example to draw text using GUI.

import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Panel extends JPanel < public void paint(Graphics gr) < Graphics2D g = (Graphics2D)gr; g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g.setFont(font); g.drawString("Tutorialspoint", 40, 120); >public static void main(String[] args) < JFrame f = new JFrame(); f.getContentPane().add(new Panel()); f.setSize(300, 200); f.setVisible(true); >>

Result

The above code sample will produce the following result.

Text is displayed in a frame.

Источник

Using Text Components

This section provides background information you might need when using Swing text components. If you intend to use an unstyled text component — a text field, password field, formatted text field, or text area — go to its how-to page and return here only if necessary. If you intend to use a styled text component, see How to Use Editor Panes and Text Panes, and read this section as well. If you do not know which component you need, read on.

Читайте также:  Владельцем торговой марки javascript является

Swing text components display text and optionally allow the user to edit the text. Programs need text components for tasks ranging from the straightforward (enter a word and press Enter) to the complex (display and edit styled text with embedded images in an Asian language).

Swing provides six text components, along with supporting classes and interfaces that meet even the most complex text requirements. In spite of their different uses and capabilities, all Swing text components inherit from the same superclass, JTextComponent , which provides a highly-configurable and powerful foundation for text manipulation.

The following figure shows the JTextComponent hierarchy.

Swing

The following picture shows an application called TextSamplerDemo that uses each Swing text component.

An application that provides a sample of each Swing text component

Try this:

  1. Click the Launch button to run TextSamplerDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
  2. Type some text in the text field and press Enter. Do the same in the password field. The label beneath the fields is updated when you press Enter.
  3. Try entering valid and invalid dates into the formatted text field. Note that when you press Enter the label beneath the fields is updated only if the date is valid.
  4. Select and edit text in the text area and the text pane. Use keyboard bindings, Ctrl-X, Ctrl-C, and Ctrl-V, to cut, copy, and paste text, respectively.
  5. Try to edit the text in the editor pane, which has been made uneditable with a call to setEditable .
  6. Look in the text pane to find an example of an embedded component and an embedded icon.

The TextSamplerDemo example uses the text components in very basic ways. The following table tells you more about what you can do with each kind of text component.

Because they are so powerful and flexible, styled text components typically require more initial programming to set up and use. One exception is that editor panes can be easily loaded with formatted text from a URL, which makes them useful for displaying uneditable help information.

This Tutorial provides information about the foundation laid by the JTextComponent class and tells you how to accomplish some common text-related tasks.

To learn more about text components in JavaFX, see the Using Text and Text Effects in JavaFX and Using JavaFX UI Controls: Text Field tutorials.

Источник

How to Use Editor Panes and Text Panes

Two Swing classes support styled text: JEditorPane and its subclass JTextPane . The JEditorPane class is the foundation for Swing’s styled text components and provides a mechanism through which you can add support for custom text formats. If you want unstyled text, use a text area instead.

You can see an editor pane and a text pane in use by running TextSamplerDemo. Here is a picture of the TextSamplerDemo example.

An application that provides a sample of each Swing text component

Click the Launch button to run TextSamplerDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

The TextSamplerDemo example barely begins to demonstrate the capabilities of editor panes and text panes. However, the top right editor pane illustrates a handy, easy-to-use feature: it displays uneditable help information loaded from a URL. The text pane at the lower right demonstrates that you can easily embed images and even components directly into text panes.

If you need a fully-fledged help system, take a look at the javahelp project.

The Swing text API is powerful and immense, and we could devote an entire book just to using editor panes and text panes. This section introduces their capabilities, offers hints on which one you might want to use, and points to other sources of information.

Using an Editor Pane to Display Text From a URL

One task that you can accomplish without knowing anything about the Swing text system is displaying text from a URL. Here is the code from TextSamplerDemo.java that creates an uneditable editor pane that displays text formatted with HTML tags.

JEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false); java.net.URL helpURL = TextSamplerDemo.class.getResource( "TextSamplerDemoHelp.html"); if (helpURL != null) < try < editorPane.setPage(helpURL); >catch (IOException e) < System.err.println("Attempted to read a bad URL: " + helpURL); >> else < System.err.println("Couldn't find file: TextSamplerDemoHelp.html"); >//Put the editor pane in a scroll pane. JScrollPane editorScrollPane = new JScrollPane(editorPane); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(250, 145)); editorScrollPane.setMinimumSize(new Dimension(10, 10));

The code uses the default constructor to create the editor pane, then calls setEditable(false) so the user cannot edit the text. Next, the code creates the URL object, and calls the setPage method with it.

The setPage method opens the resource pointed to by the URL and figures out the format of the text (which is HTML in the example). If the text format is known, the editor pane initializes itself with the text found at the URL. A standard editor pane can understand plain text, HTML, and RTF. Note that the page might be loaded asynchronously, which keeps the GUI responsive but means that you should not count on the data being completely loaded after the call to setPage returns.

Editor Panes vs. Text Panes

In order to use editor panes and text panes, you need to understand the text system, which is described in Text Component Features. Several facts about editor panes and text panes are scattered throughout that section. Here we list the facts again and provide a bit more detail. The information here should help you understand the differences between editor panes and text panes, and when to use which.

  • An editor pane or a text pane can easily be loaded with text from a URL using the setPage method. The JEditorPane class also provides constructors that let you initialize an editor pane from a URL. The JTextPane class has no such constructors. See Using an Editor Pane to Display Text From a URL for an example that uses this feature to load an uneditable editor pane with HTML-formatted text. Be aware that the document and editor kit might change when using the setPage method. For example, if an editor pane contains plain text (the default), and you load it with HTML, the document will change to an HTMLDocument instance and the editor kit will change to an HTMLEditorKit instance. If your program uses the setPage method, make sure you adjust your code for possible changes to the pane’s document and editor kit instances (re-register document listeners on the new document, and so on).
  • Editor panes, by default, know how to read, write, and edit plain, HTML, and RTF text. Text panes inherit this capability but impose certain limitations. A text pane insists that its document implement the StyledDocument interface. HTMLDocument and RTFDocument are both StyledDocuments so HTML and RTF work as expected within a text pane. If you load a text pane with plain text though, the text pane’s document is not a PlainDocument as you might expect, but a DefaultStyledDocument .
  • To support a custom text format, implement an editor kit that can read, write, and edit text of that format. Then call the registerEditorKitForContentType method to register your kit with the JEditorPane class. By registering an editor kit in this way, all editor panes and text panes in your program will be able to read, write, and edit the new format. However, if the new editor kit is not a StyledEditorKit , text panes will not support the new format.
  • As mentioned previously, a text pane requires its document to implement the StyledDocument interface. The Swing text package provides a default implementation of this interface, DefaultStyledDocument , which is the document that text panes use by default. A text pane also requires that its editor kit be an instance of a StyledEditorKit (or a subclass). Be aware that the read and write methods for StyleEditorKit work with plain text.
  • Through their styled document and styled editor kit, text panes provide support for named styles and logical styles. The JTextPane class itself contains many methods for working with styles that simply call methods in its document or editor kit.
  • Through the API provided in the JTextPane class, you can embed images and components in a text pane. You can embed images in an editor pane, too, but only by including the images in an HTML or RTF file.

An Example of Using a Text Pane

Here is the code from the TextSamplerDemo example that creates and initializes a text pane.

String[] initString = < /* . fill array with initial text . */ >; String[] initStyles = < /* . fill array with names of styles . */ >; JTextPane textPane = new JTextPane(); StyledDocument doc = textPane.getStyledDocument(); addStylesToDocument(doc); //Load the text pane with styled text. try < for (int i=0; i < initString.length; i++) < doc.insertString(doc.getLength(), initString[i], doc.getStyle(initStyles[i])); >> catch (BadLocationException ble)

Briefly, this code hard-codes the initial text into an array and creates and hard-codes several styles — objects that represent different paragraph and character formats — into another array. Next, the code loops over the arrays, inserts the text into the text pane, and specifies the style to use for the inserted text.

Although this is an interesting example that concisely demonstrates several features of JTextPane , «real-world» programs aren’t likely to initialize a text pane this way. Instead, a program would use an editor pane to save a document which would then be used to initialize the text pane.

The Editor Pane and Text Pane API

This section lists some of the API related to text and editor panes. Many of the most useful methods for JEditorPane and its subclass JTextPane are inherited from the JTextComponent class. You can find the API tables for JTextComponent in The Text Component API. Also see The JComponent Class, which describes the API inherited from JComponent .

JEditorPane API for Displaying Text from a URL

Method or Constructor Description
JEditorPane(URL)
JEditorPane(String)
Creates an editor pane loaded with the text at the specified URL.
setPage(URL)
setPage(String)
Loads an editor pane (or text pane) with the text at the specified URL.
URL getPage() Gets the URL for the editor pane’s (or text pane’s) current page.
JTextPane API
Method or Constructor Description
JTextPane()
JTextPane(StyledDocument)
Creates a text pane. The optional argument specifies the text pane’s model.
StyledDocument getStyledDocument
setStyledDocument(StyledDocument)
Gets or sets the text pane’s model.

Examples That Use Text Panes and Editor Panes

To begin using text, you might want to run these programs and examine their code to find something similar to what you want to do.

Example Where Described Notes
TextSamplerDemo Using Text Components Uses each Swing text component.
TextComponentDemo Text Component Features Provides a customized text pane. Illustrates many text component features, such as undo and redo, document filters, document listeners, caret change listeners, and how to associate editing actions with menus and key strokes.
TreeDemo How to Use Trees Uses an editor pane to display help loaded from an HTML file.

Learn to edit HTML text in JavaFX with the Using JavaFX UI Controls: HTML Editor tutorial.

Источник

Оцените статью