Swing KeyLintener键盘事件监听

package Assis;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class TestEvent extends JFrame {
	private static final long serialVersionUID = 1L;

	public TestEvent() {
		setSize(400, 300);
		// addKeyListener(new Listener());
		P p1 = new P();
		System.out.println(p1.isFocusable());
		p1.setFocusable(true);
		p1.setBackground(Color.red);
		this.getContentPane().add(BorderLayout.NORTH, p1);

		P p2 = new P();
		p2.setBackground(Color.green);
		this.getContentPane().add(BorderLayout.SOUTH, p2);

		setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public static void main(String[] args) {
		new TestEvent();
	}
}

class P extends JPanel {
	private static final long serialVersionUID = 1L;

	public P() {
		addKeyListener(new Listener());

		this.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				System.out.println(e);
			}
		});
	}
}

class Listener implements KeyListener {
	public void keyPressed(KeyEvent e) {
		System.out.println("---" + e);
	}

	public void keyReleased(KeyEvent e) {
		
	}

	public void keyTyped(KeyEvent e) {
		
	}
}

 

你可能感兴趣的:(java,swing)