Hello Experts;
I need each of your help. I bielive that we can solve this in many heads than one which is mine. I'm developing an ide, the problem I'm encountering now is line highlight. I want to highlight the line where the cursor is. I have a small codes that highlights the line but it ends on the last charter of a text how would I be able to highlight the entire line on where the cursor is ?
Here's my code :
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class TextHighlighter extends JFrame implements CaretListener {
// The text pane to have highlighting
private JTextPane textPane;
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(
new Color(208, 208, 232));
// Constructor for TextHighlighter
public TextHighlighter() {
super("Sample . . .");
textPane = new JTextPane();
Date date = new Date();
String user = System.getProperty("user.name");
textPane.addCaretListener(this);
textPane.setText("/**\n * Created On : " + date + "\n * Author : "
+ user + "\n */\n" + "\npublic class Sample" + " {\n"
+ "\n\tpublic Sample" + "() {\n\n\n" + "\t}" + "\n}");
getContentPane().add(new JScrollPane(textPane), BorderLayout.CENTER);
setSize(380, 250);
setLocationRelativeTo(null);
setVisible(true);
}
// This method is called whenever the caret changes
public void caretUpdate(CaretEvent e) {
highlight(textPane);
}
// The method is called to highlight a textcomponent
public void highlight(JTextComponent textComp) {
removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = textComp.getCaretPosition();
int start = text.lastIndexOf("\n", pos - 1);
start = start < 0 ? 0 : (start + 1);
int end = text.indexOf("\n", pos);
end = end < 0 ? text.length() : end;
hilite.addHighlight(start, end, myHighlightPainter);
} catch (BadLocationException e) {
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i = 0; i < hilites.length; i++) {
if (hilites.getPainter() instanceof MyHighlightPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}
public static void main(String[] args) {
TextHighlighter jf = new TextHighlighter();
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Hoping to hear from you people . . .
Thanks : The_Developer