使用 JTextArea 模拟文本控制台

发布于 2024-09-26 18:07:18 字数 3009 浏览 3 评论 0原文

我的目标是在 Java 中获得一个类似控制台的组件,不一定是在 JTextArea 中,但这似乎是首先尝试的合乎逻辑的事情。输出很简单,使用 JTextArea 提供的方法,但输入是另一回事。我想拦截输入,并逐个字符地对其进行操作。我发现了一些使用 DocumentListener 来处理模糊相关的示例,但它似乎不允许我轻松检查刚刚输入的内容,而这正是我需要决定如何对其采取行动的内容。

我的做法正确吗?有更好的方法吗?

我附上了我的应用程序代码的相关部分。

public class MyFrame extends JFrame {
    public MyFrame() {
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
        int x=(int)(frameSize.width/2);
        int y=(int)(frameSize.height/2);
        setBounds(x,y,frameSize.width,frameSize.height);


        console = new JTextArea("",25,80);
        console.setLineWrap(true);
        console.setFont(new Font("Monospaced",Font.PLAIN,15));
        console.setBackground(Color.BLACK);
        console.setForeground(Color.LIGHT_GRAY);
        console.getDocument().addDocumentListener(new MyDocumentListener());

        this.add(console);

    }

    JTextArea console;

}

class MyDocumentListener implements DocumentListener
{
    public void insertUpdate(DocumentEvent e)
    {
        textChanged("inserted into");
    }
    public void removeUpdate(DocumentEvent e)
    {
        textChanged("removed from");
    }
    public void changedUpdate(DocumentEvent e)
    {
        textChanged("changed");
    }
    public void textChanged(String action)
    {
        System.out.println(action);
    }
}

感谢您的任何帮助。

EDIT1:我尝试使用带有 DocumentFilter 的 JTextPane 来执行此操作,但是当我输入某些内容时,DocumentFilter 中的方法不会运行。我附上修改后的代码:

public class MyFrame extends JFrame {
    public MyFrame() {
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
        int x=(int)(frameSize.width/2);
        int y=(int)(frameSize.height/2);
        setBounds(x,y,frameSize.width,frameSize.height);

        console = new JTextPane();
        //console.setLineWrap(true);
        console.setFont(new Font("Monospaced",Font.PLAIN,15));
        console.setBackground(Color.BLACK);
        console.setForeground(Color.LIGHT_GRAY);
        StyledDocument styledDoc = console.getStyledDocument();
            if (styledDoc instanceof AbstractDocument) {
            doc = (AbstractDocument)styledDoc;
            doc.setDocumentFilter(new DocumentSizeFilter());
        }

        this.add(console);

    }

    JTextPane console;
    AbstractDocument doc;

}

class DocumentSizeFilter extends DocumentFilter {

        public DocumentSizeFilter() {

    }

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
        System.out.println(str);
        if (str.equals("y")) {
            System.out.println("You have pressed y.");
        }
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)  throws BadLocationException {

    }

}

My objective here is to obtain a console-like-behaving component in Java, not necessarily in JTextArea, but this seemed like a logical thing to try first. Output is simple enough, using the methods provided by the JTextArea, but input is another thing. I want to intercept input, and act on it - character by character. I've found some examples on using a DocumentListener for something vaguely related, but it doesn't seem to allow me to easily check what was just typed in, which is what I need to decide how to act upon it.

Am I going about this correctly? Is there a better method for this?

I enclose the pertinent parts of my application code.

public class MyFrame extends JFrame {
    public MyFrame() {
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
        int x=(int)(frameSize.width/2);
        int y=(int)(frameSize.height/2);
        setBounds(x,y,frameSize.width,frameSize.height);


        console = new JTextArea("",25,80);
        console.setLineWrap(true);
        console.setFont(new Font("Monospaced",Font.PLAIN,15));
        console.setBackground(Color.BLACK);
        console.setForeground(Color.LIGHT_GRAY);
        console.getDocument().addDocumentListener(new MyDocumentListener());

        this.add(console);

    }

    JTextArea console;

}

class MyDocumentListener implements DocumentListener
{
    public void insertUpdate(DocumentEvent e)
    {
        textChanged("inserted into");
    }
    public void removeUpdate(DocumentEvent e)
    {
        textChanged("removed from");
    }
    public void changedUpdate(DocumentEvent e)
    {
        textChanged("changed");
    }
    public void textChanged(String action)
    {
        System.out.println(action);
    }
}

Thanks for any help.

EDIT1: I have attempted to do this using a JTextPane with a DocumentFilter, but when I input something, the method in the DocumentFilter isn't getting run. I enclose the modified code:

public class MyFrame extends JFrame {
    public MyFrame() {
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
        int x=(int)(frameSize.width/2);
        int y=(int)(frameSize.height/2);
        setBounds(x,y,frameSize.width,frameSize.height);

        console = new JTextPane();
        //console.setLineWrap(true);
        console.setFont(new Font("Monospaced",Font.PLAIN,15));
        console.setBackground(Color.BLACK);
        console.setForeground(Color.LIGHT_GRAY);
        StyledDocument styledDoc = console.getStyledDocument();
            if (styledDoc instanceof AbstractDocument) {
            doc = (AbstractDocument)styledDoc;
            doc.setDocumentFilter(new DocumentSizeFilter());
        }

        this.add(console);

    }

    JTextPane console;
    AbstractDocument doc;

}

class DocumentSizeFilter extends DocumentFilter {

        public DocumentSizeFilter() {

    }

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
        System.out.println(str);
        if (str.equals("y")) {
            System.out.println("You have pressed y.");
        }
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)  throws BadLocationException {

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

他不在意 2024-10-03 18:07:18

我想拦截输入,并采取行动

您可能应该使用 DocumentFilter。有关详细信息,请参阅实现文档过滤器

I want to intercept input, and act on
it

Then you should probably be using a DocumentFilter. See Implementing a Document Filter for more information.

猥琐帝 2024-10-03 18:07:18

似乎有很多不同的方法来自定义 Swing 文本组件。当我做了与你类似的事情时,我成功地使用了自定义文档:

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

public class CustomDocument extends PlainDocument {
    @Override
    public void insertString(int offset, String string, AttributeSet attributeSet) throws BadLocationException {
        // Parse input - in this case convert everything to upper case
        string = string.toUpperCase();
        super.insertString(offset, string, attributeSet);
    }
}

这是能够测试代码的主要方法:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 300, 300);
    frame.add(new JTextArea(new CustomDocument()));
    frame.setVisible(true);
}

There seems to be lots of different ways to customise Swing text components. When I did something similar to you I had success with a custom Document:

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

public class CustomDocument extends PlainDocument {
    @Override
    public void insertString(int offset, String string, AttributeSet attributeSet) throws BadLocationException {
        // Parse input - in this case convert everything to upper case
        string = string.toUpperCase();
        super.insertString(offset, string, attributeSet);
    }
}

Here is a main method to be able to test the code:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100, 100, 300, 300);
    frame.add(new JTextArea(new CustomDocument()));
    frame.setVisible(true);
}
桃酥萝莉 2024-10-03 18:07:18

我在我构建的应用程序中使用文本区域作为控制台,该应用程序将对 jar 文件进行签名。 JTextArea 有一个append() 方法。

Jar Signer

JTextArea console=new JTextArea();
console.append("Insert console text here \n") \\  \n for new line

I'm using a text area as a console in an app I built which will sign a jar file. JTextArea has an append() method.

Jar Signer

JTextArea console=new JTextArea();
console.append("Insert console text here \n") \\  \n for new line
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文