简体   繁体   中英

Input for JTextArea

Is there any way that if the char typed is not 'x' , for example. Than take no action at all. Code:

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)
             { 
             } 

You are much better off not using a KeyListener at all within Swing text components as this can interfere with the basic underlying operation of this component. Also a KeyListener will not have any effect on text added or removed by any other means, such as by cut and paste. Much better to use a higher level type of listener.

For instance, if you want to be notified of any text changes, either input or removal then you would want to use a DocumentListener as this will notify you of any changes to the text, be it from key input or from cut and paste.

If on the other hand you want to filter text input and even prevent certain text input, then attach a DocumentFilter to the JTextArea's Document.

For instance, you could place in your DocumentFilter a String#replaceAll(...) that removes all non-X chars from a String. The regex "[^xX]" would work well for this.

eg,

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);
    }
}

Yes. You have already the answer within your own question. The following explains it why. Alternatively, you can add this to keyPressed() , which is semantically the same to your variant:

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

To make it do nothing, you need to leave an empty body - what you have done an example of. Then it meets the criterion and goes inside the body and does nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM