我使用JEditorPane显示我机器上的html文件,这个html有一个名为&#34的链接;跳到主要内容"这将引导用户到同一页面的中间;但我希望它自动滚动到页面中间只是对话框设置可见,我尝试了JEditorPane.scrollToReference(),它不起作用。
任何人都可以提供帮助吗?
答案 0 :(得分:4)
在实现组件之前,无法调用scrollToReference()方法。这就是对话框已被打包或可见。
最简单的方法是将scrollToReference()方法包装成SwingUitilities.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();
}
});
}
}