JTextArea上的KeyEvent问题 [英] KeyEvent issue on JTextArea

查看:97
本文介绍了JTextArea上的KeyEvent问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是GUI编程的新手.在Java Swing JTextarea上练习KeyEvent处理时,我遇到了一个问题.侦听器界面由文本区域本身实现.

I am new to GUI programming. While practicing KeyEvent handling on Java Swing JTextarea I face one problem. The listener interface is implemented by text area itself.

当我在文本区域中按VK_ENTER键时,我从文本区域中获取了文本,然后将该文本显示到了JTextPane中.之后,我将文本设置为文本区域上的空字符串.在这里,我使用了keyPressed键事件-它正在文本区域中创建一行新行,但已经将文本区域行设置为0(零).

When I pressed VK_ENTER key in text area I get text from text area then I displayed that text into JTextPane. After that I set text as empty string on text area. Here I used keyPressed key event - it is creating one new line in text area but already I set text area row as 0 (zero).

实际上,我希望在文本区域中显示一行,而又不想在文本区域中显示两行,如何解决此问题?

Actually I want one row in text area I don't want two line in text area, How to resolve this problem?

这是我的代码:

public void keyPressed(KeyEvent evt) {

   try {
       if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
           if (evt.isShiftDown()) {  
              textArea .setText(textArea.getText() + "\n");
           } else {   
                inputMsg = textArea.getText().trim();
                textArea.setText(EMPTYSTRING);
                if (!inputMsg.equals(EMPTYSTRING)) {   
                   textPane.setText(inputMsg);
                }
                textArea.requestFocus();
              }
          }
     } catch (Exception ex) {
         logger.log(Level.SEVERE, "Exception in textArea.keyReleased() : ", ex);
     }
}

推荐答案

实际上我要在textarea中排一行,而又不想在textarea中排两行,如何解决此问题?

Actually I want one row in textarea I don't want two line in textarea, How to resolve this problem?

然后为什么要使用textarea ?,请使用JTextField

then why are you using textarea?, use JTextField

编辑:

当您在keyPressed方法中提供逻辑时,将添加新的一行.释放键时,ENTER使它在文本区域生效(通过为ENTER添加新行).

The additional new line is coming as you are providing your logic in keyPressed method. When you release the key, the ENTER makes it effect on the text area (by adding new line for ENTER).

您可以改用public void keyReleased(java.awt.event.KeyEvent evt)方法尝试逻辑,它应该有效.

You can try your logic in public void keyReleased(java.awt.event.KeyEvent evt) method instead and it should work.

其他方法可能是在逻辑之后使用按下事件中的已释放事件,但是我不确定如何.

Other way could be to consume the released event in pressed event after your logic, but I'm not sure how.

这篇关于JTextArea上的KeyEvent问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆