程序运行时,paintComponent调用不一致

时间:2017-03-08 00:50:25

标签: java swing paintcomponent

我试图理解为什么在运行程序时不正确地调用paintComponent。在查看之前的帖子时,我已经阅读了AWT和Swing(http://www.oracle.com/technetwork/java/painting-140037.html)中的所有绘画以及涉及paintComponent的数十篇帖子。这个程序是一个使用MouseListener方法的简单程序。当我只运行这个程序而不做任何其他事情(移动鼠标等)时,paintComponent有时被称为3,4或5次。通常,它运行3或4次。这种不一致对我来说很疯狂。它显示我知道的少。有人知道为什么吗?

以下是代码:

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

public class EnterExit extends JFrame {
    public EnterExit(){
        super("Enter exit Frame");
        setSize( 300, 400);             
        setDefaultCloseOperation(EXIT_ON_CLOSE);        
        setLocation(00,0);
        EEPanel eep = new EEPanel();        
        getContentPane().add( eep );
        setVisible(true);       
    }

    public static void main (String [] args){
        EnterExit ee = new EnterExit();
    }
} 

public class EEPanel extends JPanel implements MouseListener {
    private boolean entered;
    private int x, y; // counter used to test why flickering when prog 1st runs;
    private int count; // troubleshooting how many times paintComponent is called.

    public EEPanel(){
        entered = false;
        count = x = y = 0;
        addMouseListener(this);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setFont(new Font("Serif", Font.BOLD, 50) );
        g.setColor(Color.BLACK);

        count++;    // troubleshooting
        if(entered){
            setBackground(Color.RED);
            g.drawString("entered", 50, 150);
            System.out.println("INSIDE if count = "+count);//troubleshooting
        }else{
            setBackground(Color.GREEN);
            g.drawString("exited", 50, 150);
            System.out.println("INSIDE else  count = " + count );
        }
    }

    public void mouseEntered(MouseEvent e){
        entered = true;
        repaint();              // all mouse methods seem to work correctly.
        System.out.println("mouseEntered"); // all sop lines used for testing
    }


    public void mouseExited(MouseEvent e){ 
        entered = false; 
        repaint();
        System.out.println("mouseExited"); 
    }

    public void mousePressed(MouseEvent evt) {
        x = evt.getX();
        y = evt.getY();
        repaint();
        System.out.println("mousePressed: x = " + x +"\t y = " + y);    
    }
    public void mouseClicked(MouseEvent e) {System.out.println("mouseClicked");}
    public void mouseReleased(MouseEvent e) {System.out.println("mouseReleased");}
}

0 个答案:

没有答案