这是一个教程示例,pnl.add(field); pnl.add(txtArea);未编译。为什么不?

import javax.swing.*;
import java.awt.event.*;

class KeyStrokes extends JFrame implements KeyListener {
    JPanel pnl = new JPanel();

    public static void main (String[] args) {
        KeyStrokes gui = new KeyStrokes();
    }

    JTextField field = new JTextField(38);
    JTextArea txtArea = new JTextArea(5, 38);
    pnl.add(field);
    pnl.add(txtArea);

    public KeyStrokes() {
        super("Swing Window");
        setSize(500, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(pnl);
        setVisible(true);
        field.addKeyListener(this);
    }

    public void keyPressed (KeyEvent event){
        txtArea.setText("Key Pressed");
    }

    public void keyTyped(KeyEvent event){
        txtArea.append("\nCharacter :" + event.getKeyChar());
    }

    public void keyReleased (KeyEvent event){
        int keyCode = event.getKeyCode();
        txtArea.append("\nKey Code :" + event.getKeyText(keyCode));
    }
}

最佳答案

那是因为您不能在方法之外进行这些语句,请注意,您可以在您所在的全局范围内声明变量。将其移动到KeyStrokes()语句之前的setVisible(true)方法中。然后KeyStrokes()将是这样的:

public KeyStrokes() {
    super("Swing Window");
    setSize(500, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(pnl);
    pnl.add(field);
    pnl.add(txtArea);
    setVisible(true);
    field.addKeyListener(this);
}

07-24 15:27