canvasswtawtswt-awtnattable

Adding SWT Canvas to JPanel


I'm trying to add a NatTable (which extends org.eclipse.swt.widgets.Canvas) to a JPanel (the majority of the program's graphics are in Swing, and I'm rather unfamiliar with SWT). I attempted to use the code below to test the SWT_AWT class, but I got an error:

org.eclipse.swt.widgets.Canvas canvas =
                new org.eclipse.swt.widgets.Canvas(
                        new org.eclipse.swt.widgets.Shell(
                                Display.getDefault(),
                                1264),
                        SWT.NONE);
        java.awt.Frame frame = SWT_AWT.new_Frame(canvas); //error here
        JPanel returnMe = new JPanel();
        returnMe.add(frame);

        return returnMe;

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Argument not valid

I do not understand why I have this error as I passed a SWT composite. Can anyone explain what I did wrong and how to fix it?


Solution

  • In order for the embedding to succeed, the composite must have been created with the SWT.EMBEDDED style.

    Also, you are going the other way: embedding Swing component in SWT. Instead you need

    java.awt.Canvas canvas = ...
    // assumes this code is running in SWT thread
    Shell shell = SWT_AWT.new_Shell(Display.getCurrent(), canvas); 
    NatTable table = new NatTable(shell, SWT.NONE); // etc.
    

    Note that you need to arrange to run SWT code in SWT dispatch thread and Swing code in AWT dispatch thread.