Drawing in JPanel vs JComponent

前端 未结 2 675
鱼传尺愫
鱼传尺愫 2021-01-16 04:26

I need some help understanding why the drawing works differently in JComponent vs JPanel.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Gr         


        
相关标签:
2条回答
  • 2021-01-16 04:57

    Call super.paintComponent(g) in paintComponent implementation.

    public void paintComponent(Graphics g) {
      super.paintComponent(g);
    
      Graphics2D g2d = (Graphics2D) g.create();
      g2d.setColor(getColor());
      g2d.fillRect(x, y, 4, 4);
    
    }
    
    0 讨论(0)
  • 2021-01-16 05:07

    A solution has been post by Toilal. I want to explain why:

    In the API docs of paintComponent of JComponent

    Further, if you do not invoker super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts.

    In setOpaque of JComponent

    The default value of this property is false for JComponent. However, the default value for this property on most standard JComponent subclasses (such as JButton and JTree) is look-and-feel dependent.

    Add this code:

    System.out.println(isOpaque());
    
    • In JComponent case false is printed.
    • In JPanel case true is printed.

    That's all.

    0 讨论(0)
提交回复
热议问题