Academic Java    Java Tutorial  >  Swing  >  JFrame extended

JFrame extended Example

Java JFrame extended EXAMPLE output It can sometimes be convenient to extend the class JFrame in the way shown. Class Guht is a JFrame subclass.

Notice how the first line of the constructor calls super(). This allows the program to pass a title for the frame to JFrame's constructor.

The program uses a JTextPane and SimpleAttributeSet to present some text to the user.
// JFrame extended example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

class JFrameExtendedExample extends JFrame {

   private JTextPane jtp;

   public JFrameExtendedExample() {
      super("JFrame extended");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      jtp = new JTextPane();
      jtp.setFont(new Font("SansSerif", Font.PLAIN, 18));
      SimpleAttributeSet as0 = new SimpleAttributeSet();
      StyleConstants.setForeground(as0, Color.blue);
      StyleConstants.setItalic(as0, true);

      SimpleAttributeSet as1 = new SimpleAttributeSet();
      StyleConstants.setForeground(as1, Color.orange);
      StyleConstants.setBold(as1, true);

      appendText("It was a bright ", null);
      appendText("cold", as0);
      appendText(" day in ", null);
      appendText("April", as1);

      getContentPane().add(new JScrollPane(jtp));
      setSize(180,150);
      setVisible(true);
   }

   private void appendText(String s, AttributeSet attributes) {
      Document d = jtp.getDocument();
      try {
         d.insertString(d.getLength(), s, attributes);
      }
      catch (BadLocationException e) {}
   }

   public static void main(String[] args) {
      new JFrameExtendedExample();
   }
}


* JFrame Examples