3
我試圖在我的軟件中構建一個簡單的幫助系統。
從JEditorPane構建的幫助系統(用HTML文件加載)包裝在JScrollPane內部,在同一個窗口內部有一個JLabel。
當用戶將鼠標移到特定單詞上的JEditorPane上時--JLabel中會出現更多解釋。Java:JEditorPane在JScrollPane內部的奇怪行爲
我成功做它,但問題是,由於某種原因,它的文本的開始只是工作。(HTML文件很長,必須滾動...)
後,我向下滾動頁面並徘徊在一個字,它扔我BadLocationException
。
在下面的代碼中有一個JEditorPane包裝在JScrollPane中。
當用戶移動鼠標時,它會打印鼠標指向的當前字母。 (在幫助系統上,我找到這個位置的單詞的值,並根據它向JLabel打印解釋)
但是,正如我所說的那樣,它只是在文本的開始處起作用。
爲什麼?
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Point;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
public class JEditorPaneTestApp extends JFrame {
private JEditorPane editorPan;
private JScrollPane scrollPan;
public JEditorPaneTestApp() {
super();
try {
editorPan = new javax.swing.JEditorPane("file:///path/toHTML/file/helpFile.html");
}
catch (IOException e) {e.printStackTrace();}
scrollPan = new JScrollPane(editorPan);
this.add(scrollPan);
editorPan.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
Point p = new Point(evt.getX(), evt.getY());
int pos = editorPan.viewToModel(p);
try {
System.out.println(editorPan.getText(pos--, pos).charAt(0));
}
catch (BadLocationException e1) {
System.out.println("Invalid location");/* e1.printStackTrace();*/
}
}
});
scrollPan.setViewportView(editorPan);
this.add(scrollPan);
//
this.getContentPane().setLayout(new LayoutManager() {
@Override public Dimension preferredLayoutSize(Container arg0) {return null;}
@Override public Dimension minimumLayoutSize(Container arg0) {return null;}
@Override public void removeLayoutComponent(Component arg0) {}
@Override public void addLayoutComponent(String arg0, Component arg1) {}
@Override public void layoutContainer(Container conter) {
scrollPan.setBounds(0, 0, conter.getWidth(), conter.getHeight());
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
JEditorPaneTestApp test = new JEditorPaneTestApp();
}
}
感謝
如此簡單,如此真實,非常感謝!!!!! – Arnon 2011-02-26 03:55:49