【问题标题】:Java paintComponent running but not showingJava paintComponent 正在运行但未显示
【发布时间】:2013-12-02 14:48:59
【问题描述】:

所以我只想在屏幕的随机部分绘制一个正方形作为自定义JComponent

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    if( this.good ){
        g2d.setColor(Color.green);
    }
    else{
        g2d.setColor(Color.red);
    }
    g2d.fillRect(this.x, this.y, this.w, this.h);
    System.out.println("painting");
}

这里是通过repaint()调用绘画的方法

private void stateChange(){
        
    double rand = Math.random();
        
    if (rand < 0.5){
        this.good = !this.good;
    }
    setLocation(this.x,this.y);
    repaint();
}

this.xthis.y 不断变化,但我知道这是可行的。当我运行我的代码时,它会在应有的位置打印"painting"但没有显示任何内容。我做错了吗?

额外代码:

这是我试图让它显示出来的内容:

\\in JComponent constructore
setOpaque(true);
setVisible(true);
setSize(this.w,this.h);

【问题讨论】:

  • 确保您拨打的是super.paintComponent ;)

标签: java swing paintcomponent jcomponent


【解决方案1】:

我的猜测:您有一个 while (true) 循环绑定了 Swing 事件线程,因此当您更改状态时,GUI 无法重新绘制自身以显示它正在发生。要么是那个,要么是你的 JComponent 的尺寸非常小,太小而无法显示图像。

对于不仅仅是猜测的答案,您需要使用相关代码提出更完整的问题。

请注意,您的 paintComponent(...) 方法覆盖缺少对超级方法的调用。

注意:您可以通过在您的 paintComponent 中添加 getSize() 方法来测试 JComponent 的大小:

public void paintComponent(Graphics g){
    super.paintComponent(g);  // **** don't forget this.
    Graphics2D g2d = (Graphics2D) g;
    if( this.good ){
        g2d.setColor(Color.green);
    }
    else{
        g2d.setColor(Color.red);
    }
    g2d.fillRect(this.x, this.y, this.w, this.h);

    // TODO: ***** delete this lines
    System.out.println("painting");
    System.out.println(getSize());  // **** add this***
}

注意:您应该在您的组件上调用setSize(...)。它通常具有误导性,因为布局管理器经常忽略它。

【讨论】:

  • 我没有循环,尺寸是 50 x 50
  • @RyanSaxe:查看编辑,请添加更多相关信息以完成您的问题。
  • this.wthis.h 都是 50 时,尺寸怎么是 1,1?
  • 您说的尺寸太小是对的,但考虑到我将尺寸设置为 50,50,这没有任何意义
  • @RyanSaxe:如果您需要它来显示图像,请覆盖 getPreferredSize() 并计算一个合适的 Dimension 以使其返回。
【解决方案2】:

根据您提供的示例代码,问题在于您实际上是在组件的可视空间边界之外进行绘制。

绘制时Graphics上下文的左上角是0x0,Swing已经根据组件的位置翻译了Graphics上下文,所以...

g2d.fillRect(this.x, this.y, this.w, this.h);

实际上(可能)在组件的可视区域之外进行绘制。比如x的位置是10y10,但是高宽只有1010,你是在10x10的位置画的,这会超出组件的可视空间,相反,您应该尝试类似...

g2d.fillRect(0, 0, this.w, this.h);

或者,根据您的示例代码,

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    if( this.good ){
        g2d.setColor(Color.green);
    }
    else{
        g2d.setColor(Color.red);
    }
    super.paintComponent(g2d);
}

相反....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 2018-08-18
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多