2013-03-25 49 views
2

我該如何做到這一點,滾動窗格始終位於正在寫入新數據的滾動窗格的底部?我看不到寫入的新文本。如何總是滾動到文本區域的底部?

JTextArea itTextArea = new JTextArea(10,80); 
new JScrollPane(itTextArea); 
xmlTextArea.setEditable(true); 

回答

6

這是我用:

DefaultCaret caret = (DefaultCaret) textArea.getCaret(); 
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 

這裏是你如何實現它:

public class Test 
{ 
    public static void createFrame() 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       try 
       { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       JPanel panel = new JPanel(); 
       panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
       panel.setOpaque(true); 
       JTextArea textArea = new JTextArea(15, 50); 
       textArea.setWrapStyleWord(true); 
       textArea.setEditable(false); 
       textArea.setFont(Font.getFont(Font.SANS_SERIF)); 
       JScrollPane scroller = new JScrollPane(textArea); 
       scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
       scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 
       JPanel inputpanel = new JPanel(); 
       inputpanel.setLayout(new FlowLayout()); 
       JTextField input = new JTextField(20); 
       JButton button = new JButton("Enter"); 
       DefaultCaret caret = (DefaultCaret) textArea.getCaret(); 
       caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 
       panel.add(scroller); 
       inputpanel.add(input); 
       inputpanel.add(button); 
       panel.add(inputpanel); 
       frame.getContentPane().add(BorderLayout.CENTER, panel); 
       frame.pack(); 
       frame.setLocationByPlatform(true); 
       frame.setVisible(true); 
       frame.setResizable(false); 
       input.requestFocus(); 
      } 
     }); 
    } 

    public static void main(String... args) 
    { 
     createFrame(); 
    } 
} 

那是什麼應該看起來l邁克:

enter image description here

+0

當然,你是假設插入符號是一個DefaultCaret,但不錯的想法不少於 – MadProgrammer 2013-03-25 20:11:19

+0

@MadProgrammer雅,我做了很多假設我可能不應該這樣做:P – syb0rg 2013-03-25 20:12:21

+1

我不喜歡卡雷特(13年來,從未有過這種需要),所以我可能會這樣做;) – MadProgrammer 2013-03-25 20:13:28

相關問題