在SWT中使用Swing

在SWT出现之前,已经有众多的Swing程序和控件被开发出来,为了充分利用这些现有资源,SWT需要提供一种在SWT中使用Swing的途径。
Swing是通过在AWT的Canvas控件上绘图以显示各种控件,而AWT的控件与SWT的原理相似,都是直接对应到操作系统上的资源,因此只要利用SWT模拟出AWT的Canvas,Swing的控件就可以运行在上面了,因马刺,SWT提供了一个org.eclipse.swt.awt.SWT_AWT类,它通常被称为SWT_AWT桥。
在SWT_AWT中,提供了一个方法用于从SWT的Composite容器得到一个AWT的Frame容器new_Frame(Composite composit).
既然得到了一个AWT Frame,就可以向这个Frame中添加一个Swing的一个容器JPanel,之后的工作就和纯Swing编程一样了。
这种解决方案复杂且效率低下,往往是不得已而为之,就好象戴着手套和MM牵手一样,完全不对味。但除非你打算用SWT来重写,否则也就这一条路可走的了。

下面的例子,在SWT的Composite上添加了一个Swing的Button,代码如下:

import java.awt.BorderLayout;
import java.awt.Frame;

import javax.swing.JButton;
import javax.swing.JPanel;

import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;


public class test {

/**
* @param args
*/
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setBounds(100, 100, 200, 100);
shell.open() ;

Composite composite = new Composite(shell ,SWT.EMBEDDED);
composite.setBounds(0, 0, 200, 100);

Frame frame = SWT_AWT.new_Frame(composite);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel,BorderLayout.CENTER);

JButton button = new JButton();
button.setBounds(10, 10, 180, 20);
button.setText("Swing Button");
panel.add(button);

while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep() ;
}
}
}

}



效果如下:
[img]http://dl.iteye.com/upload/attachment/499534/d0da1e34-9c72-35f5-8a56-9a2d60402c30.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值