2012-07-02 141 views
1

每次(第一次除外)我在JEditorPane滾動條中設置文本跳轉到JEditorPane的底部。有什麼辦法可以避免這種情況?我嘗試的一種方法是在setText()之後使用setCaretPosition(0)。它的作品,但它不是我所需要的。滾動條跳下來然後跳起來。有沒有辦法避免在settext()中移動滾動條?JScrollPane滾動條跳到JEditorPane.setText()

我的代碼:

package test; 

import javax.swing.JApplet; 
import javax.swing.JButton; 
import javax.swing.JEditorPane; 
import javax.swing.JScrollPane; 
import javax.swing.event.HyperlinkEvent; 
import javax.swing.event.HyperlinkListener; 

public class Test extends JApplet implements HyperlinkListener { 

    JEditorPane dataDisplayer = new JEditorPane(); 

    public void init() { 
     ataDisplayer.setEditable(false); 
     dataDisplayer.add(new JButton()); 
     dataDisplayer.setContentType("text/html"); 
     JScrollPane jsp = new JScrollPane(dataDisplayer); 
     dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla"); 
     this.dataDisplayer.addHyperlinkListener(this); 
     setContentPane(jsp); 
    } 

    @Override 
    public void hyperlinkUpdate(HyperlinkEvent arg0) { 
     dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla bla"); 

    } 

} 
+0

參見本[另類](HTTP:/ /stackoverflow.com/a/11299764/230513)。 – trashgod

回答

7

有不同的方法去與這一點。一個是簡單地避免尖知名度adjustement,像這樣:

import java.awt.Rectangle; 
import javax.swing.JButton; 
import javax.swing.JEditorPane; 
import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.SwingUtilities; 
import javax.swing.event.HyperlinkEvent; 
import javax.swing.event.HyperlinkListener; 
import javax.swing.text.DefaultCaret; 

public class TestEditorPane implements HyperlinkListener { 

    private final class MyCaret extends DefaultCaret { 

     @Override 
     protected void adjustVisibility(Rectangle nloc) { 

     } 

    } 

    JEditorPane dataDisplayer = new JEditorPane(); 
    private MyCaret caret; 

    @Override 
    public void hyperlinkUpdate(HyperlinkEvent arg0) { 
     dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla bla"); 

    } 

    public void init() { 
     JFrame frame = new JFrame(); 
     dataDisplayer.setEditable(false); 
     caret = new MyCaret(); 
     dataDisplayer.setCaret(caret); 
     dataDisplayer.add(new JButton()); 
     dataDisplayer.setContentType("text/html"); 
     JScrollPane jsp = new JScrollPane(dataDisplayer); 
     dataDisplayer.setText("<a href=''>Change Text</a><br><br><br><br><br><br><br><br><br><br>bla"); 
     this.dataDisplayer.addHyperlinkListener(this); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setContentPane(jsp); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new TestEditorPane().init(); 
      } 
     }); 
    } 
} 
0

下解決了這個問題對我來說,51分鐘的絕望後:

JEditorPane.grabFocus(); 
JEditorPane.setCaretPosition(20);