Brower based on JEditorPane : TextPane « Swing JFC « Java






Brower based on JEditorPane

Brower based on JEditorPane
   
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class Browser extends JFrame {

  protected JEditorPane m_browser;

  protected MemComboBox m_locator = new MemComboBox();

  public Browser() {
    super("HTML Browser");
    setSize(500, 300);
    getContentPane().setLayout(new BorderLayout());

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p.add(new JLabel("Address"));

    m_locator.load("addresses.dat");
    BrowserListener lst = new BrowserListener();
    m_locator.addActionListener(lst);

    MemComboAgent agent = new MemComboAgent(m_locator);

    p.add(m_locator);

    getContentPane().add(p, BorderLayout.NORTH);

    m_browser = new JEditorPane();
    m_browser.setEditable(false);
    m_browser.addHyperlinkListener(lst);

    JScrollPane sp = new JScrollPane();
    sp.getViewport().add(m_browser);
    getContentPane().add(sp, BorderLayout.CENTER);

    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        m_locator.save("addresses.dat");
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);

    setVisible(true);
    m_locator.grabFocus();
  }

  class BrowserListener implements ActionListener, HyperlinkListener {
    public void actionPerformed(ActionEvent evt) {
      String sUrl = (String) m_locator.getSelectedItem();
      if (sUrl == null || sUrl.length() == 0 )
        return;

      BrowserLoader loader = new BrowserLoader(sUrl);
      loader.start();
    }

    public void hyperlinkUpdate(HyperlinkEvent e) {
      URL url = e.getURL();
      if (url == null )
        return;
      BrowserLoader loader = new BrowserLoader(url.toString());
      loader.start();
    }
  }

  class BrowserLoader extends Thread {
    protected String m_sUrl;

    public BrowserLoader(String sUrl) {
      m_sUrl = sUrl;
    }

    public void run() {
      setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

      try {
        URL source = new URL(m_sUrl);
        m_browser.setPage(source);
        m_locator.add(m_sUrl);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Browser.this, "Error: "
            + e.toString(), "Warning", JOptionPane.WARNING_MESSAGE);
      }
      setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
  }

  public static void main(String argv[]) {
    new Browser();
  }

}
class MemComboAgent extends KeyAdapter {
  protected JComboBox m_comboBox;

  protected JTextField m_editor;

  public MemComboAgent(JComboBox comboBox) {
    m_comboBox = comboBox;
    m_editor = (JTextField) comboBox.getEditor().getEditorComponent();
    m_editor.addKeyListener(this);
  }

  public void keyReleased(KeyEvent e) {
    char ch = e.getKeyChar();
    if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch))
      return;
    int pos = m_editor.getCaretPosition();
    String str = m_editor.getText();
    if (str.length() == 0)
      return;

    for (int k = 0; k < m_comboBox.getItemCount(); k++) {
      String item = m_comboBox.getItemAt(k).toString();
      if (item.startsWith(str)) {
        m_editor.setText(item);
        m_editor.setCaretPosition(item.length());
        m_editor.moveCaretPosition(pos);
        break;
      }
    }
  }
}

class MemComboBox extends JComboBox {
  public static final int MAX_MEM_LEN = 30;

  public MemComboBox() {
    super();
    setEditable(true);
  }

  public void add(String item) {
    removeItem(item);
    insertItemAt(item, 0);
    setSelectedItem(item);
    if (getItemCount() > MAX_MEM_LEN)
      removeItemAt(getItemCount() - 1);
  }

  public void load(String fName) {
    try {
      if (getItemCount() > 0)
        removeAllItems();
      File f = new File(fName);
      if (!f.exists())
        return;
      FileInputStream fStream = new FileInputStream(f);
      ObjectInput stream = new ObjectInputStream(fStream);

      Object obj = stream.readObject();
      if (obj instanceof ComboBoxModel)
        setModel((ComboBoxModel) obj);

      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }

  public void save(String fName) {
    try {
      FileOutputStream fStream = new FileOutputStream(fName);
      ObjectOutput stream = new ObjectOutputStream(fStream);

      stream.writeObject(getModel());

      stream.flush();
      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }
}

           
         
    
    
  








Related examples in the same category

1.TextPane SampleTextPane Sample
2.JTextPane demo with various format and html loading and renderingJTextPane demo with various format and html loading and rendering
3.Styled TextStyled Text
4.Appending TextPaneAppending TextPane
5.Text Component DisplayText Component Display
6.JTextPane Styles Example 1JTextPane Styles Example 1
7.JTextPane Styles Example 2JTextPane Styles Example 2
8.JTextPane Styles Example 3JTextPane Styles Example 3
9.JTextPane Styles Example 4JTextPane Styles Example 4
10.JTextPane Styles Example 5JTextPane Styles Example 5
11.JTextPane Styles Example 6JTextPane Styles Example 6
12.JTextPane Styles Example 7JTextPane Styles Example 7
13.JTextPane Styles Example 8JTextPane Styles Example 8
14.JTextPane Highlight ExampleJTextPane Highlight Example
15.JTextPane Extended Paragraph Example
16.TextPane ElementsTextPane Elements
17.TextPane Views 2TextPane Views 2
18.List HTML ValuesList HTML Values
19.Show HTML Document
20.Show HTML Views
21.JEditorPane Replace ReaderJEditorPane Replace Reader
22.Bi-Directional TextBi-Directional Text
23.TextPane: DocumentEvent TextPane: DocumentEvent
24.Show how Icons, Components, and text can be added to a JTextPaneShow how Icons, Components, and text can be added to a JTextPane
25.Parentheses matcherParentheses matcher
26.A TabSet in a JTextPaneA TabSet in a JTextPane
27.Extension of JTextPane that allows the user to easily append colored text to the documentExtension of JTextPane that allows the user to easily append colored text to the document
28.An implementation of HighlightPainter that underlines text with a thick lineAn implementation of HighlightPainter that underlines text with a thick line
29.An example of highlighting multiple, discontiguous regions of a text component.An example of highlighting multiple, discontiguous regions of a text component.
30.A custom caret classA custom caret class
31.Enumerating the Paragraphs of a JTextPane Component
32.Inserting an Image into a JTextPane Component
33.Inserting a Component into a JTextPane Component
34.Customizing Tab Stops in a JTextPane Component
35.Sharing Styles Between JTextPanes
36.Listing the Styles Associated with a JTextPane
37.Listing the Attributes in a Style
38.Replace style
39.Set logical style; replaces paragraph style's parent
40.Get logical style and restore it after new paragraph style
41.Determining If a Style Attribute Applies to a Character or the Paragraph
42.Determine if the attribute is a color or a font-related attribute.
43.Create a tab set from the tab stops
44.Foreground color
45.Background color
46.Change the Font size of JTextPane
47.Font family
48.Bold style
49.An example of several text components including password fields and formatted fields.An example of several text components including password fields and formatted fields.
50.A style can have multiple attributes; this one makes text bold and italic
51.Duplicate style
52.Italicize the entire paragraph containing the position 12
53.Inserting Styled Text in a JTextPane Component
54.A separation of a data from the visual representation. In a JTextPane component, we have a StyledDocument for setting the style of the text data.
55.Tests two attributed strings for equality.
56.Get Leading White Space
57.Get Leading White Space Width
58.Get Max Fitting FontSize
59.Reads a AttributedString object that has been serialised by the SerialUtilities.writeAttributedString(AttributedString, ObjectOutputStream)} method.