I've been making a chat program for a few days now and I'm completely stumped on how to create a nice looking clickable text without the use of HTML. I tried to use HTML, but had extremely weird results (see below). So I am now just using basic text rather then text/html.
My first attempt to add clickable text was to use JTextPane
's ability to insert Component
s along with the text. It inserted and worked perfectly, but it was vertically offset and looked very bad. I tried to mess with setAlignmentY
, but had no luck aligning the components with the text.
JLabel l = new JLabel(test);
l.setFont(this.getFont());
l.setCursor(new Cursor(Cursor.HAND_CURSOR));
l.setBackground(Color.RED); //Just so i could see it better for testing
l.addMouseListener(new FakeMouseListener());
this.insertComponent(l);
I'm using JTextPane
and inserting text using doc.insertString
. I skip lines using the systems line separator, so a single line can contain multiple doc.insertString
s (Which is were I ran into trouble when attempting to use text/html).
Turns out i put setAlignmentY(0.85f);
for the JTextPane instead of the JLable.
If you have an offset component you're attempting to insert into JTextPane, mess around with it's Y alignment. 0.85f works for me.