分配新子类时 JPanel 不会重绘
JPanel won't repaint when assigned a new subclass
我 运行 遇到一个问题,无论我做什么,我的 JPanel 都不会重新绘制。我使用以下方法创建一个连接四游戏板并随着游戏的进行动态更改圆圈的颜色,但我已将其简化为具有相同问题的测试 class。
我决定为每个圆圈使用状态模式设计。以下是 classes 的代码,因此它知道要打印哪种颜色是 JPanel 子级 classes.
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);
}
}
以下是一个测试 class,我尝试在主要方法中更改 JPanel 的 class 以查看它是否会更改绘制的颜色(失败)。
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() 没有 gua运行tee 来调用 paint 方法,但我认为没有理由在没有其他事情发生时它不应该这样做。
因为您创建并添加的实例 this.add(testPanel);
仍然是 new WhiteGridCircle()
。
您更改了实例,但添加到 JFrame 的原始实例仍在框架中。
在实例化 RedGridCircle 之后和 revalidate()
调用之前更改调用 this.getContentPane().add(testPanel);
。
我 运行 遇到一个问题,无论我做什么,我的 JPanel 都不会重新绘制。我使用以下方法创建一个连接四游戏板并随着游戏的进行动态更改圆圈的颜色,但我已将其简化为具有相同问题的测试 class。
我决定为每个圆圈使用状态模式设计。以下是 classes 的代码,因此它知道要打印哪种颜色是 JPanel 子级 classes.
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);
}
}
以下是一个测试 class,我尝试在主要方法中更改 JPanel 的 class 以查看它是否会更改绘制的颜色(失败)。
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() 没有 gua运行tee 来调用 paint 方法,但我认为没有理由在没有其他事情发生时它不应该这样做。
因为您创建并添加的实例 this.add(testPanel);
仍然是 new WhiteGridCircle()
。
您更改了实例,但添加到 JFrame 的原始实例仍在框架中。
在实例化 RedGridCircle 之后和 revalidate()
调用之前更改调用 this.getContentPane().add(testPanel);
。