Make parts of a JTextArea non editable (not the whole JTextArea!)

前端 未结 5 1587
甜味超标
甜味超标 2020-12-16 18:42

I\'m currently working on a console window in Swing. It\'s based on a JTextArea and works like a common command line. You type a command in one line and press enter. In the

5条回答
  •  攒了一身酷
    2020-12-16 19:29

    What about that, when ">> " is the beginning of every line in the command line where the user can input a command:

    textArea.addKeyListener(new KeyAdapter() {
    
        public void keyPressed(KeyEvent event) {
    
            int code = event.getKeyCode();          
            int caret = textArea.getCaretPosition();
            int last = textArea.getText().lastIndexOf(">> ") + 3;
    
            if(caret <= last) {
    
                if(code == KeyEvent.VK_BACK_SPACE) {
    
                    textArea.append(" ");
    
                    textArea.setCaretPosition(last + 1);
                }
    
                textArea.setCaretPosition(textArea.getText().length());
             }
         }
     });
    

提交回复
热议问题