我遇到了一个问题,无论我做什么,我的JPanel都不会重新绘制。我正在使用以下方法创建一个连接四个游戏板,并随着游戏进行动态地改变圈子的颜色,但我将它简化成了一个具有相同问题的测试课程。JPanel在分配新子类时不会重新绘制
我决定为每个圆圈使用状态模式设计。以下是类的代码,因此它知道要打印哪种颜色,即JPanel儿童类。
public class GridCircle extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 100, 100);
}
}
public class WhiteGridCircle extends GridCircle
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillOval(5, 5, 80, 80);
}
}
public class RedGridCircle extends GridCircle
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(5, 5, 80, 80);
}
}
以下是测试类,我试图改变类一个JPanel在主方法,以看它是否会改变所画的颜色(失败)。
public class test extends JFrame
{
static JPanel testPanel = new WhiteGridCircle();
public static void main(String[] args)
{
new test();
testPanel = new RedGridCircle();
testPanel.revalidate();
testPanel.repaint();
}
test()
{
this.add(testPanel);
this.setSize(150,150);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
}
我不明白为什么面板不会重漆,不管我尝试过什么。根据我的理解,repaint()不能保证调用paint方法,但我没有理由不会在没有任何其他事情发生时进行调用。
您正在更改某个变量引用的对象,但这不会对所显示的对象产生神奇的影响。您需要更改由GUI保存的JPanel *对象*。这可以归结为* object *和a * variable *之间的基本区别。 – 2015-04-06 12:08:14