Doubts about the Graphics and Graphics2D classes in Java

2

I'm having a lot of questions about Java graphical libraries, which are as follows:

  • What is the difference between overwriting the paint(Graphics) method or the paintComponent(Graphics) method?

  • What is the Graphics2D class of difference in relation to class Graphics ?

  • asked by anonymous 12.03.2018 / 02:15

    1 answer

    1
  • The paint(Graphics) method in lightweight components (those of Swing) accomplishes these three things, in that order:

    • Paints the contents of the component itself by calling the paintComponent(Graphics) method.

    • Paints the subcomponents when calling the paintChildren(Graphics) method.

    • Paints the edge of the component when calling the paintBorder(Graphics) method.


    The paint(Graphics) method also does a few more things to determine which area is to be painted. It also handles the case that you are printing the component (to the printer), then calling the print*(Graphics) methods instead of paint*(Graphics) . See it all in matching source code .

    As you will hardly want to change this default functioning of paint(Graphics) % (there is little reason to do so), hardly would override such a method is meaningless. Therefore, override the paintComponent(Graphics) method that actually draws the component.

  • The class Graphics2D is a subclass of Graphics . It has many more methods, just take a quick look at javadoc it

  • 12.03.2018 / 03:37