I want to restrict the height of a JEditorPane inside a JScrollPane to have a maximum value, but still allow the width to expand to fit the content.
My reasoning for this is that I want a single line of text that allows me to embed components. I really want something like a JTextField with embeddable components, but since JTextField cannot do this, I'm using JEditorPane (JTextPane would be fine, too).
I'm trying to mimic the StackOverflow tag behavior in a desktop Swing application. So I will embed clickable "tags" in the JEditorPane and they'll all appear in one line, just like SO does.
As it stands, the JEditorPane expands vertically, but not horizontally with this SSCCE:
import javax.swing.*;
import java.awt.BorderLayout;
public class Tags {
/*
* This is the method I want to modify to implement this behavior:
*/
public static JComponent buildTagsComponent() {
JScrollPane scrollPane = new JScrollPane();
JEditorPane editorPane = new JEditorPane();
scrollPane.setViewportView(editorPane);
return scrollPane;
}
/*
* The remainder of this code is just to make the example complete.
*/
public static JFrame buildFrame() {
JFrame frame = new JFrame("Tags example");
JPanel panel = new JPanel();
JPanel tagsPanel = new JPanel();
JLabel tagsLabel = new JLabel("Tags:");
JLabel mainContent = new JLabel("Main Content Goes Here");
tagsPanel.add(tagsLabel);
tagsPanel.add(buildTagsComponent());
panel.setLayout(new BorderLayout());
panel.add(tagsPanel,BorderLayout.SOUTH);
panel.add(mainContent,BorderLayout.CENTER);
frame.setContentPane(panel);
return frame;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
JFrame frame = buildFrame();
frame.pack();
frame.setVisible(true);
}
}
);
}
}
Note also that I plan to disable the scrollbars and require scrolling with a gesture or moving the cursor position with the cursor keys. When I added a "NEVER" for the scrollbar policies, that just made things not scrollable at all. I'm not looking for a solution for the scrolling problem right now, I just want the answers to take into account that I will be setting the scrollbar policy to NEVER for horizontal and vertical.
I've tried explicitly setting the height and width (minimum, preferred, and maximum) to something like 12 and Integer.MAX_VALUE
, respectively.
UPDATE
After some research I believe the solution I'm looking for has to do with word wrapping. I want the JEditorPane to not wrap paragraphs when there is no line break (line feed).