0
本質上,我試圖向JPanel網格矩陣添加一個圓(這是我的主要問題所在)。 運行下面的代碼時,一旦調用新的OvalComponent類將圓添加到網格中的(1,1)位置,就會讀取該類,但只會跳過繪畫組件函數。Java--被稱爲paintComponent將被讀取,但在運行時不會被實現
package Exercises;
import javax.swing.*;
import java.awt.*;
import java.io.FileNotFoundException;
/**
* Created by user on 4/1/2017.
*/
public class Mazes extends JPanel {
public static void main(String[] args) throws FileNotFoundException {
Mazes maze = new Mazes();
}
public Mazes() throws FileNotFoundException{
Boolean[][] maze = Exercise4.readMaze();
int row = maze.length;
JFrame f = new JFrame("Maze");
f.setLayout(new GridLayout(row, row));
JPanel[][] grid = new JPanel[row][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
grid[i][j] = new JPanel();
grid[i][j].setOpaque(true);
if ((i==1&&j==1) || (i==row-1 && j==row-1))
grid[i][j].add(new OvalComponent());
if (maze[i][j].equals(false)){
grid[i][j].setBackground(Color.BLACK);}
else grid[i][j].setBackground(Color.WHITE);
f.add(grid[i][j]);
}
}
//f.add(new JButton("Reset"), BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
class OvalComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(4, 4, 10, 10);
}
}