作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试向 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
}
}
}
最佳答案
nested类 AL
需要是静态的。除非出于某种原因需要导出该类,否则它应该是 private
。
private static class AL implements DocumentListener {…}
关于java - 如何将文档监听器添加到 JScrollPane 内的 JTextArea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22883951/
我是一名优秀的程序员,十分优秀!