一、前言
通过Java的Swing实现Web客户端浏览器UI界面,只是完成最简单的URL的输入、后退、前进等基本功能满足初步使用,没有能兼容最新主流的CSS及JS,可以通过该实例了解一个浏览器最最基本的重要功能组件,效果如下图所示
二、代码实例
import java.awt.*;@b@import java.awt.event.*;@b@import java.net.*;@b@import java.util.*;@b@import javax.swing.*;@b@import javax.swing.event.*;@b@import javax.swing.text.html.*;@b@@b@// The Mini Web Browser.@b@public class JavaWebBrowser extends JFrame@b@ implements HyperlinkListener@b@{@b@ // These are the buttons for iterating through the page list.@b@ private JButton backButton, forwardButton;@b@@b@ // Page location text field.@b@ private JTextField locationTextField;@b@@b@ // Editor pane for displaying pages.@b@ private JEditorPane displayEditorPane;@b@@b@ // Browser's list of pages that have been visited.@b@ private ArrayList pageList = new ArrayList();@b@@b@ // Constructor for Mini Web Browser.@b@ public JavaWebBrowser()@b@ {@b@ // Set application title.@b@ super("JavaWebBrowser");@b@@b@ // Set window size.@b@ setSize(640, 480);@b@@b@ // Handle closing events.@b@ addWindowListener(new WindowAdapter() {@b@ public void windowClosing(WindowEvent e) {@b@ actionExit();@b@ }@b@ });@b@@b@ // Set up file menu.@b@ JMenuBar menuBar = new JMenuBar();@b@ JMenu fileMenu = new JMenu("File");@b@ fileMenu.setMnemonic(KeyEvent.VK_F);@b@ JMenuItem fileExitMenuItem = new JMenuItem("Exit",@b@ KeyEvent.VK_X);@b@ fileExitMenuItem.addActionListener(new ActionListener() {@b@ public void actionPerformed(ActionEvent e) {@b@ actionExit();@b@ }@b@ });@b@ fileMenu.add(fileExitMenuItem);@b@ menuBar.add(fileMenu);@b@ setJMenuBar(menuBar);@b@@b@ // Set up button panel.@b@ JPanel buttonPanel = new JPanel();@b@ backButton = new JButton("< Back");@b@ backButton.addActionListener(new ActionListener() {@b@ public void actionPerformed(ActionEvent e) {@b@ actionBack();@b@ }@b@ });@b@ backButton.setEnabled(false);@b@ buttonPanel.add(backButton);@b@ forwardButton = new JButton("Forward >");@b@ forwardButton.addActionListener(new ActionListener() {@b@ public void actionPerformed(ActionEvent e) {@b@ actionForward();@b@ }@b@ });@b@ forwardButton.setEnabled(false);@b@ buttonPanel.add(forwardButton);@b@ locationTextField = new JTextField(35);@b@ locationTextField.addKeyListener(new KeyAdapter() {@b@ public void keyReleased(KeyEvent e) {@b@ if (e.getKeyCode() == KeyEvent.VK_ENTER) {@b@ actionGo();@b@ }@b@ }@b@ });@b@ buttonPanel.add(locationTextField);@b@ JButton goButton = new JButton("GO");@b@ goButton.addActionListener(new ActionListener() {@b@ public void actionPerformed(ActionEvent e) {@b@ actionGo();@b@ }@b@ });@b@ buttonPanel.add(goButton);@b@@b@ // Set up page display.@b@ displayEditorPane = new JEditorPane();@b@ displayEditorPane.setContentType("text/html");@b@ displayEditorPane.setEditable(false);@b@ displayEditorPane.addHyperlinkListener(this);@b@@b@ getContentPane().setLayout(new BorderLayout());@b@ getContentPane().add(buttonPanel, BorderLayout.NORTH);@b@ getContentPane().add(new JScrollPane(displayEditorPane),@b@ BorderLayout.CENTER);@b@ }@b@@b@ // Exit this program.@b@ private void actionExit() {@b@ System.exit(0);@b@ }@b@@b@ // Go back to the page viewed before the current page.@b@ private void actionBack() {@b@ URL currentUrl = displayEditorPane.getPage();@b@ int pageIndex = pageList.indexOf(currentUrl.toString());@b@ try {@b@ showPage(@b@ new URL((String) pageList.get(pageIndex - 1)), false);@b@ }@b@ catch (Exception e) {}@b@ }@b@@b@ // Go forward to the page viewed after the current page.@b@ private void actionForward() {@b@ URL currentUrl = displayEditorPane.getPage();@b@ int pageIndex = pageList.indexOf(currentUrl.toString());@b@ try {@b@ showPage(@b@ new URL((String) pageList.get(pageIndex + 1)), false);@b@ }@b@ catch (Exception e) {}@b@ }@b@@b@ // Load and show the page specified in the location text field.@b@ private void actionGo() {@b@ URL verifiedUrl = verifyUrl(locationTextField.getText());@b@ if (verifiedUrl != null) {@b@ showPage(verifiedUrl, true);@b@ } else {@b@ showError("Invalid URL");@b@ }@b@ }@b@@b@ // Show dialog box with error message.@b@ private void showError(String errorMessage) {@b@ JOptionPane.showMessageDialog(this, errorMessage,@b@ "Error", JOptionPane.ERROR_MESSAGE);@b@ }@b@@b@ // Verify URL format.@b@ private URL verifyUrl(String url) {@b@ // Only allow HTTP URLs.@b@ if (!url.toLowerCase().startsWith("http://"))@b@ return null;@b@@b@ // Verify format of URL.@b@ URL verifiedUrl = null;@b@ try {@b@ verifiedUrl = new URL(url);@b@ } catch (Exception e) {@b@ return null;@b@ }@b@@b@ return verifiedUrl;@b@ }@b@@b@ /* Show the specified page and add it to@b@ the page list if specified. */@b@ private void showPage(URL pageUrl, boolean addToList)@b@ {@b@ // Show hour glass cursor while crawling is under way.@b@ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));@b@@b@ try {@b@ // Get URL of page currently being displayed.@b@ URL currentUrl = displayEditorPane.getPage();@b@@b@ // Load and display specified page.@b@ displayEditorPane.setPage(pageUrl);@b@@b@ // Get URL of new page being displayed.@b@ URL newUrl = displayEditorPane.getPage();@b@@b@ // Add page to list if specified.@b@ if (addToList) {@b@ int listSize = pageList.size();@b@ if (listSize > 0) {@b@ int pageIndex =@b@ pageList.indexOf(currentUrl.toString());@b@ if (pageIndex < listSize - 1) {@b@ for (int i = listSize - 1; i > pageIndex; i--) {@b@ pageList.remove(i);@b@ }@b@ }@b@ }@b@ pageList.add(newUrl.toString());@b@ }@b@@b@ // Update location text field with URL of current page.@b@ locationTextField.setText(newUrl.toString());@b@@b@ // Update buttons based on the page being displayed.@b@ updateButtons();@b@ }@b@ catch (Exception e)@b@ {@b@ // Show error messsage.@b@ showError("Unable to load page");@b@ }@b@ finally@b@ {@b@ // Return to default cursor.@b@ setCursor(Cursor.getDefaultCursor());@b@ }@b@ }@b@@b@ /* Update back and forward buttons based on@b@ the page being displayed. */@b@ private void updateButtons() {@b@ if (pageList.size() < 2) {@b@ backButton.setEnabled(false);@b@ forwardButton.setEnabled(false);@b@ } else {@b@ URL currentUrl = displayEditorPane.getPage();@b@ int pageIndex = pageList.indexOf(currentUrl.toString());@b@ backButton.setEnabled(pageIndex > 0);@b@ forwardButton.setEnabled(@b@ pageIndex < (pageList.size() - 1));@b@ }@b@ }@b@@b@ // Handle hyperlink's being clicked.@b@ public void hyperlinkUpdate(HyperlinkEvent event) {@b@ HyperlinkEvent.EventType eventType = event.getEventType();@b@ if (eventType == HyperlinkEvent.EventType.ACTIVATED) {@b@ if (event instanceof HTMLFrameHyperlinkEvent) {@b@ HTMLFrameHyperlinkEvent linkEvent =@b@ (HTMLFrameHyperlinkEvent) event;@b@ HTMLDocument document =@b@ (HTMLDocument) displayEditorPane.getDocument();@b@ document.processHTMLFrameHyperlinkEvent(linkEvent);@b@ } else {@b@ showPage(event.getURL(), true);@b@ }@b@ }@b@ }@b@@b@ // Run the JavaWebBrowser.@b@ public static void main(String[] args) {@b@ JavaWebBrowser browser = new JavaWebBrowser();@b@ browser.show();@b@ }@b@}