1
16package org.tp23.gui.widget;
17
18import java.awt.event.ActionEvent;
19import java.awt.event.ActionListener;
20import java.awt.event.MouseAdapter;
21import java.awt.event.MouseEvent;
22import java.io.FileNotFoundException;
23import java.io.FileWriter;
24import java.io.IOException;
25
26import javax.swing.JMenuItem;
27import javax.swing.JPopupMenu;
28import javax.swing.JTextArea;
29
30public class FollowingJTextArea extends JTextArea{
31
32 private boolean follow = true;
33
34 public FollowingJTextArea() {
35 jInit();
36 }
37
38
39 private void jInit(){
40 final JPopupMenu popUp = getPopupMenu();
41 this.add(popUp);
42 this.addMouseListener(new MouseAdapter(){
43 public void mouseClicked(MouseEvent e) {
44 if (e.getButton() == e.BUTTON3) {
45 popUp.show(FollowingJTextArea.this,e.getX(),e.getY());
46 }
47 }
48 });
49 }
50
51 public boolean isFollow() {
52 return follow;
53 }
54 public void setFollow(boolean follow) {
55 this.follow = follow;
56 }
57
58 private void scrollToEnd(){
59 setCaretPosition(getDocument().getLength());
60 }
61 private void toggleFollow(){
62 setFollow(!isFollow());
63 }
64
65
71 public void append(String str) {
72 super.append(str);
73 if(follow)scrollToEnd();
74 }
75 private JPopupMenu getPopupMenu() {
76 JPopupMenu contextMenu = new JPopupMenu("Options");
77 JMenuItem saveMenu = new JMenuItem("Save Text");
78 saveMenu.addActionListener(new ActionListener() {
79 public void actionPerformed(ActionEvent e) {
80 SelectFileAction action = new SelectFileAction("Save Output", null, null);
81 try {
82 action.actionPerformed(new ActionEvent(this, 0, "Save Output"));
83 if (action.selectedFile != null) {
84 FileWriter fos = new FileWriter(action.selectedFile);
85 fos.write(getText());
86 fos.close();
87 }
88
89 }
90 catch (FileNotFoundException ex) {
91 System.err.println("FileNotFoundException");
92 }
93 catch (IOException ex) {
94 System.err.println("IOException");
95 }
96 }
97 });
98 contextMenu.add(saveMenu);
99
00 JMenuItem toggleFollowMenu = new JMenuItem("Toggle Follow");
01 toggleFollowMenu.addActionListener(new ActionListener() {
02 public void actionPerformed(ActionEvent e) {
03 toggleFollow();
04 }
05 });
06 contextMenu.add(toggleFollowMenu);
07
08 JMenuItem jumpToEndMenu = new JMenuItem("Jump To End");
09 jumpToEndMenu.addActionListener(new ActionListener() {
10 public void actionPerformed(ActionEvent e) {
11 setCaretPosition(getDocument().getLength());
12 }
13 });
14 contextMenu.add(toggleFollowMenu);
15
16 JMenuItem clearTextMenu = new JMenuItem("Clear Text");
17 clearTextMenu.addActionListener(new ActionListener() {
18 public void actionPerformed(ActionEvent e) {
19 setText("");
20 }
21 });
22 contextMenu.add(clearTextMenu);
23 return contextMenu;
24 }
25}
26