java - AWT Canvas 在手动调整大小时闪烁

标签 java user-interface swing awt

出于智力的兴趣,您能否使 Canvas 在手动调整大小时不闪烁。

public class FlickerAWT extends Canvas {

public static void main(String[] args) {
 Frame f = new Frame(str);
 //this line change nothing
 //JFrame f = new JFrame(str);
 f.add(new FlickerAWT());
 f.pack();

 int frameWidth = f.getWidth();
 int frameHeight = f.getHeight();
 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
 f.setLocation(screenSize.width / 2 - frameWidth / 2, screenSize.height / 2 - frameHeight / 2);
 f.setVisible(true);

 f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
      System.exit(0);
    }
    public void windowDeiconified(WindowEvent e) {
    }
    public void windowIconified(WindowEvent e) {
    }
 });
}
private Color bgColor; private Color contentColor;
Font          f   = new Font("Georgia", Font.BOLD, 16);
static String str = "AWT Canvas Resize Flickering";
public FlickerAWT() {
 Random r = new Random();
 bgColor = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
 contentColor = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
}
public Dimension getPreferredSize() {
 FontMetrics fm = getFontMetrics(f);
 return new Dimension(fm.stringWidth(str) + 20, fm.getHeight() + 10);
}
public void paint(java.awt.Graphics g) {
 g.setColor(bgColor);
 g.fillRect(0, 0, getWidth(), getHeight());
 g.setColor(contentColor);
 g.setFont(f);
 FontMetrics fm = g.getFontMetrics(f);
 int dx = getWidth() / 2 - (fm.stringWidth(str) / 2);
 int dy = getHeight() / 2 + (fm.getHeight() / 2);
 g.drawString(str, dx, dy);
}
}

您可以在 Java 编辑器中复制粘贴并运行示例。

最佳答案

您可以将此添加到您的主要方法的开头以避免背景闪烁:

System.setProperty("sun.awt.noerasebackground", "true");

关于java - AWT Canvas 在手动调整大小时闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5452439/

相关文章:

ios - scrollView 的 ContentInset

java - 在哪里可以找到 jdatepicker jar 文件?

java - 我如何对齐特定行中的所有 JProgressbar 显示它看起来像目标中所示

java - 安装 JDBC 驱动程序以从 Matlab 访问 Mariadb 数据库

java - 调试 jaxb2 maven 插件

python - 如何在 Python GUI 应用程序中显示 PostScript 文件

c++ - wxWidgets 在 wxPanel 上绘制 wxGLCanvas

java - 文本字段中的数据不会存储到我的字段变量中

java - SWT 表 : auto resize all columns

javascript - Frida 拦截 Android 中调用函数时传递的参数值是什么的代码