从 JTextArea 获取密钥 [英] Get a key from JTextArea

查看:22
本文介绍了从 JTextArea 获取密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是,如果我在 JtextArea 中按 '{' 这个键.自动 '}' 这也将被打印.

All I want to do, If I'm pressing '{' this key in JtextArea.automatically '}' this will be print also.

 if(evt.KEY_PRESSED == '{')

            System.out.print("}");

这样好吗??

推荐答案

为了监听 JTextComponent 的变化,是否有 DocumentListener,如果你需要控制输入的 Char、sings、空格字符或单词,你必须实现 DocumentFilter

for listening changes into JTextComponent is there DocumentListener, if you have to need control over inputed Char, sings, whitespace chars or word(s) you have to implements DocumentFilter

注意编程语言保留的字符,您必须使用双转义,

notice for Chars reservated by programing language(s) you have to use double escapes,

\( 而不是 (

\{ 而不是 {

否则你会得到

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("
")) {
            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);
            }
        });
    }
}

这篇关于从 JTextArea 获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆