在paintComponent完成后更改JComponent的颜色 [英] Change color of JComponent after paintComponent has finished

查看:488
本文介绍了在paintComponent完成后更改JComponent的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个扩展JComponent的小部件类。

小部件的构造函数包含一个向量并设置了组件的PreferredSize,然后是paintComponent:

I am testing one small widget class that extends JComponent
the constructor for the widget contains one vector and sets PreferredSize of the component, then there is the paintComponent:

public void paintComponent(Graphics g){
        g.setColor(Color.RED);
        g.drawString("this is text one", 10, 10);
            //here I draw some shapes based on the 
            //vector size and integers
        }
    }

组件被正确绘制后,我调用main中的一些其他方法,当方法完成他们的工作,我调用 widget.methodsFinished():

the component is drawn correctly and after that i call some other methods in main, when the methods finish their jobs i call widget.methodsFinished():

methodsFinished(){
        g.setColor(Color.GREEN);
        g.drawString("this is text two", 30, 30);
                this.update(g);
}



我通过这样做得到nullpointer异常,你能告诉我如何正确更新该组件中已绘制的形状的颜色。

I get nullpointer exception by doing this, can you tell me how to correctly update the color of already drawn shapes in this component, thank you in advance.

推荐答案


我如何正确更新此组件中已绘制的
形状的颜色,请提前感谢。

can you tell me how to correctly update the color of already drawn shapes in this component, thank you in advance.

不是真的坚韧:


  1. 在类上下文中声明私有颜色字段。

  2. 声明公共< c $ c> setShapeColor(Color color)将颜色设置为组件

  3. invoke repaint()以反映颜色变化

  4. 并作为警告:不要忘记调用 super.paintComponent(g); paitnComponent(Graphics)函数中,您尚未完成。

  1. Declare a private Color field in your class context.
  2. Declare a public setShapeColor(Color color) to set the color to the component
  3. invoke repaint() to reflect the color changes
  4. And as a warning: don't forget to call super.paintComponent(g); inside the paitnComponent(Graphics) function, which you haven't done.

 class MyComponent extends JPanel
 {
     private Color shapeColor = Color.RED;

     public void setShapeColor(Color color)
     {
       this.shapeColor = color; 
     }

    @Override
   public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(shapeColor);
    g.drawString("this is text one", 10, 10);
        //here I draw some shapes based on the 
        //vector size and integers
       }
   }
 } 


尽管作为OOP原则,你应该实际声明一个 MyShape 类与颜色属性,在绘制之前使用setter方法作为示例设置颜色的形状。

Though as OOP principle, you should actually declare a MyShape class with Color attribute and before drawing use the setter method as the example to set the color to the shape.

这篇关于在paintComponent完成后更改JComponent的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆