gpt4 book ai didi

java - java中如何避免形状超出框架的边界

转载 作者:行者123 更新时间:2023-12-01 21:50:11 28 4
gpt4 key购买 nike

我有这个程序,当按箭头键时它会超出框架。然而,我希望形状在超过该边界时反弹。谁能帮我解决这个问题。

  {
JFrame frame = new JFrame("PacMan");
PacManObject panel = new PacManObject();
panel.setFocusable(true);
panel.setRequestFocusEnabled(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setVisible(true);

frame.add(panel);
panel.addKeyListener(panel);


}

public static void main(String[] args) {
Runnable runnable = new Runnable(){

@Override
public void run() {
new PacMan();
}

};EventQueue.invokeLater(runnable);
}

class PacManObject extends JPanel implements KeyListener{

private int xLocation = 100;
private int yLocation = 100;
private int mouth = 280;
private int angle = 45;
private int xrandomLocation = 300;
private int yrandomLocation = 400;
private int xLocationEyes = 115;
private int yLocationEyes = 115;

我在哪里绘制形状

    @Override
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);

//pacman
graphics.setColor(Color.yellow);
graphics.fillArc(xLocation, yLocation, 100, 100, angle, mouth);

//eyes
graphics.setColor(Color.BLACK);
graphics.fillOval(xLocationEyes, yLocationEyes, 20, 20);
food(graphics);
}

按箭头键时

    @Override
public void keyPressed(KeyEvent keyboard) {

int keyboardPress = keyboard.getKeyCode();
if(keyboardPress == KeyEvent.VK_RIGHT){
xLocation += 30;
xLocationEyes += 30;
angle = 45;
repaint();
}
else if(keyboardPress == KeyEvent.VK_LEFT){

angle = -145;
xLocation -= 30;
xLocationEyes -= 30;
repaint();
}
}

最佳答案

放入范围检查,使用类似的东西

if (xLocation + 100 >= getWidth()) { 
xLocation = getWidth() - 100;
} else if (xLocation < 0) {
xLocation = 0;
}

您应该对 yLocation 执行相同的操作

一般来说,您应该有一个主/游戏循环,负责更新游戏的当前状态(基于输入的当前状态和其他要求(例如幽灵的 AI))并安排更新到用户界面。

这样,您可以在 key 处理程序中设置一个标志,主/游戏循环将检查该标志,更新玩家的状态并安排重绘。这克服了第一次按键事件和重复事件之间延迟的固有问题。

我还会考虑在 KeyListener 上使用键绑定(bind) API。

也许,看看 How to Use Key Bindings , How to use Swing TimersHow to eliminate delay in keyPress?获取更多想法

关于java - java中如何避免形状超出框架的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353226/

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