Java/Tiny Application/Browser

Материал из Java эксперт
Перейти к: навигация, поиск

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.ruboBoxModel;
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());
    }
  }
}





Drag and drop web browser

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class DnDWebBrowser extends JFrame {
  private WebToolBar toolBar;
  private WebBrowserPane browserPane = new WebBrowserPane();
  public DnDWebBrowser() {
    super("Drag-and-Drop Web Browser");
    toolBar = new WebToolBar(browserPane);
    browserPane.setDropTarget(new DropTarget(browserPane, DnDConstants.ACTION_COPY,
        new DropTargetHandler()));
    Container contentPane = getContentPane();
    contentPane.add(toolBar, BorderLayout.NORTH);
    contentPane.add(new JScrollPane(browserPane), BorderLayout.CENTER);
  }
  private class DropTargetHandler implements DropTargetListener {
    public void drop(DropTargetDropEvent event) {
      Transferable transferable = event.getTransferable();
      if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
        event.acceptDrop(DnDConstants.ACTION_COPY);
        try {
          List fileList = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
          Iterator iterator = fileList.iterator();
          while (iterator.hasNext()) {
            File file = (File) iterator.next();
            browserPane.goToURL(file.toURL());
          }
          event.dropComplete(true);
        } catch (UnsupportedFlavorException flavorException) {
          flavorException.printStackTrace();
          event.dropComplete(false);
        } catch (IOException ioException) {
          ioException.printStackTrace();
          event.dropComplete(false);
        }
      } else {
        event.rejectDrop();
      }
    }
    public void dragEnter(DropTargetDragEvent event) {
      if (event.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
        event.acceptDrag(DnDConstants.ACTION_COPY);
      else {
        event.rejectDrag();
      }
    }
    public void dragExit(DropTargetEvent event) {
    }
    public void dragOver(DropTargetDragEvent event) {
    }
    public void dropActionChanged(DropTargetDragEvent event) {
    }
  }
  public static void main(String args[]) {
    DnDWebBrowser browser = new DnDWebBrowser();
    browser.setDefaultCloseOperation(EXIT_ON_CLOSE);
    browser.setSize(640, 480);
    browser.setVisible(true);
  }
}
class WebBrowserPane extends JEditorPane {
  private List history = new ArrayList();
  private int historyIndex;
  public WebBrowserPane() {
    setEditable(false);
  }
  public void goToURL(URL url) {
    displayPage(url);
    history.add(url);
    historyIndex = history.size() - 1;
  }
  public URL forward() {
    historyIndex++;
    if (historyIndex >= history.size())
      historyIndex = history.size() - 1;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  public URL back() {
    historyIndex--;
    if (historyIndex < 0)
      historyIndex = 0;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  private void displayPage(URL pageURL) {
    try {
      setPage(pageURL);
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }
  }
}
class WebToolBar extends JToolBar implements HyperlinkListener {
  private WebBrowserPane webBrowserPane;
  private JButton backButton;
  private JButton forwardButton;
  private JTextField urlTextField;
  public WebToolBar(WebBrowserPane browser) {
    super("Web Navigation");
    webBrowserPane = browser;
    webBrowserPane.addHyperlinkListener(this);
    urlTextField = new JTextField(25);
    urlTextField.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        try {
          URL url = new URL(urlTextField.getText());
          webBrowserPane.goToURL(url);
        } catch (MalformedURLException urlException) {
          urlException.printStackTrace();
        }
      }
    });
    backButton = new JButton("back");
    backButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.back();
        urlTextField.setText(url.toString());
      }
    });
    forwardButton = new JButton("forward");
    forwardButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.forward();
        urlTextField.setText(url.toString());
      }
    });
    add(backButton);
    add(forwardButton);
    add(urlTextField);
  }
  public void hyperlinkUpdate(HyperlinkEvent event) {
    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      URL url = event.getURL();
      webBrowserPane.goToURL(url);
      urlTextField.setText(url.toString());
    }
  }
}





MDI based web browser

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class MDIWebBrowser extends JFrame {
  JDesktopPane desktopPane = new JDesktopPane();
  public MDIWebBrowser() {
    super("MDI Web Browser");
    createNewWindow();
    Container contentPane = getContentPane();
    contentPane.add(desktopPane);
    JMenu fileMenu = new JMenu("File");
    fileMenu.add(new NewWindowAction());
    fileMenu.addSeparator();
    fileMenu.add(new ExitAction());
    fileMenu.setMnemonic("F");
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
  }
  private void createNewWindow() {
    JInternalFrame frame = new JInternalFrame("Browser", // title
        true, // resizable
        true, // closable
        true, // maximizable
        true); // iconifiable
    WebBrowserPane browserPane = new WebBrowserPane();
    WebToolBar toolBar = new WebToolBar(browserPane);
    Container contentPane = frame.getContentPane();
    contentPane.add(toolBar, BorderLayout.NORTH);
    contentPane.add(new JScrollPane(browserPane), BorderLayout.CENTER);
    frame.setSize(320, 240);
    // move JInternalFrame to prevent it from obscuring others
    int offset = 30 * desktopPane.getAllFrames().length;
    frame.setLocation(offset, offset);
    desktopPane.add(frame);
    frame.setVisible(true);
  }
  private class NewWindowAction extends AbstractAction {
    public NewWindowAction() {
      putValue(Action.NAME, "New Window");
      putValue(Action.SHORT_DESCRIPTION, "Create New Web Browser Window");
      putValue(Action.MNEMONIC_KEY, new Integer("N"));
    }
    public void actionPerformed(ActionEvent event) {
      createNewWindow();
    }
  }
  private class ExitAction extends AbstractAction {
    public ExitAction() {
      // set name, description and mnemonic key
      putValue(Action.NAME, "Exit");
      putValue(Action.SHORT_DESCRIPTION, "Exit Application");
      putValue(Action.MNEMONIC_KEY, new Integer("x"));
    }
    public void actionPerformed(ActionEvent event) {
      System.exit(0);
    }
  }
  public static void main(String args[]) {
    MDIWebBrowser browser = new MDIWebBrowser();
    browser.setDefaultCloseOperation(EXIT_ON_CLOSE);
    browser.setSize(640, 480);
    browser.setVisible(true);
  }
}
class WebToolBar extends JToolBar implements HyperlinkListener {
  private WebBrowserPane webBrowserPane;
  private JButton backButton;
  private JButton forwardButton;
  private JTextField urlTextField;
  public WebToolBar(WebBrowserPane browser) {
    super("Web Navigation");
    webBrowserPane = browser;
    webBrowserPane.addHyperlinkListener(this);
    urlTextField = new JTextField(25);
    urlTextField.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        try {
          URL url = new URL(urlTextField.getText());
          webBrowserPane.goToURL(url);
        }catch (MalformedURLException urlException) {
          urlException.printStackTrace();
        }
      }
    });
    backButton = new JButton("back");
    backButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.back();
        urlTextField.setText(url.toString());
      }
    });
    forwardButton = new JButton("forward");
    forwardButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.forward();
        urlTextField.setText(url.toString());
      }
    });
    add(backButton);
    add(forwardButton);
    add(urlTextField);
  }
  public void hyperlinkUpdate(HyperlinkEvent event) {
    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      URL url = event.getURL();
      webBrowserPane.goToURL(url);
      urlTextField.setText(url.toString());
    }
  }
}
class WebBrowserPane extends JEditorPane {
  private List history = new ArrayList();
  private int historyIndex;
  public WebBrowserPane() {
    setEditable(false);
  }
  public void goToURL(URL url) {
    displayPage(url);
    history.add(url);
    historyIndex = history.size() - 1;
  }
  public URL forward() {
    historyIndex++;
    if (historyIndex >= history.size())
      historyIndex = history.size() - 1;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  public URL back() {
    historyIndex--;
    if (historyIndex < 0)
      historyIndex = 0;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  private void displayPage(URL pageURL) {
    try {
      setPage(pageURL);
    }
    catch (IOException ioException) {
      ioException.printStackTrace();
    }
  }
}





Tabbed Web browser

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class TabbedPaneWebBrowser extends JFrame {
  private JTabbedPane tabbedPane = new JTabbedPane();
  public TabbedPaneWebBrowser() {
    super("JTabbedPane Web Browser");
    createNewTab();
    getContentPane().add(tabbedPane);
    JMenu fileMenu = new JMenu("File");
    fileMenu.add(new NewTabAction());
    fileMenu.addSeparator();
    fileMenu.add(new ExitAction());
    fileMenu.setMnemonic("F");
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
  }
  private void createNewTab() {
    JPanel panel = new JPanel(new BorderLayout());
    WebBrowserPane browserPane = new WebBrowserPane();
    WebToolBar toolBar = new WebToolBar(browserPane);
    panel.add(toolBar, BorderLayout.NORTH);
    panel.add(new JScrollPane(browserPane), BorderLayout.CENTER);
    tabbedPane.addTab("Browser " + tabbedPane.getTabCount(), panel);
  }
  private class NewTabAction extends AbstractAction {
    public NewTabAction() {
      putValue(Action.NAME, "New Browser Tab");
      putValue(Action.SHORT_DESCRIPTION, "Create New Web Browser Tab");
      putValue(Action.MNEMONIC_KEY, new Integer("N"));
    }
    public void actionPerformed(ActionEvent event) {
      createNewTab();
    }
  }
  private class ExitAction extends AbstractAction {
    public ExitAction() {
      putValue(Action.NAME, "Exit");
      putValue(Action.SHORT_DESCRIPTION, "Exit Application");
      putValue(Action.MNEMONIC_KEY, new Integer("x"));
    }
    public void actionPerformed(ActionEvent event) {
      System.exit(0);
    }
  }
  public static void main(String args[]) {
    TabbedPaneWebBrowser browser = new TabbedPaneWebBrowser();
    browser.setDefaultCloseOperation(EXIT_ON_CLOSE);
    browser.setSize(640, 480);
    browser.setVisible(true);
  }
}
class WebBrowserPane extends JEditorPane {
  private List history = new ArrayList();
  private int historyIndex;
  public WebBrowserPane() {
    setEditable(false);
  }
  public void goToURL(URL url) {
    displayPage(url);
    history.add(url);
    historyIndex = history.size() - 1;
  }
  public URL forward() {
    historyIndex++;
    if (historyIndex >= history.size())
      historyIndex = history.size() - 1;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  public URL back() {
    historyIndex--;
    if (historyIndex < 0)
      historyIndex = 0;
    URL url = (URL) history.get(historyIndex);
    displayPage(url);
    return url;
  }
  private void displayPage(URL pageURL) {
    try {
      setPage(pageURL);
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }
  }
}
class WebToolBar extends JToolBar implements HyperlinkListener {
  private WebBrowserPane webBrowserPane;
  private JButton backButton;
  private JButton forwardButton;
  private JTextField urlTextField;
  public WebToolBar(WebBrowserPane browser) {
    super("Web Navigation");
    // register for HyperlinkEvents
    webBrowserPane = browser;
    webBrowserPane.addHyperlinkListener(this);
    urlTextField = new JTextField(25);
    urlTextField.addActionListener(new ActionListener() {
      // navigate webBrowser to user-entered URL
      public void actionPerformed(ActionEvent event) {
        try {
          URL url = new URL(urlTextField.getText());
          webBrowserPane.goToURL(url);
        }
        catch (MalformedURLException urlException) {
          urlException.printStackTrace();
        }
      }
    });
    backButton = new JButton("back");
    backButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.back();
        urlTextField.setText(url.toString());
      }
    });
    forwardButton = new JButton("forward");
    forwardButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        URL url = webBrowserPane.forward();
        urlTextField.setText(url.toString());
      }
    });
    add(backButton);
    add(forwardButton);
    add(urlTextField);
  }
  public void hyperlinkUpdate(HyperlinkEvent event) {
    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      URL url = event.getURL();
      webBrowserPane.goToURL(url);
      urlTextField.setText(url.toString());
    }
  }
}