01: package net.sourceforge.pmd.util.viewer.gui;
02:
03: import net.sourceforge.pmd.ast.SimpleNode;
04: import net.sourceforge.pmd.util.viewer.model.ViewerModel;
05: import net.sourceforge.pmd.util.viewer.model.ViewerModelEvent;
06: import net.sourceforge.pmd.util.viewer.model.ViewerModelListener;
07: import net.sourceforge.pmd.util.viewer.util.NLS;
08:
09: import javax.swing.*;
10: import javax.swing.text.BadLocationException;
11: import javax.swing.text.DefaultHighlighter;
12: import java.awt.BorderLayout;
13: import java.awt.Color;
14:
15: /**
16: * source code panel
17: *
18: * @author Boris Gruschko ( boris at gruschko.org )
19: * @version $Id: SourceCodePanel.java 4711 2006-10-20 02:40:49Z hooperbloob $
20: */
21:
22: public class SourceCodePanel extends JPanel implements
23: ViewerModelListener {
24:
25: private ViewerModel model;
26: private JTextArea sourceCodeArea;
27:
28: private static final Color highlightColor = new Color(79, 237, 111);
29:
30: public SourceCodePanel(ViewerModel model) {
31: this .model = model;
32: init();
33: }
34:
35: private void init() {
36: model.addViewerModelListener(this );
37: setBorder(BorderFactory.createTitledBorder(BorderFactory
38: .createEtchedBorder(), NLS.nls("SOURCE.PANEL.TITLE")));
39: setLayout(new BorderLayout());
40: sourceCodeArea = new JTextArea();
41: add(new JScrollPane(sourceCodeArea), BorderLayout.CENTER);
42: }
43:
44: /**
45: * retrieves the string representation of the source code
46: *
47: * @return source code's string representation
48: */
49: public String getSourceCode() {
50: return sourceCodeArea.getText();
51: }
52:
53: /**
54: * @see ViewerModelListener#viewerModelChanged(ViewerModelEvent)
55: */
56: public void viewerModelChanged(ViewerModelEvent e) {
57: if (e.getReason() == ViewerModelEvent.NODE_SELECTED) {
58: final SimpleNode node = (SimpleNode) e.getParameter();
59: SwingUtilities.invokeLater(new Runnable() {
60: public void run() {
61: try {
62: sourceCodeArea.getHighlighter()
63: .removeAllHighlights();
64: if (node == null) {
65: return;
66: }
67: int startOffset = (sourceCodeArea
68: .getLineStartOffset(node.getBeginLine() - 1) + node
69: .getBeginColumn()) - 1;
70: int end = (sourceCodeArea
71: .getLineStartOffset(node.getEndLine() - 1) + node
72: .getEndColumn());
73: sourceCodeArea
74: .getHighlighter()
75: .addHighlight(
76: startOffset,
77: end,
78: new DefaultHighlighter.DefaultHighlightPainter(
79: highlightColor));
80: sourceCodeArea.moveCaretPosition(startOffset);
81: } catch (BadLocationException exc) {
82: throw new IllegalStateException(exc
83: .getMessage());
84: }
85: }
86: });
87: }
88: }
89: }
|