我正在嘗試做一個Java乒乓球遊戲。我對Java很少有經驗,需要一些幫助。我在網上閱讀了很多東西,下面是我提出的代碼。 我創建了以下類,但我得到的只是灰色屏幕。我只是試圖爲此實現最簡單的解決方案。任何人都可以指出這個代碼有什麼問題嗎?謝謝。嘗試Java乒乓球
package pong_test_1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
*
* @author jtrinidad
*/
public class main_class extends JFrame implements KeyListener{
static final int FRAME_WIDTH = 800;
static final int FRAME_HEIGHT = 500;
JFrame f;
public main_class()
{
super();
addKeyListener (this);
setFocusable (true);
f = new JFrame("Pong");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(FRAME_WIDTH,FRAME_HEIGHT);
f.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
Pong_Test_1 p = new Pong_Test_1();
int keyCode = e.getKeyCode();
switch(keyCode) {
case KeyEvent.VK_UP:
Pong_Test_1.p2_pos_y--;
break;
case KeyEvent.VK_DOWN:
Pong_Test_1.p2_pos_y++;
break;
case KeyEvent.VK_Q:
Pong_Test_1.p1_pos_y++;
break;
case KeyEvent.VK_A :
Pong_Test_1.p1_pos_y++;
break;
}
add(p);
repaint();
}
/** Handle the key released event from the text field. */
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
// TODO code application logic here
main_class c = new main_class();
}
}
和
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pong_test_1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author jtrinidad
*/
public class Pong_Test_1 extends JPanel implements ActionListener{
/**
* @param args the command line arguments
*/
//Sizes of each object
static final int WIDTH = 10;
static final int HEIGHT = 120;
static final int RADIUS = 10;
//Position of Player 1's paddle
static int p1_pos_x = 10;
static int p1_pos_y = main_class.FRAME_HEIGHT/2;
//Position of Player 2's paddle
static int p2_pos_x = main_class.FRAME_WIDTH - 20;
static int p2_pos_y = main_class.FRAME_HEIGHT/2;;
//Position of the ball
static int ball_pos_x;
static int ball_pos_y;
Timer animator;
public Pong_Test_1()
{
animator = new Timer (10, this);
animator.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK); //Sets background color
g.setColor(Color.WHITE);
g.fillRect(p1_pos_x, p1_pos_y, WIDTH, HEIGHT);
g.fillRect(p2_pos_x, p2_pos_y, WIDTH, HEIGHT);
g.fillOval(100, 100, RADIUS, RADIUS);
}
public void actionPerformed(ActionEvent e) {
repaint();
revalidate(); // new line
}
private void addKeyListener(Pong_Test_1 aThis) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
從基礎開始。你知道如何着色屏幕嗎?在這裏,你可以提出具體的問題,但檢查整個來源不是我們的工作。 – Jimmt
另外,你應該遵循命名約定;在類/方法名稱中沒有下劃線,並且將每個單詞的首字母大寫爲類名稱。 – Jimmt
在你的'actionPerformed()'方法中調用'repaint();'不會像你認爲的那樣調用'paintComponent()'。 –