Java Swing:用户输入文本 - 将其插入句子中间:问题是光标在输入每个字母后跳到末尾

问题描述 投票:0回答:1

我知道 Java Swing 已经过时了,但我仍然使用它。我主要使用 JTextArea,如果用户想在现有文本中间插入文本,它工作得很好。但是 JTextArea 中没有行间距,而希伯来语中的标点符号则上下行的标点符号重叠。因此我改用 JTextPane 并能够更改行距。但是,如果用户想要将文本插入现有文本,则光标会跳到每个字母之后的文本末尾。这使得插入文本变得乏味。

我做了很多谷歌搜索,但没有找到关于这个主题的任何内容。

这是我的代码:

  hebrewField = new JTextPane();
  hebrewField.setFont(ApplicationFonts.getHebrewFont(30F));
  hebrewField.setDocument(new NikudStyledDocument(true));
  hebrewField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);     
  hebrewField.setMinimumSize(new Dimension(Settings.getKeyboardWidth() - 30,
        (heightTotal - heightBorderTitel)));
  hebrewField.setMaximumSize(
        new Dimension(this.widthTotal, (heightTotal - heightBorderTitel)));
  hebrewField.setBorder(
        BorderFactory.createTitledBorder(translator.realisticTranslate(
              Translation.HEBRAEISCH__EINFACHE_SCHREIBWEISE)));
  changeLineSpacing(hebrewField);

 private void changeLineSpacing(JTextPane pane) {
  SimpleAttributeSet set = new SimpleAttributeSet(pane.getParagraphAttributes());
  StyleConstants.setLineSpacing(set, 0.5F);
  pane.setParagraphAttributes(set, true);
  }

还有人记得如何在 Java Swing 中实现这一点吗?任何想法表示赞赏。谢谢你的好意。

JTextPane

更新

此处文本已设置。我想我必须在插入文本后设置插入符位置。

public void mousePressed(MouseEvent e)
  {
     DataButton jButton = (DataButton) e.getComponent();
     String caption = jButton.getData();

     JTextComponent focusElement = findFocusElement();
     if (focusElement != null)
     {
        int position = focusElement.getCaretPosition();
        String text = focusElement.getText();
        String before = text.substring(0, position);
        String after = text.substring(position);
        focusElement.setText(before + caption + after);
        focusElement.requestFocus();
     }
  }
java swing jtextpane
1个回答
0
投票

谢谢阿布拉的请求。这让我重新思考这个问题。这是解决方案。

public void mousePressed(MouseEvent e)
  {
     DataButton jButton = (DataButton) e.getComponent();
     String caption = jButton.getData();

     JTextComponent focusElement = findFocusElement();
     if (focusElement != null)
     {
        int position = focusElement.getCaretPosition();
        String text = focusElement.getText();
        String before = text.substring(0, position);
        String after = text.substring(position);
        focusElement.setText(before + caption + after);
        focusElement.requestFocus();
        focusElement.setCaretPosition(position + 1);
     }
  }
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.