2013-11-24 130 views
1

我正在使用Swing進行命令提示。我正在使用可編輯的JTextArea作爲輸入,但我不想在輸入可編輯之前將其區域化(C:\Windows\system32>)。圍繞Java中的不可編輯文本編輯可編輯的JTextArea

我知道這一點的唯一方法可以做到這一點是這樣的:Make parts of a JTextArea non editable (not the whole JTextArea!)

是否有其他方法嗎?

+0

我不知道,如果你談論的是隻在文本的開頭有沒有編輯的文本區域或文本區域的每一行。根據要求,答案會有所不同。 – camickr

+0

只是開始。 –

回答

2

剛開始的時候

然後,你可以這樣做:

import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.text.*; 

public class NavigationFilterPrefixWithBackspace extends NavigationFilter 
{ 
    private int prefixLength; 
    private Action deletePrevious; 

    public NavigationFilterPrefixWithBackspace(int prefixLength, JTextComponent component) 
    { 
     this.prefixLength = prefixLength; 
     deletePrevious = component.getActionMap().get("delete-previous"); 
     component.getActionMap().put("delete-previous", new BackspaceAction()); 
     component.setCaretPosition(prefixLength); 
    } 

    public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) 
    { 
     fb.setDot(Math.max(dot, prefixLength), bias); 
    } 

    public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) 
    { 
     fb.moveDot(Math.max(dot, prefixLength), bias); 
    } 

    class BackspaceAction extends AbstractAction 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      JTextComponent component = (JTextComponent)e.getSource(); 

      if (component.getCaretPosition() > prefixLength) 
      { 
       deletePrevious.actionPerformed(null); 
      } 
     } 
    } 

    public static void main(String args[]) throws Exception { 

     JTextField textField = new JTextField("Prefix_", 20); 
     textField.setNavigationFilter(new NavigationFilterPrefixWithBackspace(7, textField)); 

     JFrame frame = new JFrame("Navigation Filter Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(textField); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
}