【问题标题】:browse html files in java swing [duplicate]在java swing中浏览html文件[重复]
【发布时间】:2012-09-14 11:22:49
【问题描述】:

可能重复:
Swing JDialog/JTextPane and HTML links

我想在 swing 中浏览 HTML 文件,我已经做到了,在 JEditorPane 的帮助下显示了 html 文件的内容,但是 html 文件的链接没有在同一个窗格中打开另一个 HTML 文件。 摇摆可能吗?我希望 html 文件应该像纯 HTML 文件一样处理,这意味着链接应该在 JAVA 编辑器窗格中工作,目前我正在使用以下代码。

try
{
  FileInputStream fstream = new FileInputStream("src\\html\\test.html");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  String text="";
  while ((strLine = br.readLine()) != null)   {
    text=text+strLine+"\n";
  }
  JEditorPane htmlPane = new JEditorPane("text/html",text);
  cp.add(htmlPane);
  htmlPane.setBounds(750,50,600,600);
 }catch(Exception ex){
  JOptionPane.showMessageDialog(null,"exception is"+ex)   ;
 }

【问题讨论】:

    标签: java swing html-parsing jtextcomponent


    【解决方案1】:

    这个例子展示了如何在 Swing 中创建一个简单的浏览器。

    简单浏览器的课程代码如下:

    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.html.*;
    
    // The Simple Web Browser.
    public class MiniBrowser extends JFrame
    
            implements HyperlinkListener {
        // These are the buttons for iterating through the page list.
        private JButton backButton, forwardButton;
    
        // Page location text field.
        private JTextField locationTextField;
    
        // Editor pane for displaying pages.
        private JEditorPane displayEditorPane;
    
        // Browser's list of pages that have been visited.
        private ArrayList pageList = new ArrayList();
    
        // Constructor for Mini Web Browser.
        public MiniBrowser() {
            // Set application title.
            super("Mini Browser");
    
            // Set window size.
            setSize(640, 480);
    
            // Handle closing events.
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    actionExit();
                }
            });
    
            // Set up file menu.
            JMenuBar menuBar = new JMenuBar();
            JMenu fileMenu = new JMenu("File");
            fileMenu.setMnemonic(KeyEvent.VK_F);
            JMenuItem fileExitMenuItem = new JMenuItem("Exit",
                    KeyEvent.VK_X);
            fileExitMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    actionExit();
                }
            });
            fileMenu.add(fileExitMenuItem);
            menuBar.add(fileMenu);
            setJMenuBar(menuBar);
    
            // Set up button panel.
            JPanel buttonPanel = new JPanel();
            backButton = new JButton("< Back");
            backButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    actionBack();
                }
            });
            backButton.setEnabled(false);
            buttonPanel.add(backButton);
            forwardButton = new JButton("Forward >");
            forwardButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    actionForward();
                }
            });
            forwardButton.setEnabled(false);
            buttonPanel.add(forwardButton);
            locationTextField = new JTextField(35);
            locationTextField.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        actionGo();
                    }
                }
            });
            buttonPanel.add(locationTextField);
            JButton goButton = new JButton("GO");
            goButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    actionGo();
                }
            });
            buttonPanel.add(goButton);
    
            // Set up page display.
            displayEditorPane = new JEditorPane();
            displayEditorPane.setContentType("text/html");
            displayEditorPane.setEditable(false);
            displayEditorPane.addHyperlinkListener(this);
    
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(buttonPanel, BorderLayout.NORTH);
            getContentPane().add(new JScrollPane(displayEditorPane),
                    BorderLayout.CENTER);
        }
    
        // Exit this program.
        private void actionExit() {
            System.exit(0);
        }
    
        // Go back to the page viewed before the current page.
        private void actionBack() {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            try {
                showPage(
                        new URL((String) pageList.get(pageIndex - 1)), false);
            } catch (Exception e) {}
        }
    
        // Go forward to the page viewed after the current page.
        private void actionForward() {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            try {
                showPage(
                        new URL((String) pageList.get(pageIndex + 1)), false);
            } catch (Exception e) {}
        }
    
        // Load and show the page specified in the location text field.
        private void actionGo() {
            URL verifiedUrl = verifyUrl(locationTextField.getText());
            if (verifiedUrl != null) {
                showPage(verifiedUrl, true);
            } else {
                showError("Invalid URL");
            }
        }
    
        // Show dialog box with error message.
        private void showError(String errorMessage) {
            JOptionPane.showMessageDialog(this, errorMessage,
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    
        // Verify URL format.
        private URL verifyUrl(String url) {
            // Only allow HTTP URLs.
            if (!url.toLowerCase().startsWith("http://"))
                return null;
    
            // Verify format of URL.
            URL verifiedUrl = null;
            try {
                verifiedUrl = new URL(url);
            } catch (Exception e) {
                return null;
            }
    
            return verifiedUrl;
        }
    
      /* Show the specified page and add it to
         the page list if specified. */
        private void showPage(URL pageUrl, boolean addToList) {
            // Show hour glass cursor while crawling is under way.
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    
            try {
                // Get URL of page currently being displayed.
                URL currentUrl = displayEditorPane.getPage();
    
                // Load and display specified page.
                displayEditorPane.setPage(pageUrl);
    
                // Get URL of new page being displayed.
                URL newUrl = displayEditorPane.getPage();
    
                // Add page to list if specified.
                if (addToList) {
                    int listSize = pageList.size();
                    if (listSize > 0) {
                        int pageIndex =
                                pageList.indexOf(currentUrl.toString());
                        if (pageIndex < listSize - 1) {
                            for (int i = listSize - 1; i > pageIndex; i--) {
                                pageList.remove(i);
                            }
                        }
                    }
                    pageList.add(newUrl.toString());
                }
    
                // Update location text field with URL of current page.
                locationTextField.setText(newUrl.toString());
    
                // Update buttons based on the page being displayed.
                updateButtons();
            } catch (Exception e) {
                // Show error messsage.
                showError("Unable to load page");
            } finally {
                // Return to default cursor.
                setCursor(Cursor.getDefaultCursor());
            }
        }
    
      /* Update back and forward buttons based on
         the page being displayed. */
        private void updateButtons() {
            if (pageList.size() < 2) {
                backButton.setEnabled(false);
                forwardButton.setEnabled(false);
            } else {
                URL currentUrl = displayEditorPane.getPage();
                int pageIndex = pageList.indexOf(currentUrl.toString());
                backButton.setEnabled(pageIndex > 0);
                forwardButton.setEnabled(
                        pageIndex < (pageList.size() - 1));
            }
        }
    
        // Handle hyperlink's being clicked.
        public void hyperlinkUpdate(HyperlinkEvent event) {
            HyperlinkEvent.EventType eventType = event.getEventType();
            if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
                if (event instanceof HTMLFrameHyperlinkEvent) {
                    HTMLFrameHyperlinkEvent linkEvent =
                            (HTMLFrameHyperlinkEvent) event;
                    HTMLDocument document =
                            (HTMLDocument) displayEditorPane.getDocument();
                    document.processHTMLFrameHyperlinkEvent(linkEvent);
                } else {
                    showPage(event.getURL(), true);
                }
            }
        }
    
        // Run the Mini Browser.
        public static void main(String[] args) {
            MiniBrowser browser = new MiniBrowser();
            browser.show();
        }
    }
    

    参考:http://www.java-tips.org/java-se-tips/javax.swing/how-to-create-a-simple-browser-in-swing-3.html

    【讨论】:

    【解决方案2】:

    来自JEditorPane Javadocs

    某些类型的内容可以通过生成超链接事件来提供超链接支持。如果JEditorPane 不可编辑JEditorPane.setEditable(false); 已被调用),HTML EditorKit 将生成超链接事件。如果 HTML 框架嵌入到文档中,典型的响应是更改当前文档的一部分。以下代码片段是一个可能的超链接侦听器实现,它专门处理 HTML 框架事件,并简单地显示任何其他激活的超链接。

    class Hyperactive implements HyperlinkListener {
    
         public void hyperlinkUpdate(HyperlinkEvent e) {
             if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                 JEditorPane pane = (JEditorPane) e.getSource();
                 if (e instanceof HTMLFrameHyperlinkEvent) {
                     HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
                     HTMLDocument doc = (HTMLDocument)pane.getDocument();
                     doc.processHTMLFrameHyperlinkEvent(evt);
                 } else {
                     try {
                         pane.setPage(e.getURL());
                     } catch (Throwable t) {
                         t.printStackTrace();
                     }
                 }
             }
         }
     }
    

    所以:

    htmlPane.setEditable(false); 
    htmlPane.addHyperlinkListener(new Hyperactive());
    

    【讨论】:

      【解决方案3】:

      来自JEditorPane 的文档。

      某些类型的内容可以通过生成超链接事件来提供超链接支持。如果 JEditorPane 不可编辑(已调用JEditorPane.setEditable(false);),HTML EditorKit 将生成超链接事件。 ...

      继续阅读这些文档。对于另一个答案中提到的提示。


      顺便说一句

        FileInputStream fstream = new FileInputStream("src\\html\\test.html");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        String text="";
        while ((strLine = br.readLine()) != null)   {
          text=text+strLine+"\n";
        }
        JEditorPane htmlPane = new JEditorPane("text/html",text);
      

      可以换成..

        File file = new File("src\\html\\test.html");
        JEditorPane htmlPane = new JEditorPane(file.toURI().toURL());
      

      【讨论】:

        【解决方案4】:

        您可以使用 dj 项目嵌入原生浏览器,这样您就可以渲染 html+js+css 并跟随链接甚至渲染 flash。 sourceforge.net/projects/djproject/

        【讨论】:

          猜你喜欢
          • 2023-03-20
          • 2012-09-13
          • 1970-01-01
          • 2010-10-02
          • 2023-03-17
          • 2011-01-20
          • 2011-01-02
          • 2014-07-05
          相关资源
          最近更新 更多