【发布时间】:2015-04-06 11:48:18
【问题描述】:
我遇到了一个问题,无论我做什么,我的 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);
}
}
以下是一个测试类,我尝试在 main 方法中更改 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。这归结为 object 和 variable 之间的基本区别。