gpt4 book ai didi

java - 调用 repaint() 时字符串字体变小

转载 作者:行者123 更新时间:2023-12-02 13:30:45 24 4
gpt4 key购买 nike

当我使用 g.drawString() 绘制字符串时,生成的文本小于设置的字体。如果运行以下代码,您可以看到显示了所需的字体大小,然后一旦第二个线程调用 repaint() 就会显示较小的字体我已经尝试过 SwingUtilities.invokeLater() 在调用 repaint 之前,但这没有帮助。有什么想法吗?

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();
}
}

最佳答案

  1. 不要覆盖paint,而是覆盖paintComponent。
  2. 始终调用 super 方法。
<小时/>

例如

  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
}
};

关于java - 调用 repaint() 时字符串字体变小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25148562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com