Reputation: 399
The question might seem to be a duplicate of this one but it actually is not. So before downvoting this question, please clarify if any confusion.
I want to draw a horizontal line after every 6-7 lines in my JTextPane
I am using StyledDocument
and inserting strings to my JTextPane
at runtime. Something like:
String myStr = "Some program-generated text";
doc.insertString(doc.getLength(), myStr, attributeSet);
Now how do I draw a horizontal line after every few lines? I tried
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText("<html>Some Text Above The Line<hr size=5>Some Text Below</html>");
But currently my app uses setContentType("text/plain");
changing it to Text.html
disturbs the whole UI. Furthermore, if I use SetText()
then it would be inserted as fresh text, all the previous text will be gone which I appended with doc.insertString();
Any help would be highly appreciated.
Upvotes: 2
Views: 2012
Reputation: 11
you can call it by editing your main method to call the MyTextPane()
subclass instead of JTextPane()
I.e.
public static void main(String[] args) {
//add your jframe here
JFrame frame=new JFrame();
//add component
MyTextPane pane1=new MyTextPane();
pane1.setText("text here");
frame.add(pane1);
frame.pack();
frame1.setVisible(true);
}
Upvotes: 1
Reputation: 694
Something like this!?
Start by creating your own subclass of JTextPane. Implement the draw method and use the FontMetrics from the Graphics Context to get the height of your text.
public class MyTextPane extends JTextPane {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(new Color(255, 0, 0, 128));
FontMetrics fm = g2.getFontMetrics();
int textHeight = fm.getHeight();
for (int i = textHeight; i < getHeight(); i += (6 * textHeight)) {
g2.drawLine(0, i + 1, getWidth(), i + 1);
}
g2.dispose();
}
}
Upvotes: 3