下面的代码显示了在 SWT 中使用带有SWT_AWT
桥的 Swing 绘制的 50 个圆圈。
每次调用paint 都会导致调试打印。
很明显,油漆在运行时被调用了 3 次。如果在普通 Swing 中运行,它只会被调用一次。
如果在 SWT 内部,为什么会调用 3 次?
package tests;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Try_SWT_Swing {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite composite = new Composite(shell, SWT.EMBEDDED | SWT.NO_BACKGROUND);
composite.setLayout(new FillLayout());
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
System.out.println("paint");
Graphics2D g2 = (Graphics2D) g;
for(int i=1; i<50; ++i) {
g2.drawOval(i*10, i*10, 100, 100);
}
}
};
Frame frame = SWT_AWT.new_Frame(composite);
frame.setLayout(new BorderLayout());
frame.add(panel);
shell.setSize(640, 480);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}