我是Java图形和线程的新手,我正在尝试制作游戏(特别是Pong).这个想法是两个人可以在同一个键盘上玩(即有两个通过不同键控制的拨片).目前,两名球员不能同时移动他们的球拍.
这个问题有方法解决吗?单独的线程是答案吗?
如果可能的话,我希望桨能够同时移动(至少看似).
更新:似乎使用Set<Integer>存储按键是最好的选择.我已经完成了(并且它可以工作),但我想知道是否有任何此代码不在事件调度线程(EDT)上,如果我需要使用SwingUtilities.invokeLater();.这是必要的代码:
private Set<Integer> keysDown = Collections.synchronizedSet(new HashSet<Integer>());
public void keyPressed(KeyEvent e)
{
keysDown.add(e.getKeyCode());
}
public void keyReleased(KeyEvent e)
{
keysDown.remove(e.getKeyCode());
}
public void updatePaddlePositions()
{
if (keysDown.contains(KeyEvent.VK_W))
paddleOne.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_S))
paddleOne.move(PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_UP))
paddleTwo.move(-PADDLE_MOVE_INCREMENT);
if (keysDown.contains(KeyEvent.VK_DOWN))
paddleTwo.move(PADDLE_MOVE_INCREMENT);
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("You Interrupted the game!");
}
canvas.repaint();
}
Run Code Online (Sandbox Code Playgroud)
这是对象的paintComponent方法canvas:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paddleOne.paint(g);
paddleTwo.paint(g);
updatePaddlePositions(); // Does this need to be …Run Code Online (Sandbox Code Playgroud) 说我有一个JFrame和一个JButton..gif单击按钮后,我想显示动画()图像.而另一个事件(比如说ActionEvent e)则停止在中显示动画JFrame.我的方法应该是什么?
对不起,请问java重复重复的问题,我遇到麻烦,我反复使用起草来表达Pacman Open&Close嘴巴动作.但是这个程序只有一次不会动......有人可以帮我解决这个问题......非常非常感谢!:D
我的代码如下:
package Strive;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class CDrawF extends JFrame {
CDrawF (){
setTitle("??????"); //JFrame interface
setBounds(50, 50, 490, 260); setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for(int i = 0; i<= 360; i++){ //repeatly 360 times
repaint();
g2.setColor(new Color(1.0f, 0.0f, 1.0f));
g2.fill(new Arc2D.Double(100, 100, 80, 80, 30, 300, Arc2D.PIE));
//PacMan close mouth
repaint();
try{ //Delay setions
Thread.sleep(1000);
}catch(InterruptedException ex){}
g2.fill(new Arc2D.Double(100, 100, 80, 80, 10, 340, Arc2D.PIE));
//PacMan …Run Code Online (Sandbox Code Playgroud) 我需要在我的Java GUI中运行后台线程,该线程仅在我单击按钮时运行,并在我再次单击该按钮时暂停.我不确定如何设置它,但我已经在我的构造函数中放置了一个线程,并且当我将特定布尔值设置为TRUE时,while循环设置为通过.一个按钮从设置此布尔值TRUE或FALSE切换.
我在这个GUI中的其他所有工作都很好.当我尝试调试线程时,它实际上是在我逐步完成线程时工作但当我尝试完全运行GUI时没有任何内容.GUI相当大,所以我要设置一部分构造函数和按钮的动作监听器.其余的代码是不必要的,因为它工作得很好.我需要知道我在做错了什么:
public BasketballGUI() {
// certain labels and buttons
Thread runningSim = new Thread() {
public void run() {
while(simRun) {
// do stuff here
}
}
};
runningSim.start();
}
// other GUI stuff
// actionListener that should run the thread.
class SimButtonListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if(!simRun) {
simRun = true;
sim.setText("Pause Simulator");
}
else if(simRun) {
simRun = false;
sim.setText("Run Simulator");
}
// other stuff in this actionListener
}
}
Run Code Online (Sandbox Code Playgroud)