我试图将 JEditorPane 嵌入到 SWT Shell 中但没有成功。JEditorPane 没有出现,我不明白为什么。
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();
}
}
我还做了一个只使用swing组件的小程序,出现了JEditorPane,但是当我将它嵌入到shell中时,它没有出现。谢谢你。