JTextPane でのラッピング動作がわかりません。短いテキストを挿入し、次に JComponent を挿入し、次に短いテキストを挿入すると、もちろんフレームが十分に大きい場合、挿入されたものを 1 行で見ることができます。ただし、テキストが長くて数行かかる場合、コンポーネントは常に新しい行に配置されます。
コンポーネントが JTextPane に挿入された後、そのテキストが 1 文字長くなることがわかりました。コンポーネントが JTextPane によって文字と見なされる場合、なぜ文字のように動作しないのでしょうか? Javaのバージョンにもよるかな?Java(TM) SE ランタイム環境 (ビルド 1.7.0-b147)を使用しています。
以下は私のコードです(変数 currentText を shortText/longText でインスタンス化して、前述の動作を再現します):
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
String shortText = "one two three four five six seven";
String longText = "A text component that can be marked up with attributes that are represented graphically. You can find how-to information and examples of using text panes in Using Text Components, a section in The Java Tutorial. This component models paragraphs that are composed of runs of character level attributes. Each paragraph may have a logical style attached to it which contains the default attributes to use if not overridden by attributes set on the paragraph or character run. Components and images may be embedded in the flow of text.";
String currentText = shortText;
try {
// insert text before the component
textPane.getDocument().insertString(textPane.getDocument().getLength(), currentText,
new SimpleAttributeSet());
textPane.setSelectionStart(textPane.getDocument().getLength());
textPane.setSelectionEnd(textPane.getDocument().getLength());
JComboBox component = new JComboBox();
component.setMaximumSize(component.getPreferredSize());
textPane.insertComponent(component);
// insert text after the component
textPane.getDocument().insertString(textPane.getDocument().getLength(), currentText,
new SimpleAttributeSet());
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textPane.setEditable(false);
frame.add(new JScrollPane(textPane));
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}