【问题标题】:How JEditorPane scroll to specified HTML linkJEdi​​torPane 如何滚动到指定的 HTML 链接
【发布时间】:2013-05-31 14:38:11
【问题描述】:

我使用 JEditorPane 在我的机器上显示一个 html 文件,这个 html 有一个名为“skip to main content”的链接,它将引导用户到同一页面的中间;但我希望它在对话框设置为可见的情况下自动滚动到页面中间,我尝试了 JEditorPane.scrollToReference(),它不起作用。

有人可以帮忙吗?

【问题讨论】:

    标签: java html swing jscrollpane jeditorpane


    【解决方案1】:

    在实现组件之前,您不能调用 scrollToReference() 方法。那就是对话框已被打包或可见。

    执行此操作的最简单方法是将 scrollToReference() 方法包装为 SwingUtilities.invokeLater。比如:

    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    
    public class EditorPaneScroll extends JPanel 
    {
        private JEditorPane html;
    
        public EditorPaneScroll()
        {
            setLayout( new BorderLayout() );
            String text = "<html>one<br>two<br><a name =\"three\"></a>three<br>four<br>five<br>six<br>seven<br>eight<br>nine<br>ten</html>";
            StringReader reader = new StringReader(text);
    
            html = new JEditorPane();
            html.setContentType("text/html");
    
            try
            {
                html.read(reader, null);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
    
            JScrollPane scrollPane = new JScrollPane( html );
            scrollPane.setPreferredSize( new Dimension(400, 100) );
            add( scrollPane );
    
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    html.scrollToReference("three");
                }
            });
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("EditorPaneScroll");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new EditorPaneScroll() );
            frame.pack();
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 2011-04-11
      • 2013-01-29
      • 2011-06-06
      • 2013-05-02
      • 2011-08-20
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多