私は自分のソフトウェアに簡単なヘルプシステムを構築しようとしています。
JScrollPane内にラップされたJEditorPane(HTMLファイルでロード)から構築されたヘルプシステム。同じウィンドウ内にJLabelがあります。
ユーザーが特定の単語のJEditorPaneの上にマウスを移動すると、JLabelに詳細な説明が表示されます。
私はそれを成功させましたが、問題は、何らかの理由でテキストの先頭でのみ機能することです(HTMLファイルは長く、スクロールする必要があります...)
ページを下にスクロールして単語にカーソルを合わせた後、それは私を投げますBadLocationException
。
以下のコードには、JScrollPane内にラップされたJEditorPaneがあります。
ユーザーがマウスを動かすと、マウスが指している現在の文字が印刷されます。(ヘルプシステムでは、この位置で単語の値を見つけ、それに応じて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();
}
}
ありがとう