JTextArea换班线+输入新线 [英] JTextArea new line on shift + enter
问题描述
我在我的JTextArea字段中添加了一个keylistener,但它的行为与我的预期不同。
I've added a keylistener to my JTextArea field, but it doesn't behave as I expected.
inputTextArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent k) {
//If the return button is hit, only set to a new line if shift is also down.
if(k.getKeyChar() == KeyEvent.VK_ENTER) {
if(k.isShiftDown()) {
inputTextArea.append(" \n");
} else {
//Send The Message...
boolean cleanTextField = false;
try {
sendMessage(inputTextArea.getText());
cleanTextField = true;
msgScrollPane.setAutoscrolls(true);
JScrollBar vbar = msgScrollPane.getVerticalScrollBar();
if ((vbar.getValue() + vbar.getVisibleAmount()) == vbar.getMaximum()) {
msgPane.setCaretPosition(msgDoc.getLength());
}
} catch (Exception ex) {
ex.printStackTrace();
cleanTextField = false;
} finally {
if(cleanTextField) {
inputTextArea.setText("");
}
}
}
}
}
});
我想这样:
- 如果点击返回按钮并且班次下调:添加一条新线。
- 如果按下返回按钮并且按钮没有按下:没有新行,但是提交。
I want this: - If the return button is hit and shift is down: add a new line. - If the return button is hit and the shift button isn't down: no new line, but submit.
现在它的行为如下:
- 如果我点击返回按钮并且班次下降:没有添加任何行。什么都没发生。
- 如果我点击返回按钮并且班次没有下降:提交,但是如果我再次开始输入则从新行开始。
Now it behaves like this: - If I hit the return button and shift is down: no line added. Nothing happens. - If I hit the return button and shift isn't down: submitted, but if I start typing again it begins on new line.
有人知道吗怎么做我想要的?
Does someone know how to do what I want?
编辑:
我尝试了一些其他代码来检测是否有移位按钮关闭:
I tried some other code to detect if the shift button is down:
if((k.getModifiersEx() == KeyEvent.SHIFT_DOWN_MASK) ||
(k.getModifiers() == KeyEvent.SHIFT_DOWN_MASK)) {
这不起作用
推荐答案
您可以使用 InputMap
和 ActionMap
的 JTextArea
将关键笔划映射到操作:
You may use the InputMap
and ActionMap
of the JTextArea
to map the key strokes to actions:
private static final String TEXT_SUBMIT = "text-submit";
private static final String INSERT_BREAK = "insert-break";
...
private void initialize() {
InputMap input = inputTextArea.getInputMap();
KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
input.put(shiftEnter, INSERT_BREAK); // input.get(enter)) = "insert-break"
input.put(enter, TEXT_SUBMIT);
ActionMap actions = inputTextArea.getActionMap();
actions.put(TEXT_SUBMIT, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
submitText();
}
});
}
...
private void submitText() {
// TODO
}
ENTER的原始操作
- 插入 - 断开 - 用于 shift ENTER
。
The original action for ENTER
- "insert-break" - is used for shift ENTER
.
这篇关于JTextArea换班线+输入新线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!