簡體   English   中英

JTextArea的輸入

[英]Input for JTextArea

例如,是否有任何方式可以輸入的字符不是'x' 比什么都不采取行動。 碼:

main_text_area.addKeyListener(new KeyListener()
         {
             public void keyTyped(KeyEvent e)
             {

             }

             public void keyPressed(KeyEvent e1)
             {

             char c ='x';
                 if!((e1.getKeyChar() == c))
                 {

                  //Do nothing at all

                 }
             }
             public void keyReleased(KeyEvent e2)
             { 
             } 

您最好不要在Swing文本組件中完全不使用KeyListener,因為這可能會干擾該組件的基本基礎操作。 另外,KeyListener不會對通過任何其他方式(例如,剪切和粘貼)添加或刪除的文本產生任何影響。 使用更高級別的偵聽器更好。

例如,如果您想收到任何文本更改(輸入或刪除)的通知,則您想使用DocumentListener,因為它會通知您文本的任何更改,無論是通過鍵盤輸入還是通過剪切和粘貼。

另一方面,如果您想過濾文本輸入甚至阻止某些文本輸入,則將DocumentFilter附加到JTextArea的Document。

例如,您可以在DocumentFilter中放置一個String#replaceAll(...) ,以從字符串中刪除所有非X字符。 正則表達式"[^xX]"可以很好地解決這個問題。

例如,

import javax.swing.*;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class DocFilterExample extends JPanel {
    private static final int ROWS = 30;
    private static final int COLS = 40;

    private JTextArea textArea = new JTextArea(ROWS, COLS);

    public DocFilterExample() {
        ((PlainDocument) textArea.getDocument()).setDocumentFilter(new XcharFilter());

        add(new JScrollPane(textArea));
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("DocFilterExample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DocFilterExample());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class XcharFilter extends DocumentFilter {
    private static final String REGEX = "[^xX]";

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        string = string.replaceAll(REGEX, "");
        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(REGEX, "");
        super.replace(fb, offset, length, text, attrs);
    }
}

是。 您已經在自己的問題中找到了答案。 以下說明其原因。 另外,您可以將其添加到keyPressed()這與您的變體在語義上是相同的:

if(!(e1.getKeyChar() == 'x')); //Does nothing, notice the ';'!
else {
    //Do something
}

要使其無所事事,您需要留下一個空的身體-您所做的一個例子。 然后,它符合標准並進入體內,什么也不做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM