我下面的java代码正在尝试进行keyListener继承。问题是私有(private)静态JTextArea jt; CustomKeyListener 类中无法识别。我不知道我认为这两个类是通过 jt.addKeyListener(new CustomKeyListener()); 连接的但它没有被连接。我的代码无法编译。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text11 extends JFrame implements ActionListener{ /**
*
*/
private static final long serialVersionUID = 1L;
// JFrame
static JFrame f;
// text area
private static JTextArea jt;
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("textfield");
// create a label to display text
// create a object of the text class
text11 te = new text11();
// create a text area, specifying the rows and columns
jt = new JTextArea(" ", 20, 20);
JPanel p = new JPanel();
// add the text area and button to panel
p.add(jt);
f.add(p);
// set the size of frame
f.setSize(300, 300);
jt.addKeyListener(new CustomKeyListener());
f.show();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jt.addKeyListener(new CustomKeyListener());
}
}
class CustomKeyListener implements KeyListener{
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
jt.setText(jt.getText() + " sam");
}
}
public void keyReleased(KeyEvent e) {
}
}
最佳答案
这不是最佳实践,但您可以将 jt
更改为 public static JTextArea jt;
,然后在您的 CustomKeyListener
类中调用它text11.jt
例如:text11.jt.setText(text11.jt.getText() + "sam");
关于java - 识别文本区域对象时的 KeyListener 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62316369/