gpt4 book ai didi

java - 让它们移动并同步

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

我正在尝试使图形在面板中移动,但我还有其他人在从一侧移动到另一侧的线中,第一个问题不同步,第二个问题不移动,如果我做线程,任何人都知道如何使其同步分开并使其移动谢谢

public class caminos extends JPanel implements Runnable {
int x1 = 0;
int y1 = 50;
int x2 = 400;
int y2 = 150;
int x3 = 0;
int y3 = 250;
int x = 200;
int y = 350;
int velX = 3;
int velXX = -3;
public boolean corren = true;
Thread threadprincipal;

caminos() {
setPreferredSize(new Dimension(420, 420));
addKeyListener(new personaje(this));

threadprincipal = new Thread(this);
threadprincipal.start();

}

public void up() {
y = y - 3;
}

public synchronized void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, 460, 450);

g.setColor(Color.red);
g.fillRect(x1, y1, 40, 40);

g.setColor(Color.blue);
g.fillRect(x2, y2, 40, 40);

g.setColor(Color.green);
g.fillRect(x3, y3, 40, 40);

}// this is the problem is not synchronized and does not move

private synchronized void render() {

Graphics g;
g = this.getGraphics();

if (g != null) {
g.setColor(Color.orange);
g.fillRect(x, y, 30, 30);

Toolkit.getDefaultToolkit().sync();
}
}

public void run() {

while (corren) {
render();

x1 = x1 + velX;
x3 = x3 + velX;
x2 = x2 + velXX;

if (x1 < 0 || x1 > 400) {
velX = -velX;
}

if (x2 <= 0 || x2 > 400) {
velXX = -velXX;
}

try {
Thread.sleep(10);
} catch (Exception e) {
}
//
repaint();
}
// x1=x1+velX;
// x3=x3+velX;
// x2=x2-3;
}

public static void main(String[] args) {

JFrame ven = new JFrame();
ven.setSize(460, 430);
ven.setTitle("game");
ven.add(new caminos());
ven.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ven.setVisible(true);
}

// another class to move
class personaje implements KeyListener {

caminos game;

personaje(caminos passjuego) {
game = passjuego;
}

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
game.up();
}
}

public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}
}
}

最佳答案

  • 使用Swing Timer而不是由 Thread.sleep(int) 停止的 Runnable#Thread

  • 阅读 Java Naming Convention

  • 覆盖 JPanelgetPreferredSize而不是 setPreferredSize(new Dimension(420, 420));

  • paintComponent 内的所有坐标均可通过 getHeight/Wieght

    访问
  • 使用KeyBindings而不是KeyListener

  • 否则您(为Container启用KeyEvents)必须为JPanelsetFocusable()

  • 第一。代码行应该是 super.paintComponentpublic synchronized void PaintComponent(Graphics g) {

  • 你不能编写代码g = this.getGraphics();,一切都可以paintComponent

  • 参见Initial Thread

  • 使用JFrame.pack();而不是ven.setSize(460, 430);如果您覆盖 JPanelgetPreferredSize

  • Thread.sleep(10);

    a) native 操作系统中的延迟过载延迟非常短

    b) 区 block Event Dispatch Thread ,我建议再次使用 Swing Timer

  • 将所有内容(不包括 Swing Timer)放在一起 - for example

关于java - 让它们移动并同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20872443/

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