【问题标题】:I do not understand the paintComponent method [closed]我不明白paintComponent方法[关闭]
【发布时间】:2013-03-30 12:32:37
【问题描述】:

谁能解释一下paintComponent的方法?这是什么意思?什么时候叫?它与paint 方法有何不同?

请解释一下以下代码:

    public RoundButton(String label) {
    super(label);

// These statements enlarge the button so that it 
// becomes a circle rather than an oval.
    Dimension size = getPreferredSize();
    size.width = size.height = Math.max(size.width, 
      size.height);
    setPreferredSize(size);

// This call causes the JButton not to paint 
   // the background.
// This allows us to paint a round background.
    setContentAreaFilled(false);
  }

// Paint the round background and label.
  protected void paintComponent(Graphics g) {
    if (getModel().isArmed()) {
// You might want to make the highlight color 
   // a property of the RoundButton class.
      g.setColor(Color.lightGray);
    } else {
      g.setColor(getBackground());
    }
    g.fillOval(0, 0, getSize().width-1, 
      getSize().height-1);

// This call will paint the label and the 
   // focus rectangle.
    super.paintComponent(g);
  }

【问题讨论】:

  • 请阅读这个 -- Painting in AWT and Swing -- 这篇文章已经解释过了。
  • 投票结束,因为最好的答案是让您阅读上面链接的教程,而不是让我们中的一个人无力地尝试重新编写教程。

标签: java swing paintcomponent


【解决方案1】:

Jcomponent 除了 paint(...) 之外还有 3 个其他的绘制方法:

paintComponent()
paintBorder()
paintChildren()

这些方法在paint方法中以这种方式被调用(来自Jcomponent的paint方法的代码):

     if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) {
        if (!printing) {
        paintComponent(co);
        paintBorder(co);
        }
        else {
        printComponent(co);
        printBorder(co);
        }
            }
    if (!printing) {
        paintChildren(co);
    }
    else {
        printChildren(co);
    }

当更改组件的绘制方式时,总是会覆盖 paintComponent () 方法,就像在您的示例中一样。在您的示例中,在调用 super.paintComponent() 之前绘制了一个椭圆。 更改边框的原因相同,您只需覆盖paintBorder 方法...

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2015-03-08
    • 2012-01-14
    • 1970-01-01
    • 2013-10-22
    • 2020-10-23
    相关资源
    最近更新 更多