目前我正在学习Java,而且我遇到了问题。
我试图抓住KeyEvent
,但它不起作用。
也许你们其中一个人有解决方案?
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SpielFenster extends JFrame implements KeyListener {
int posX = 100;
int posY = 100;
SpielFenster(){
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize( 400, 600 );
this.setTitle( "Hindi Bones - Lost in Labyrinth" );
this.setVisible( true );
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.ORANGE);
g.fillOval(posX, posY, 20, 20);
}
public void keyPressed(KeyEvent e) {
test("test");
}
public void keyReleased(KeyEvent e) { test("test");}
public void keyTyped(KeyEvent e) { test("test");}
public void test(String x){
System.out.println(x);
}
public static void main(String[] args){
SpielFenster fenster = new SpielFenster();
fenster.test("yoo");
}
}
提前致谢! :)
答案 0 :(得分:2)
因为你没有在任何摇摆组件上注册听众:
.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/base64.rb:58:in `decode64'
app/controllers/buy_tags_controller.rb:18:in `block in index'
app/controllers/buy_tags_controller.rb:13:in `each'
app/controllers/buy_tags_controller.rb:13:in `index'
actionpack (4.2.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.2.1) lib/abstract_controller/base.rb:198:in `process_action'
actionpack (4.2.1) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.2.1) lib/active_support/callbacks.rb:117:in `call'
答案 1 :(得分:1)
你忘了将keylistener添加到你拥有的任何JComponents中......
你唯一拥有的是JFrame,所以在JFrame中,在构造函数中这样做:
this.addKeyListener(this);
这里面是你的应用程序:
package alltests;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SpielFenster extends JFrame implements KeyListener{
int posX = 100;
int posY = 100;
SpielFenster(){
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize( 400, 600 );
this.setTitle( "Hindi Bones - Lost in Labyrinth" );
this.addKeyListener(this);//here <<<<<
this.setVisible( true );
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.ORANGE);
g.fillOval(posX, posY, 20, 20);
}
public static void main(String[] args){
SpielFenster fenster = new SpielFenster();
}
@Override
public void keyPressed(KeyEvent e) {
test("test");
}
@Override
public void keyReleased(KeyEvent e) {
test("test");
}
@Override
public void keyTyped(KeyEvent e) {
test("test");
}
public void test(String x){
System.out.println(x);
}
}
希望有所帮助