为什么这不起作用 制作了JFrame并且绘画工作正常但我无法使用keylistener。我曾尝试在keylistener中打印一些内容,但是当按下左箭头时它没有显示。
import java.awt.event.KeyEvent;
public class movingsquare extends runpaintgui{
public void key(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 5;
repaint();
System.out.println( x);
}
}
}
其他班级
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class runpaintgui extends JFrame{
int x = 30;
public static void main(String[] args){
runpaintgui frame = new runpaintgui();
frame.setSize(1275, 775);
frame.setResizable(false);
frame.setTitle("game");
frame.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.fill3DRect(x, 30, 60, 60, true);
}
}
答案 0 :(得分:1)
以这种方式更改您的代码:
package de.swisslife.muellerj.test;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class runpaintgui extends JFrame implements KeyListener{
public runpaintgui(){
this.setSize(1275, 775);
this.setResizable(false);
this.setTitle("game");
this.setVisible(true);
this.addKeyListener(this);
this.setVisible(true);;
}
int x = 30;
public static void main(String[] args){
runpaintgui runpaintgui = new runpaintgui();
}
public void paint(Graphics g){
super.paint(g);
g.fill3DRect(x, 30, 60, 60, true);
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 5;
repaint();
System.out.println( x);
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
答案 1 :(得分:0)
首先,我没有主程序的子类实现。
我不确定你想在你的程序中做什么,但你可能只需要实现这样一个关键的监听器:
public class Test extends JFrame {
static int x = 30;
public static void main(String[] args) {
final Test frame = new Test();
frame.setSize(1275, 775);
frame.setResizable(false);
frame.setTitle("game");
frame.setVisible(true);
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 5;
frame.repaint();
System.out.println( x);
}
}
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyPressed(KeyEvent arg0) {}
});
}
public void paint(Graphics g) {
super.paint(g);
g.fill3DRect(x, 30, 60, 60, true);
}
}