我有一个 JPanel,它的 paintComponent(Graphics g) 方法没有被调用。我知道这是一个常见问题,但到目前为止我发现的任何建议都无法解决它。这是 JPanel 的代码:
import javax.swing.*;
import java.awt.*;
public class Grid extends JPanel
{
Candy[][] gridRep = new Candy[8][8];
public Grid()
{
this.setLayout(new GridLayout(8,8));
this.populateRandom();
this.repaint();
}
...
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
for (int r = 0; r<8; r++){
for (int c = 0; c<8; c++){
g2.setColor(gridRep[r][c].getColor());
g2.drawOval(getXCoordinate(gridRep[r][c])*15, getYCoordinate(gridRep[r][c])*15, 10, 10);
System.out.println("repainting");
}
}
}
}
如您所见,我在构造函数中调用了 repaint(),但它什么也没做。我还在创建此类对象的 JFrame 类中称其为 willy nilly:
import javax.swing.*;
import java.awt.*;
public class Game
{
private Grid grid;
private JFrame frame;
public Game(){
this.makeFrame();
}
private void makeFrame(){
grid = new Grid();
frame = new JFrame ("Frame");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
//grid.paint(grid.getGraphics());
grid.repaint();
frame.add(grid);
grid.repaint();
frame.pack();
grid.repaint();
frame.setVisible(true);
grid.repaint();
}