在实现您自己的呈现时使用 AWT Frame 和 Swing JFrame 与不使用标准 Java GUI 组件之间的主要区别是什么?
这是上一个问题的后续:
AWT custom rendering - capture smooth resizes and eliminate resize flicker
关于 Swing 与 AWT 的典型谈话要点似乎并不适用,因为我们只使用框架。例如,重量级 vs 轻量级已经过时了(JFrame 扩展了 Frame)。
那么对于这种情况,JFrame 还是 Frame 哪个最好?它有什么有意义的不同吗?
注意:在这种情况下,不希望在 EDT 中呈现。有一个未链接到 EDT 的应用程序工作流,渲染是在 EDT 之外按需完成的。将渲染与 EDT 同步会增加渲染的延迟。除了 Frame 或 JFrame(或封闭的 JPanel/Component/etc,如果最好的话),我们不渲染任何 Swing 或 AWT 组件。
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());
}
}
最佳答案
扩展@camickr 的 answer , "missing detail"是JRootPane
,它管理 contentPane
。请注意,对于 JFrame
“add
及其变体、remove
和 setLayout
已被覆盖,以根据需要转发到 contentPane
。” JRootPane#createContentPane()
“创建一个新的 JComponent
,[n]d 将一个 BorderLayout
设置为它的 LayoutManager
。”作为实现细节,JComponent
恰好是一个 new JPanel()
。这对 JFrame
的 contentPane
有几个影响:
- 默认情况下,
contentPane
是双缓冲的。 contentPane
有一个BorderLayout
,尽管JPanel
通常默认为FlowLayout
。contentPane
具有 L&F 特定的 UI 委托(delegate),通常派生自PanelUI
,可能会影响外观和几何形状。
关于java - Swing/JFrame 与 AWT/Frame 在 EDT 之外的渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899004/