【问题标题】:Java Swing How to reset JTextAreaJava Swing 如何重置 JTextArea
【发布时间】:2015-09-27 12:39:44
【问题描述】:

我正在制作一个程序,用户可以在 JTextArea 组件中键入字符串消息,然后按 Enter 以发送消息,然后应清除 JTextArea 并将插入符号位置重置为 0。

    JTextArea userChatBox = new JTextArea();
    userChatBox.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==10){
            //If key pressed is enter.  
                client.send(userChatBox.getText());
                userChatBox.setCaretPosition(0);
                userChatBox.setText("");

            }

        }
    });
    userChatBox.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
    userChatBox.setTabSize(4);
    userChatBox.setLineWrap(true);
    userChatBox.setForeground(UIManager.getColor("ColorChooser.foreground"));
    userChatBox.setFont(new Font("DejaVu Serif", Font.PLAIN, 12));
    userChatBox.setBackground(Color.WHITE);
    userChatBox.setBounds(10, 255, 400, 80);
    frmChatClient.getContentPane().add(userChatBox);

但是,当用户按下回车键时,JTextArea 将其注册为返回并输入新行。即使在userChatBox.setCaretPosition(0); 之后,插入符号也会出现在第二行,随后从 JTextArea 发送的任何字符串都将包含一个空行。我也尝试设置选择开始和结束,但无济于事。

【问题讨论】:

标签: java swing user-interface jtextpane


【解决方案1】:

正如@luxxminer 所说,问题是在文本追加到jtextarea之前首先发生事件。如果你可以消费事件,那么新行将不会追加。

所以你可以使用event.consume(); 方法

if (e.getKeyCode()==10){

    //If key pressed is enter.  
        client.send(userChatBox.getText());
        userChatBox.setCaretPosition(0);
        userChatBox.setText("");
        e.consume();
}

【讨论】:

  • 请问有真正的使用理由吗,为什么要为 JTextComponents 使用 KeyListener,可能是 10 == ENTER,这是一个 new_line 作为 JTextArea 的 UIManager 中的 KeyBindings
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 2020-04-02
  • 2016-09-18
相关资源
最近更新 更多