Моя цель здесь - получить компонент, похожий на консольный, в 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: я пытался сделать это, используя JTextPane с DocumentFilter, но когда я что-то вводил, метод в 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 {
}
}