JTextPane insert component, faulty vertical alignm

2019-08-14 21:25发布

问题:

I have a JTextPane, into which I need to insert a JComponent. I'm using

JTextPane.insertComponent(Component)

The item is indeed inserted, but the vertical positioning is too high. Instead of having the bottom of the component aligned with the baseline of the current line of text, the component is way above that position, blocking out/over-painting lines of text appearing above.

I have tried calling setAlignmentY(float) with various values, on both the inserted component and the JTextPane, but it doesn't affect the behavior at all.

My guess: there seems to be some state inside my JTextPane or its Document that I need to be changing. But I don't know what it is.

回答1:

Have you tried calling setSize(width, height) on the JComponent before you insert it into the JTextPane? It should work for most components.



回答2:

I know, this is a pretty old question, but your approach of using setAlignmentY is totally correct. Don't know what code caused it to not work, but the javadoc of JTextPane.insertComponent(Component) says the following about the alignment:

The component is placed relative to the text baseline according to the value returned by Component.getAlignmentY. For Swing components this value can be conveniently set using the method JComponent.setAlignmentY. For example, setting a value of 0.75 will cause 75 percent of the component to be above the baseline, and 25 percent of the component to be below the baseline

So using textPane.setAlignmentY(1.0f) has the desired effect.



回答3:

I ran into the same problem and could not find a solution using JTextPane or JEditorPane. But I was able to use JavaFX/WebView/WebEngine/JFXPanel. You will need to update to Java 8 (JDK 1.8). I made my own class HTMLPaneType, an extension of JFXPanel, and use HTMLPaneType in place of a JTextPane.

A JTextPane requires adding a HyperlinkListener if you want to respond to href clicks. HTMLPaneType requires adding a listener if you want to NOT respond to href clicks or to respond differently. In my case, I wanted to launch an external browser on an href click. I was able to do that with both the JTextPane and the extended JFXPanel. See also
http://blogs.kiyut.com/tonny/2013/07/30/javafx-webview-addhyperlinklistener/#.VK-JIHsueWN