Reputation: 450
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();
}
}
Upvotes: 2
Views: 248
Reputation: 347314
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
Upvotes: 4
Reputation: 285405
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
}
};
Upvotes: 6