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

Mor*_*dan 1 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);
}
}
Run Code Online (Sandbox Code Playgroud)

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

Whi*_*g34 5

您可以将其添加到main方法的开头以避免背景闪烁:

System.setProperty("sun.awt.noerasebackground", "true");
Run Code Online (Sandbox Code Playgroud)

  • 实际上,不得不把它放在 VM 参数中。刚刚做了另一个我想使用它的项目,它使用`-D`标志工作。 (2认同)