I am trying to embed a JEditorPane in a SWT Shell without success. The JEditorPane does not appear and I don't understand why.
import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.rtf.RTFEditorKit;
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.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
public class EmbeddedRtf {
public static void main(String args[]) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Rtf editor");
Menu mb = new Menu(shell, SWT.BAR);
MenuItem fileItem = new MenuItem(mb, SWT.CASCADE);
fileItem.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
fileItem.setMenu(fileMenu);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText("&Exit\tCtrl+X");
exitItem.setAccelerator(SWT.CONTROL + 'X');
MenuItem aboutItem = new MenuItem(fileMenu, SWT.PUSH);
aboutItem.setText("&About\tCtrl+A");
aboutItem.setAccelerator(SWT.CONTROL + 'A');
shell.setMenuBar(mb);
Composite rtfComposite = new Composite(shell, SWT.EMBEDDED);
java.awt.Frame frame = SWT_AWT.new_Frame(rtfComposite);
java.awt.Panel panel = new java.awt.Panel(new java.awt.FlowLayout());
frame.add(panel);
// Create an RTF editor window
RTFEditorKit rtf = new RTFEditorKit();
JEditorPane editor = new JEditorPane();
editor.setEditorKit(rtf);
editor.setBackground(Color.white);
// This text could be big so add a scroll pane
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(editor);
panel.add(scroller);
// Load an RTF file into the editor
try {
FileInputStream fi = new FileInputStream("test.rtf");
rtf.read(fi, editor.getDocument(), 0);
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("I/O error");
} catch (BadLocationException e) {
}
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
I made also a small program using only swing components and the JEditorPane appears, but when I embed it in a shell, it does not appear. Thank you.
You need to set a layout on your shell for the composite to appear. Use something like this:
shell.setLayout(new FillLayout());