JTextArea 实现 单击某行高亮 双击显示内容的功能
程序员文章站
2022-07-13 23:08:51
...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
public class MyTextPanel extends JPanel {
private JTextArea text;
private JScrollPane scrollPanel = null;;
private int line;
public MyTextPanel() {
super();
setLayout(new BorderLayout());
scrollPanel = new JScrollPane(getText());
add(scrollPanel);
}
public void addContent(String content) {
text.setText(content);
}
public JTextArea getText() {
if (text == null) {
text = new JTextArea();
text.setMargin(new Insets(5, 5, 5, 5));
text.setEditable(false);
text.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
if (text.getText().trim().length() == 0)
return;
int offset = e.getDot();
// 计算光标所在行列
try {
//得到光标所在的行数
line = text.getLineOfOffset(offset);
//System.out.println(line);
// int col = offset - text.getLineStartOffset(line);
// System.out.println("col:"+col);
} catch (BadLocationException e3) {
e3.printStackTrace();
}
}
});
text.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {//单击 高亮
DefaultHighlighter h = (DefaultHighlighter) text.getHighlighter();
MyHighlightPainter p = new MyHighlightPainter(
new Color(226, 239, 255));
try {
int start = text.getLineStartOffset(line);
int end = text.getLineEndOffset(line);
h.removeAllHighlights();
h.addHighlight(start, end, p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
if (e.getClickCount() == 2) {//双击
String[] lines = text.getText().split("\n");
String store = lines[line];
System.out.println(store);
}
}
});
}
return text;
}
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}
}
效果图 上传了
加了2个监听器 才能实现 因为单单一个MouseListener 得不到 点击所在的行数 如有更加简单的方法 请指教