Cha*_*win 6 java swing rendering doublebuffered awt
在实现自己的渲染而不使用标准Java GUI组件时,使用AWT Frame和Swing JFrame有什么主要区别?
这是上一个问题的后续内容:
关于Swing vs AWT的典型谈话要点似乎并不适用,因为我们只使用框架.例如,重量级和轻量级超出窗口(并且JFrame扩展了Frame).
那么哪种情况最好,JFrame或Frame适用于这种情况?它有什么有意义的区别吗?
注意:这种情况是不希望在EDT中进行渲染的情况.有一个应用程序工作流程没有链接到EDT,渲染是在EDT之外的需要基础上完成的.要使渲染与EDT同步会增加渲染的延迟.除了Frame或JFrame之外,我们不渲染任何Swing或AWT组件(如果最好的话,我们不会渲染封闭的JPanel/Component/etc).
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.awt.Frame;
public class SmoothResize extends Frame {
public static void main(String[] args) {
Toolkit.getDefaultToolkit().setDynamicLayout(true);
System.setProperty("sun.awt.noerasebackground", "true");
SmoothResize srtest = new SmoothResize();
//srtest.setIgnoreRepaint(true);
srtest.setSize(100, 100);
srtest.setVisible(true);
}
public SmoothResize() {
render();
}
private Dimension old_size = new Dimension(0, 0);
private Dimension new_size = new Dimension(0, 0);
public void validate() {
super.validate();
new_size.width = getWidth();
new_size.height = getHeight();
if (old_size.equals(new_size)) {
return;
} else {
render();
}
}
public void paint(Graphics g) {
validate();
}
public void update(Graphics g) {
paint(g);
}
public void addNotify() {
super.addNotify();
createBufferStrategy(2);
}
protected synchronized void render() {
BufferStrategy strategy = getBufferStrategy();
if (strategy == null) {
return;
}
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
Graphics draw = strategy.getDrawGraphics();
Insets i = getInsets();
int w = (int)(((double)(getWidth() - i.left - i.right))/2+0.5);
int h = (int)(((double)(getHeight() - i.top - i.bottom))/2+0.5);
draw.setColor(Color.YELLOW);
draw.fillRect(i.left, i.top + h, w,h);
draw.fillRect(i.left + w, i.top, w,h);
draw.setColor(Color.BLACK);
draw.fillRect(i.left, i.top, w, h);
draw.fillRect(i.left + w, i.top + h, w,h);
draw.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
}
Run Code Online (Sandbox Code Playgroud)
扩展@camickr的答案,“缺失的细节”是JRootPane,它管理contentPane. 请注意,对于JFrame“add及其变体,remove并且setLayout已被覆盖以contentPane根据需要转发到”。JRootPane#createContentPane()“创建一个新的JComponenta[n]d 将 a 设置BorderLayout为其LayoutManager。” 作为一个实现细节,这JComponent恰好是一个new JPanel(). 这对 产生了几个contentPane后果JFrame:
contentPane双缓冲的。contentPane有一个。BorderLayoutJPanelFlowLayoutcontentPaneL&F 特定的 UI 委托,通常派生自PanelUI,可能会影响外观和几何形状。