【问题标题】:JPanel won't repaint when assigned a new subclass分配新的子类时,JPanel 不会重新绘制
【发布时间】: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。这归结为 objectvariable 之间的基本区别。

标签: java swing jpanel repaint


【解决方案1】:

因为您创建并添加的实例 this.add(testPanel); 仍然是 new WhiteGridCircle()

您更改了实例,但添加到 JFrame 的原始实例仍保留在框架中。

在实例化 RedGridCircle 之后和 revalidate() 调用之前更改调用 this.getContentPane().add(testPanel);

【讨论】:

  • 我不得不将它调整为我的主程序,因为我将所有内容都放在一个数组中,不能只在末尾添加一个。我最终需要重置整个外部 JPanel 并阅读了所有内容,但它确实有效,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
  • 2013-05-07
  • 2011-05-22
  • 2014-05-20
  • 1970-01-01
  • 2013-11-12
  • 2012-08-05
相关资源
最近更新 更多