组件未添加到JPanel对象

时间:2016-05-13 15:08:19

标签: java swing compiler-errors jpanel

这是一个教程示例,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));
    }
}

1 个答案:

答案 0 :(得分:2)

那是因为你不能在方法之外创建这些语句,请注意你可以在你所在的全局范围内声明变量。将它移到KeyStrokes()方法,就在{{{}之前1}}陈述。然后setVisible(true)将是这样的:

KeyStrokes()