我正在尝试创建简单的 Pong 游戏。我正在做的第一件事是当用户单击框架中提供的“左”或“右”按钮时让桨向左或向右移动。当用户单击按钮时,MainPanel 类中的动作侦听器会更改 Paddle 类中名为“paddlePosition”的常量,然后调用“repaint()”。但是,它不起作用,并且桨没有移动。我知道这些按钮正在工作,因为它输出“Hello World”和 paddlePosition 的值,但显然重绘有问题。到目前为止,我正在使用 Swing、JFrame 和 Graphics2D 来让一切正常工作。
我的课程:
乒乓球架(跑步班)
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PongFrame extends JFrame{
private static final long serialVersionUID = 1L;
public PongFrame(){
ButtonPanel buttonPanel = new ButtonPanel();
MainPanel mainPanel = new MainPanel();
add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new PongFrame();
}
}
主面板:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainPanel extends JPanel implements ActionListener{
public Paddle paddle;
public MainPanel(){
setSize(300, 300);
paddle = new Paddle();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
paddle.draw(g2);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World");
Paddle.movePaddleLeft();
System.out.println(Paddle.paddlePosition);
this.repaint();
}
}
按键面板:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ButtonPanel extends JPanel {
private static final long serialVersionUID = 1L;
public MainPanel mainPanelActionListener = new MainPanel();
JButton left;
JButton right;
public ButtonPanel(){
left = new JButton("Left");
right = new JButton("Right");
add(left);
add(right);
left.addActionListener(mainPanelActionListener);
right.addActionListener(mainPanelActionListener);
}
}
桨:
import java.awt.Graphics2D;
public class Paddle{
public static int paddlePosition = 200;
private java.awt.Rectangle paddle;
private int centerCoordinateX;
private int centerCoordinateY;
public Paddle(){
//paddle = new java.awt.Rectangle(paddlePosition, 285, 100, 10); // x, y, width, height
}
public void draw(Graphics2D g2){
paddle = new java.awt.Rectangle(paddlePosition, 285, 100, 10);
g2.draw(paddle);
}
public static void movePaddleLeft(){
paddlePosition = (paddlePosition + 3);
}
}
有谁看到出了什么问题?为什么单击按钮时桨叶不会移动?