首先得让JLabel能够接收键盘事件,使用setFocusable setFocusablepublic void setFocusable(boolean focusable) Sets the focusable state of this Component to the specified value. This value overrides the Component's default focusability. Parameters: focusable - indicates whether this Component is focusable Since: 1.4 See Also: isFocusable()
setFocusablepublic void setFocusable(boolean focusable) Sets the focusable state of this Component to the specified value. This value overrides the Component's default focusability. Parameters:
focusable - indicates whether this Component is focusable
Since:
1.4
See Also:
isFocusable()
用JPanel 然后添加JLable比较好可以用接口来实现
新建一个类继承JLable implements ItemListener, MouseListener, FocusListener, KeyListener, ActionListener想要什么有什么,哈哈
KeyStroke up = KeyStroke.getKeyStroke(KeyEvent.VK_UP,0);
InputMap inputmap= panel.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionmap = panel.getActionMap();
inputmap.put(up,"up");
actionmap.put("up",new upAction(this));
class upAction extends AbstractAction{
public upAction(){
}
public void actionPerformed(ActionEvent e) {
//你的响应
}
}
其中panel一般是你的contentPane,即获得焦点的panel。
jlable.addActionListener(new KeyListener(){
public void actionPerformed(ActionEvent e) {
//你的响应
}
});
package layout.test;import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;public class OverlayTest { public static void main(String args[]) {
JFrame f = new JFrame();
final JLabel lbl = new JLabel("Hello");
lbl.setBorder(BorderFactory.createLineBorder(Color.red, 10));
lbl.setFocusable(true);
lbl.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
//
lbl.setText(String.valueOf(e.getKeyChar()));
}
}); f.getContentPane().add(lbl);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
//exp:覆盖里面的类即可
public void mousePressed(MouseEvent e){
if(e.getClickCount() >= 2){
System.out.println(">>>>>>>");
}
}});