ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java在无法编辑的JTextArea中插入退格键

2019-12-01 13:04:12  阅读:289  来源: 互联网

标签:jtextarea swing key-bindings backspace java


我有一个在特定设置下不可编辑的JTextArea.但是,在此设置下,用户仍然可以使用空格键和退格键.为了容纳空间,我有以下代码,

if (e.getKeyChar() == KeyEvent.VK_SPACE) {
    editor.insert(" ", editor.getCaretPosition());
}

我在退格上有问题.我已经试过了

if (e.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
    editor.insert("\b", editor.getCaretPosition());
}

当按下退格键时,这似乎增加了一个很小的空间.它不像空格那么大,按一次几乎不明显.绝对不是退格.更糟糕的是,我将必须复制所有字符直到插入符号的位置-1并将它们附加到插入符号位置之后的所有字符,但是我不喜欢这种解决方案.

解决方法:

使用键绑定使空格键和退格键具有关联的操作,然后如果按下了退格键,则从JTextArea的Document中删除一个字符.

例如,

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class TextAreaFun extends JPanel {
   public static final String SPACE = "space";
   public static final String BACK_SPACE = "back space";
   private JTextArea textArea = new JTextArea(15, 50);

   public TextAreaFun() {
      // create our key bindings
      // only allow key presses to initiate an action if the JTextArea has focus
      int condition = JComponent.WHEN_FOCUSED;
      InputMap taInputMap = textArea.getInputMap(condition);
      ActionMap taActionMap = textArea.getActionMap();

      taInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), SPACE);
      taInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0),
            BACK_SPACE);
      taActionMap.put(SPACE, new KeyAction(textArea, SPACE));
      taActionMap.put(BACK_SPACE, new KeyAction(textArea, BACK_SPACE));

      // checkbox that stops all editing except for that specified in the 
      // key bindings above
      JCheckBox chkBox = new JCheckBox(new AbstractAction("Prevent Editing") {
         {
            putValue(SELECTED_KEY, Boolean.FALSE); // default to unchecked
            putValue(MNEMONIC_KEY, KeyEvent.VK_P);
         }

         @Override
         public void actionPerformed(ActionEvent evt) {
            boolean selection = (Boolean) getValue(SELECTED_KEY);
            textArea.setEditable(!selection);
         }
      });
      JPanel bottomPanel = new JPanel();
      bottomPanel.add(chkBox);

      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
      add(new JScrollPane(textArea));
      add(Box.createVerticalStrut(10));
      add(bottomPanel);
   }

   private static void createAndShowGui() {
      TextAreaFun mainPanel = new TextAreaFun();

      JFrame frame = new JFrame("TextAreaFun");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
// action to be initiated by key bindings
class KeyAction extends AbstractAction {
   private PlainDocument textAreaDocument;
   private String title;

   public KeyAction(JTextArea textArea, String title) {
      this.textAreaDocument = (PlainDocument) textArea.getDocument();
      this.title = title;
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      if (title.equals(TextAreaFun.SPACE)) {
         try {
            textAreaDocument.insertString(textAreaDocument.getLength(), " ",
                  null);
         } catch (BadLocationException e1) {
            e1.printStackTrace();
         }
      } else if (title.equals(TextAreaFun.BACK_SPACE)) {
         if (textAreaDocument.getLength() == 0) {
            return;
         }
         try {
            textAreaDocument.remove(textAreaDocument.getLength() - 1, 1);
         } catch (BadLocationException e1) {
            e1.printStackTrace();
         }
      }
   }
}

标签:jtextarea,swing,key-bindings,backspace,java
来源: https://codeday.me/bug/20191201/2080753.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有