View Javadoc
1   package com.jsql.view.swing.text.action;
2   
3   import com.jsql.util.LogLevelUtil;
4   import org.apache.logging.log4j.LogManager;
5   import org.apache.logging.log4j.Logger;
6   
7   import javax.swing.text.BadLocationException;
8   import javax.swing.text.Document;
9   import javax.swing.text.JTextComponent;
10  import javax.swing.text.TextAction;
11  import java.awt.event.ActionEvent;
12  
13  /**
14   * Action to cancel Beep sound when deleting last character.
15   * Used on TextPane and TextArea.
16   */
17  public abstract class AbstractCharAction extends TextAction {
18      
19      private static final Logger LOGGER = LogManager.getRootLogger();
20  
21      /**
22       * Create this object with the appropriate identifier.
23       */
24      protected AbstractCharAction(String deleteAction) {
25          super(deleteAction);
26      }
27  
28      protected abstract void delete(Document doc, int dot) throws BadLocationException;
29  
30      /**
31       * The operation to perform when this action is triggered.
32       */
33      @Override
34      public void actionPerformed(ActionEvent event) {
35          
36          JTextComponent target = this.getTextComponent(event);
37  
38          if (target == null || !target.isEditable()) {
39              return;
40          }
41          
42          try {
43              var doc = target.getDocument();
44              var caret = target.getCaret();
45              int dot = caret.getDot();
46              int mark = caret.getMark();
47              
48              if (dot != mark) {
49                  doc.remove(Math.min(dot, mark), Math.abs(dot - mark));
50              } else {
51                  this.delete(doc, dot);
52              }
53          } catch (BadLocationException e) {
54              LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
55          }
56      }
57  }