首页 > 解决方案 > 如何将 Swing 小部件插入 SWT 我在使用 SWT_AWT.new_Frame 时在线程“main”java.lang.IllegalArgumentException 中出现异常

问题描述

嗨,我是 eclipse 的新手,我想在 SWT 中的现有代码中添加一个像 JCombobox 这样的 Swing 组件。有什么方法可以通过 SWT 或 Swing 中的可用 API 来实现吗?

我使用了建议的SWT_AWT.new_Frame(composite) API。这是我的代码。

public static void main(String[] args) {
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());

        Composite composite = new Composite(shell, SWT.NO_BACKGROUND);
        Frame myframe = SWT_AWT.new_Frame(composite);
        Panel mypanel = new Panel(new BorderLayout()) {
            @Override
            public void update(java.awt.Graphics g) {
                paint(g);
            }
        };
        myframe.add(mypanel);
        JRootPane root = new JRootPane();
        mypanel.add(root);
        java.awt.Container contentPane = root.getContentPane();
        String languages[]={"C","C++","C#","Java","PHP"};        
        final JComboBox cb=new JComboBox(languages);  

        JScrollPane scrollPane = new JScrollPane(cb);
        contentPane.setLayout(new BorderLayout());
        contentPane.add(scrollPane);

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

我得到以下异常。

Exception in thread "main" java.lang.IllegalArgumentException: Argument not valid
    at org.eclipse.swt.SWT.error(SWT.java:4533)
    at org.eclipse.swt.SWT.error(SWT.java:4467)
    at org.eclipse.swt.SWT.error(SWT.java:4438)
    at org.eclipse.swt.awt.SWT_AWT.new_Frame(SWT_AWT.java:129)

标签: javaswingeclipse-pluginswtjface

解决方案


您实际上已经使用了正确的 API。但是您错过了在创建 Composite 时添加诸如将 AWT 小部件嵌入 SWT 之类的功能。SWT.嵌入式

Composite composite = new Composite(shell, SWT.NO_BACKGROUND | SWT.EMBEDDED);
        Frame frame = SWT_AWT.new_Frame(composite);

请通过Eclipse 帮助此链接了解有关此 API 使用的更多信息。


推荐阅读