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          JTextComponent target = this.getTextComponent(event);
36          if (target == null || !target.isEditable()) {
37              return;
38          }
39          try {
40              var doc = target.getDocument();
41              var caret = target.getCaret();
42              int dot = caret.getDot();
43              int mark = caret.getMark();
44              
45              if (dot != mark) {
46                  doc.remove(Math.min(dot, mark), Math.abs(dot - mark));
47              } else {
48                  this.delete(doc, dot);
49              }
50          } catch (BadLocationException e) {
51              LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
52          }
53      }
54  }