Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials

Program Challenge: Create Tabs in a Text Pane

 
New to Java Programming Center

Java Technology Fundamentals
January's Program Challenge
New to Java Programming Center

Java Platform Overview | Getting Started | Step-by-Step Programming
Learning Paths | References & Resources | Courses & Certification | Newsletters


Following the example of setting the tab attribute for a text pane, create a text pane that manipulates the character attributes. Have three words in the text pane, each with their own attributes.

Have the first word be "One" with bold text.
Have the second word be "Two" with red text on a black background.
Have the third word be "Three" with a 32-point font.

  import java.awt.*;
  import javax.swing.*;
  import javax.swing.text.*;

  public class Style {
    public static void main(String args[]) {
      JFrame frame = new JFrame("Character Attributes");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container content = frame.getContentPane();
      JTextPane pane = new JTextPane();
      SimpleAttributeSet set = new SimpleAttributeSet();
      set.addAttribute(
        StyleConstants.CharacterConstants.Bold,
        Boolean.TRUE);
      // Initialize attributes before adding text
      pane.setCharacterAttributes(set, true);
      pane.setText("One ");

      set = new SimpleAttributeSet();
      StyleConstants.setItalic(set, true);
      StyleConstants.setForeground(set, Color.RED);
      StyleConstants.setBackground(set, Color.BLACK);

      Document doc = pane.getStyledDocument();
      try {
        doc.insertString(doc.getLength(), "Two ", set);
      } catch (BadLocationException e) {
        System.err.println("Bad location");
        return;
      }

      set = new SimpleAttributeSet();
      StyleConstants.setFontSize(set, 32);

      try {
        doc.insertString(doc.getLength(), "Three", set);
      } catch (BadLocationException e) {
        System.err.println("Bad location");
        return;
      }

      JScrollPane scrollPane = new JScrollPane(pane);
      content.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(300, 200);
      frame.setVisible(true);
    }
  }