尝试运行程序时,我陷入了无限循环,无法突破。 - 我尝试将不同的类调用设为私有,但是,它没有改变任何东西。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
class Mazes extends JPanel {
public static void main(String[] args) throws FileNotFoundException {
new Mazes();
}
public Mazes() throws FileNotFoundException {
JFrame f = new JFrame("Maze");
f.add(new Board());
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
董事会成员
class Board extends JPanel {
Boolean[][] maze = getMaze();
int row = maze.length;
private Ball b = new Ball();
public Boolean[][] getMaze() throws FileNotFoundException {
Boolean[][] maze = Exercise4.readMaze();
return maze;
}
public Board() throws FileNotFoundException {
add(b);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int y = 0; y < row; y++) {
for (int x = 0; x < row; x++) {
if (maze[y][x].equals(false)) {
g.setColor(Color.BLACK);
g.fillRect(x * 25, y * 25, 120, 120);
} else {
g.setColor(Color.WHITE);
g.fillRect(x * 25, y * 25, 120, 120);
}
}
}
g.setColor(Color.RED);
g.fillOval((row - 1) * 24 - 5, (row - 1) * 24 - 5, 20, 20);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(row * 25, row* 25);
}
}
球类
class Ball extends JPanel implements ActionListener {
int x = 25, y = 25, vx = 25, vy = 25, tileX = 0, tileY = 0;
private Board test = new Board(); // I believe the problem lies here when constructing the new Board, as it recalls the ball in the Board class again.
Boolean[][] maze = test.getMaze();
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
setBounds(0,0, 25*600,25*600);
setOpaque(false);
g.setColor(Color.BLUE);
g.fillOval(x, y, 20, 20);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
public Ball() throws FileNotFoundException {
addKeyListener(new AL());
setFocusable(true);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public class AL extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
if (!maze[tileX][tileY].equals(false)) {
y -= vy;
tileY += 1;
repaint();
}
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
}
}
基本上,我的呼唤是: 主类 - &gt;董事会类 - &gt;球类(将球员添加到迷宫中) - &gt;董事会类
我陷入了构造函数循环,并且不知道如何修复/更改它。
我试图从Ball类的Board类中调用board构造函数:我已经评论了我认为问题出现的地方。
我这样做是为了试图引用Ball类中的迷宫(Board)以使碰撞可行 - &gt;没有Board构造函数或碰撞条件的Ball类在板上运行良好。