嵌入式JEditorPane在SWT Shell中

时间:2013-01-16 20:06:13

标签: java swing swt swt-awt

我试图在SWT Shell中嵌入JEditorPane但没有成功。 JEdi​​torPane没有出现,我不明白为什么。

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中时,它不会出现。 谢谢。

1 个答案:

答案 0 :(得分:1)

您需要在shell上设置布局以显示复合材料。使用这样的东西:

shell.setLayout(new FillLayout());