我正在尝试通过面板进行图形移动,但我有其他人在一条移动的导线中从一侧移到另一侧第一个问题是不同步的,第二个问题没有移动任何人都知道如果我做线程,如何使它变为sincronize分开并让它移动谢谢
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
}
}
}
答案 0 :(得分:2)
使用Swing Timer代替Runnable#Thread
停靠Thread.sleep(int)
覆盖JPanel的getPreferredSize
而不是setPreferredSize(new Dimension(420, 420));
paintComponent
/ getHeight
Wieght
内的所有坐标
否则您(KeyEvents
启用Container
)setFocusable()
必须JPanel
,
第一。代码行应在super.paintComponent
public synchronized void paintComponent(Graphics g) {
您无法对g = this.getGraphics()
;进行编码,一切都可以完成paintComponent
使用JFrame.pack();
代替ven.setSize(460, 430)
;在您为JPanel
getPreferredSize
的情况下
Thread.sleep(10);
a)Native OS中的延迟超载延迟
b)阻止Event Dispatch Thread,我建议再次使用Swing Timer
将所有内容(不包括Swing Timer)放在一起 - for example