Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa phương thức paint() và repaint() trong Java

paint() và repaint()

  • paint(): Phương thức này chứa hướng dẫn vẽ component. Trong Java Swing, chúng ta nên ghi đè paintComponent() thay vì paint() vì paint() gọi paintBorder(), paintComponent() và paintChildren(). Chúng ta không gọi trực tiếp paint() mà gọi repaint().
  • repaint(): Phương thức này không thể ghi đè. Nó điều khiển chu trình update() -> paint(). Ta gọi repaint() để yêu cầu component vẽ lại mình. Nếu thay đổi giao diện nhưng không thay đổi kích thước thì gọi repaint().

Ví dụ

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

public class PaintRepaintTest extends JPanel implements MouseListener {
    private Vector v;

    public PaintRepaintTest() {
        v = new Vector();
        setBackground(Color.white);
        addMouseListener(this);
    }

    public void paint(Graphics g) { // paint() method
        super.paint(g);
        g.setColor(Color.black);
        Enumeration enumeration = v.elements();
        while (enumeration.hasMoreElements()) {
            Point p = (Point) (enumeration.nextElement());
            g.drawRect(p.x - 20, p.y - 20, 40, 40);
        }
    }

    public void mousePressed(MouseEvent me) {
        v.add(me.getPoint());
        repaint(); // call repaint() method
    }

    public void mouseClicked(MouseEvent me) {}
    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me) {}
    public void mouseReleased(MouseEvent me) {}

    public static void main(String args[]) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new PaintRepaintTest());
        frame.setTitle("PaintRepaint Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(375, 250);
        frame.setVisible(true);
    }
}

Trong chương trình trên, nếu click trên màn hình sẽ vẽ được các hình vuông. Trong phương thức mousePressed(), ta gọi repaint().

Kết quả

Khác biệt giữa phương thức paint() và repaint() trong Java