The Swing Text Components

Despite all the complexity and power Swing’s text components provide, it’s still pretty simple to do most things. Figure 19-1 shows each of the six Swing text components, plus an extra JTextArea (to show a different wrapping style) and an extra JEditorPane (to show a different EditorKit).

// TextComponentSampler.java // import javax.swing.*; import javax.swing.text.*; import javax.swing.border.*; import java.awt.*; public class TextComponentSampler extends JFrame { public static String word = "portmeiron"; public static String markup = "Questions are <font size='+1' color='blue'>a burden</font> to others,\n" + "answers <font size='+2' color='red'>a prison</font> for oneself."; public TextComponentSampler( ) { super("TextComponentSampler"); JTextField tf = new JTextField(word, 12); JPasswordField pf = new JPasswordField(word, 12); MaskFormatter formatter = null; try { formatter = new MaskFormatter("UUUUU"); } catch (java.text.ParseException ex) { } JFormattedTextField ftf = new JFormattedTextField(formatter); ftf.setColumns(12); ftf.setValue(word); JTextArea ta1 = new JTextArea(markup); JScrollPane scroll1 = new JScrollPane(ta1); JTextArea ta2 = new JTextArea(markup); ta2.setLineWrap(true); ta2.setWrapStyleWord(true); JScrollPane scroll2 = new JScrollPane(ta2); JTextPane tp = new JTextPane( ); tp.setText(markup); // Create an AttributeSet with which to change color and font. SimpleAttributeSet attrs = new SimpleAttributeSet( ); StyleConstants.setForeground(attrs, ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.