gpt4 book ai didi

java - 如何将文档监听器添加到 JScrollPane 内的 JTextArea?

转载 作者:行者123 更新时间:2023-11-29 07:48:56 25 4
gpt4 key购买 nike

我正在尝试向 JTextArea 添加一个文档监听器,这样当用户按下回车键时,它将读取最后一行/自新行以来的字符。

我尝试了以下代码,但 Eclipse 不喜欢 display.getDocument().addDocumentListener(new AL());。它说

No enclosing instance of type ScrollingTextArea is accessible. Must qualify the allocation with an enclosing instance of type ScrollingTextArea (e.g. x.new A() where x is an instance of ScrollingTextArea).

如何向 JTextArea 添加 Action 监听器?

代码:

package guis;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class ScrollingTextArea {

public static void main ( String[] args )
{
JPanel middlePanel = new JPanel ();
middlePanel.setBorder(new TitledBorder(new EtchedBorder (), "Display Area" ) );

// create the middle panel components

JTextArea display = new JTextArea(16,58 );
JScrollPane scroll = new JScrollPane(display);

display.getDocument().addDocumentListener(new AL());
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

//Add Textarea in to middle panel
middlePanel.add(scroll);

JFrame frame = new JFrame();
frame.add( middlePanel );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class AL implements DocumentListener {


@Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub

}

@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub

}

@Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub

}
}
}

最佳答案

nestedAL 需要是静态的。除非出于某种原因需要导出该类,否则它应该是 private

private static class AL implements DocumentListener {…}

关于java - 如何将文档监听器添加到 JScrollPane 内的 JTextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22883951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com