gpt4 book ai didi

未调用 Java JPanel paintComponent(Graphics g)

转载 作者:行者123 更新时间:2023-12-03 23:17:56 27 4
gpt4 key购买 nike

我有一个 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();
}

最佳答案

As you can see, I call repaint() in the constructor, but that does nothing

您不需要调用 repaint()。 Swing 将确定何时需要重新绘制。

无论如何,在这种情况下它什么都不做,因为组件还没有被添加到 GUI 中。

 contentPane.setLayout(new FlowLayout());

您正在使用尊重组件大小的 FlowLayout。您进行绘画的自定义组件没有首选大小,因此它的大小为 (0, 0),因此没有要绘画的内容。

覆盖 getPreferredSize() 方法以返回组件的大小。看起来每个网格都是 (15, 15),所以你应该使用:

@Override Dimension getPreferredSize()
{
return new Dimension(120, 120);
}

当然,最好为您的类定义变量以包含网格大小和网格数量,而不是在代码中硬编码 8 和 15。

关于未调用 Java JPanel paintComponent(Graphics g),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821601/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com