Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String font size smaller when calling repaint()

When I draw a string with g.drawString() the resulting text is smaller than the set font. If you run the following code, you can see that the desired font size is displayed, then a smaller one shows up once the second thread calls repaint() I have tried SwingUtilities.invokeLater() before calling repaint but that did not help. Any ideas?

import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {
    static JPanel   panel;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        panel = new JPanel() {
            private static final long   serialVersionUID    = 1L;

            public void paint(Graphics g) {
                g.clearRect(0, 0, panel.getWidth(), panel.getHeight());
                g.drawString("TEST", 20, 100);// Where I draw the string
            }
        };
        panel.setFont(new Font("Arial", Font.BOLD, 30));// The desired font
        frame.add(panel);
        frame.setSize(500, 500);
        frame.setVisible(true);
        new Thread() {// This thread calls repaint() after two seconds
            public void run() {
                try {
                    Thread.sleep(2000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                panel.repaint();
            }
        }.start();
    }
}
like image 371
Christopher Smith Avatar asked Mar 16 '26 18:03

Christopher Smith


2 Answers

  1. Don't override paint but rather paintComponent.
  2. Always call the super method.

e.g.

  panel = new JPanel() {
     private static final long serialVersionUID = 1L;

     @Override
     protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // g.clearRect(0, 0, panel.getWidth(), panel.getHeight());
        g.drawString("TEST", 20, 100);// Where I draw the string
     }
  };
like image 105
Hovercraft Full Of Eels Avatar answered Mar 19 '26 08:03

Hovercraft Full Of Eels


The problem is, paint is probably setting the font to use before up it paints the reset of the component, because you've overridden it, but failed to call super.paint, it has not had a chance to set these values

Instead of overriding paint, override paintComponent instead...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("TEST", 20, 100);// Where I draw the string
}

Painting is complex process of a series of chained method calls, if you break this Chain, be prepared for some serious weirdness

Take a look at Performing Custom Painting and Painting in AWT and Swing for more details

like image 24
MadProgrammer Avatar answered Mar 19 '26 07:03

MadProgrammer