Search code examples
javaswingjtextfieldpaintcomponent

java JTextField paintComponent Method called repeatedly. Is that normal?


having subclassed JTextField, I noticed the paintComponent Method is called repeatedly (approximately every half-a-second) when the Field has Focus, even with no user interaction.

I read the Oracle article "Painting in AWT and Swing", but didn't find any enlightenment there.

Is this normal behaviour, or have a missed something?

Here's my example Proggy:
(positioning the Cursor in the 2nd - not subclassed - JTextField which has no logging, causes the subclassed one with logging to lose Focus which stops being repeatedly repainted)

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

public class SwingPaintDemo2 extends JFrame {

    public SwingPaintDemo2(final String title) {
        super(title);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Box box = new Box(BoxLayout.Y_AXIS);

        box.add(new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(250, 200);
            }
            @Override
            public void paintComponent(final Graphics g) {
                super  .paintComponent(               g);

                System.out.println("MyPanel.paintComponent......: " + g);

                g.drawString("This is my custom Panel!", 10, 20);
            }
        });
        box.add(new JTextField("JayTekst") {
            @Override
            public void paintComponent(final Graphics g) {
                super  .paintComponent(               g);

                System.out.println("JayTextField.paintComponent.: " + g);
            }
        });
        box.add(new JTextField("JText"));
        this.add(box);
        this.pack();
        this.setVisible(true);
    }
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new SwingPaintDemo2("Swing Paint Demo"));
    }
}

Solution

  • Of course it is normal. When the textfield has focus, you can see the cursor blinking which means you see the textfield with new a visual representation, which means paintComponent().