Login: password:
Forgot your password?
Programmazione 2 - a.a. 2012/13
Intercettazione tasti

package it.unitn.prog2.keybindingdemo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.*;
/* Usare il tab per fare ciclare il focus tra le componenti */
public class KeyBindingDemo {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new KeyBindingDemo();
}

KeyBindingDemo() {
JFrame f = new JFrame();
f.setSize(400, 400);
JPanel p = (JPanel) (f.getContentPane());
p.setLayout(new BorderLayout());
//====================================
AbstractAction enterAction = new AbstractAction() {
public void actionPerformed(ActionEvent tf) {
System.out.println("The Enter key has been pressed in "+tf.getSource().getClass().toString());

}
};
//====================================
AbstractAction enterAction2 = new AbstractAction() {
public void actionPerformed(ActionEvent tf) {
System.out.println("The Enter key has been pressed on the yellow panel ");

}
};
p.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
p.getActionMap().put("doEnterAction", enterAction);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton b=new JButton();
b.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
b.getActionMap().put("doEnterAction", enterAction);
p.add(b,BorderLayout.NORTH);
//--------------------
JPanel ip=new JPanel();
ip.setBackground(Color.yellow);
ip.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
ip.getActionMap().put("doEnterAction", enterAction2);
p.add(ip,BorderLayout.CENTER);
//--------------------
JTextField tf=new JTextField();
p.add(tf,BorderLayout.SOUTH);
tf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
tf.getActionMap().put("doEnterAction", enterAction);
f.setVisible(true);
}
}



class MyPanel extends JPanel implements KeyListener {
private char c = 'e';

public MyPanel() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
}

public void addNotify() {
super.addNotify();
requestFocus();
}

public void paintComponent(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
g.drawString("the key that pressed is " + c, 250, 250);
}

public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) {
c = e.getKeyChar();
repaint();
}

public static void main(String[] s) {
JFrame f = new JFrame();
f.getContentPane().add(new MyPanel());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}

tratto da stackoverflow



powered by segue
segue_logo