gpt4 book ai didi

java - KeyAdapter 监听器,没有任何反应

转载 作者:行者123 更新时间:2023-11-30 11:28:09 25 4
gpt4 key购买 nike

我目前正在编写一个小程序,我应该在其中使用基本转换。现在,我正在研究如何使用箭头键移动多边形。现在我可以通过按鼠标将其向右移动,但我更愿意使用向右箭头键。但是,无论我尝试哪种方法,我都无法做到。

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JPanel;


class PolygonPanel extends JPanel implements MouseListener{
Polygon p;
public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
addKeyListener(new MKeyListener());
}

class MKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode==e.VK_RIGHT){
System.out.println("FFFFUUUUU");
}
}
}


public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.white);
g.fillPolygon(p);
}

@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("hei");
for (int i = 0; i < p.npoints; i++) {
p.xpoints[i] = p.xpoints[i]+10;
repaint();
}

}

@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub

}
}

class PolygonFrame extends JFrame{
public PolygonFrame(){
setTitle("Polygoner");
setSize(700, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add(new PolygonPanel());
}
}

public class Polygonfun {
public static void main(String[] args) {
JFrame frame = new PolygonFrame();
frame.setVisible(true);
}

}

当我按向右箭头键时没有任何反应。我也试过这样实现它:

class PolygonPanel extends JPanel implements MouseListener,KeyAdapter

然后添加未实现的方法,但这也不起作用。我知道我可能忽略了一些东西,但我似乎无法弄清楚。有什么建议吗?

谢谢

最佳答案

为您的面板设置 this.setFocusable(true);

应该是:

public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
this.setFocusable(true);
this.addKeyListener(new MKeyListener());
}

关于java - KeyAdapter 监听器,没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19005589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com