调用repaint() 在重量级和轻量级组件区别

1.轻量级的组件继承的是JComponent的子类,因此它们包含paintComoponent()方法;
  所以当调用repaint()方法是表示应该尽早绘制该组件,即调用的是paintComoponent()方法。 只有当组件不透明的是才需要清除GUI组件的背景。大多数的组件在默认时是透明的。(设置组件的是否透明是JComponent的setOpaque方法来设定的)。
  举例如下:
import java.awt.*;
import javax.swing.*;

public class CustomPanel extends JPanel{
    public final static int CIRCLE = 1,SQUARE = 2;
    private int shape;
   
    public void paintComponent(Graphics g){
       
        super.paintComponent(g);  // 清除绘制的其他图像
        if(shape == CIRCLE){
            g.fillOval(50,10,60,60);
        }
        else if(shape == SQUARE){
            g.fillRect(50,10,60,60);
        }
    }
   
    public void draw(int shapeToDraw){
        shape = shapeToDraw;
        repaint();
    }
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CustomPanelTest extends JFrame{
   
    private JPanel buttonPanel;
    private CustomPanel myPanel;
    private JButton circleButton,squareButton;
   
    public CustomPanelTest(){
        super("CustomPanel Test");
       
        myPanel = new CustomPanel();
        myPanel.setBackground(Color.green);
       
        squareButton = new JButton("Square");
        squareButton.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    myPanel.draw(CustomPanel.CIRCLE);
                }
            }
        );
       
        circleButton = new JButton("Circle");
        circleButton.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    myPanel.draw(CustomPanel.SQUARE);
                }
            });
       
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(1,2));
        buttonPanel.add(circleButton);
        buttonPanel.add(squareButton);
       
        Container container = getContentPane();
        container.add(myPanel,BorderLayout.CENTER);
        container.add(buttonPanel,BorderLayout.SOUTH);
       
        setSize(300,150);
        setVisible(true);
    }
   
    public static void main(String args[]){
        CustomPanelTest application = new CustomPanelTest();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

2. 重量级的组件继承的是Component类,当调用repaint()方法时是先调用Component类的update方法(用于清除组件的背景),并且update方法会调用paint方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值