2012-02-24 133 views
1

我想要做的所有事情如果我在JtextArea.automatically'}'中按'{'這個鍵,那麼這也將是打印。從JTextArea獲取密鑰

if(evt.KEY_PRESSED == '{') 

      System.out.print("}"); 

這是好嗎?

+0

不太清楚你要實現的目標是什麼。你嘗試過這個嗎?究竟是什麼問題? – DNA 2012-02-24 10:58:41

+0

@Adnan:你想要實現的內容必須在keyReleased()方法內完成,而不是keyPressed(),像這樣public void keyReleased(KeyEvent ke){if(ke.getKeyCode()== 91){System.out .println(KeyEvent.VK_BRACELEFT); int len = tarea.getDocument()。getLength(); tarea.append(「}」);}}。那麼只有你會得到你的輸出。此外,「@mKorbel」告訴你這是Swing的新方式。 KeyListener不適用於Swing。 – 2012-02-24 16:25:55

回答

3

聽變爲JTextComponent是那裏的DocumentListener,如果您必須控制輸入的字符,唱歌,空格字符或單詞,以實現DocumentFilt呃

通知由編程語言(S),你必須使用雙逃逸reservated個字符,

\\(而不是(

\\{,而不是{

否則你

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: 
Illegal repetition 

例如

import java.awt.*; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.*; 
import javax.swing.event.*; 
import javax.swing.text.*; 

public class TextAreaTest extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private JTextArea textArea; 

    public TextAreaTest() { 
     textArea = new JTextArea(); 
     textArea.setPreferredSize(new Dimension(60, 32)); 
     textArea.setOpaque(true); 
     textArea.setLineWrap(true); 
     textArea.setWrapStyleWord(true); 
     ((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() { 

      @Override 
      public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { 
       string = string.replaceAll("\\{", "\\{}"); 
       super.insertString(fb, offset, string, attr); 
      } 

      @Override 
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { 
       text = text.replaceAll("\\{", "\\{}"); 
       //TODO must do something here 
       super.replace(fb, offset, length, text, attrs); 
      } 
     }); 

     textArea.getDocument().addDocumentListener(new DocumentListener() { 

      @Override 
      public void changedUpdate(DocumentEvent e) { 
       update(e); 
      } 

      @Override 
      public void insertUpdate(DocumentEvent e) { 
       update(e); 
      } 

      @Override 
      public void removeUpdate(DocumentEvent e) { 
       update(e); 
      } 

      private void update(DocumentEvent e) { 
       List<String> lines = getLines(textArea); 
       String lastLine = lines.get(lines.size() - 1); 
       int tabbedTextWidth = Utilities.getTabbedTextWidth(new Segment(
         lastLine.toCharArray(), 0, lastLine.length()), textArea.getFontMetrics(textArea.getFont()), 0, null, 0); 
       int lineHeight = getLineHeight(textArea); 
       if (lines.size() * lineHeight > textArea.getHeight() || tabbedTextWidth > textArea.getWidth()) { 
        System.out.println("Too big! Should refuse the update!"); 
       } 
      } 
     }); 

     getContentPane().add(textArea); 
    } 

    private static List<String> getLines(JTextArea textArea) { 
     int lineHeight = getLineHeight(textArea); 
     List<String> list = new ArrayList<String>(); 
     for (int num = 0;; num++) { 
      int i = textArea.viewToModel(new Point(0, num * lineHeight)); 
      int j = textArea.viewToModel(new Point(0, (num + 1) * lineHeight)); 
      if (i == 0 && j == 0) { 
       continue; 
      } 
      if (textArea.getDocument().getLength() == i && i == j) { 
       break; 
      } 
      String s = removeTrailingNewLine(textArea.getText().substring(i, j)); 
      list.add(s); 
      //System.out.println(i + " " + j + " = " + s); 
     } 
     return list; 
    } 

    private static int getLineHeight(JTextArea textArea) { 
     return textArea.getFontMetrics(textArea.getFont()).getHeight(); 
    } 

    private static String removeTrailingNewLine(String s) { 
     if (s.endsWith("\n")) { 
      return s.substring(0, s.length() - 1); 
     } else { 
      return s; 
     } 
    } 

    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       TextAreaTest test = new TextAreaTest(); 
       test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       test.pack(); 
       test.setVisible(true); 
      } 
     }); 
    } 
} 
+0

太複雜了,但在DocumentFilter類中得到了這個想法。 +1爲此:-) – 2012-02-24 16:23:22

+0

嗯我認爲沒有另一種,最簡單和更快的方式 – mKorbel 2012-02-24 16:25:08

0

我認爲這是你正在尋找

if(evt.getID() == evt.KEY_PRESSED) { 

    if(evt.getKeyChar() == '{') { 
     System.out.print("}"); 
    } 
} 

測試什麼,以及工作

+0

不工作。但是,我看起來像這樣 – Adnan 2012-02-24 11:30:14

+0

我編輯了答案,現在它應該可以工作 – Zhertal 2012-02-24 12:23:12