我有一个名为input的JTextArea,当我按向上箭头键时,我试图将字符串inputValue加载到其中。到目前为止,这段代码似乎不起作用,我不确定为什么。请帮忙。
input.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
System.out.println("test");
if(e.getKeyCode() == KeyEvent.VK_UP) {
input.setText(inputValue);
System.out.println("up is pressed");
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
});
答案 0 :(得分:6)
在Swing文本组件(如JTextAreas)上使用像KeyListeners这样的低级侦听器时应该注意,因为搞乱这些可能会导致文本组件出错。
如果您想要在之前监听和阻止或更改文本条目,那么如果您正在寻找对文档或DocumentFilter的更改,那么使用DocumentListener会更好。
如果您只是希望收到诸如向上箭头之类的密钥的通知,我将使用密钥绑定 - JTextArea使用什么来通知和响应按键,并将替换密钥绑定新的那一个。如果您小心翼翼地执行此操作,您甚至可以在新操作中调用与按键相关联的原始操作。例如:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class TextAreaTrapUp extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
public TextAreaTrapUp() {
// get JTextArea's InputMap and ActionMap
int condition = JComponent.WHEN_FOCUSED;
InputMap inputMap = textArea.getInputMap(condition);
ActionMap actionMap = textArea.getActionMap();
// get the up keystroke
KeyStroke upKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
String upKey = (String) inputMap.get(upKeyStroke); // get the input map's key for this keystorke
Action originalUpAction = actionMap.get(upKey); // and get the action map's original action for this key
Action newUpAction = new NewUpAction(originalUpAction); // create our new up action passing in the old one
actionMap.put(upKey, newUpAction); // and set this into our ActionMap
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
add(new JScrollPane(textArea));
}
// Action called when up-arrow pressed
private class NewUpAction extends AbstractAction {
private Action originalUpAction; // the original action
public NewUpAction(Action originalUpAction) {
this.originalUpAction = originalUpAction;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Up Arrow Pressed");
// if you want to move the caret up, then call the original action
// as well
if (originalUpAction != null) {
originalUpAction.actionPerformed(e);
}
}
}
private static void createAndShowGui() {
TextAreaTrapUp mainPanel = new TextAreaTrapUp();
JFrame frame = new JFrame("TextAreaTrapUp");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
答案 1 :(得分:2)
你应该覆盖void keypressed而不是keytyped
@Override
public void keyPressed(KeyEvent e) {
System.out.println("test");
if(e.getKeyCode() == KeyEvent.VK_UP) {
input.setText(inputValue);
System.out.println("up is pressed");
}
因为它不是一个特色