我的目标是在 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 {
}
}