我在 Java 中有更多的文本字段。当我按CTRL+时A,我希望所有的文本字段都被选中。我尝试过这种方式,但只有具有焦点的文本字段被选中。
你能帮我吗?
class Main{
public JTextField[] textFields;
private TextFieldSelected(int byteCount) {
textFields = new JTextField[byteCount];
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField(3);
}
private class CtrlAAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
//JTextField textField = (JTextField) e.getComponent();
if(KeyEvent.VK_CONTROL == e.getKeyCode() && e.getModifiers() == 0)
if(KeyEvent.VK_A == e.getKeyCode() && e.getModifiers() ==0)
new SelectAllListener();}}
// for(int i=0; i < textFields.length; i++) textFields[i].selectAll();
class SelectAllListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
for(int i=0; i < textFields.length; i++){
//JTextField field = textFields[i];
// String text=textFields[i].getText();
// textArea.append(text);
textFields[i].selectAll();
}
}
// reset();
// e.consume();
}
}
我改了,还是不行:
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.getDocument().addDocumentListener(documentListener);
KeyBindings keybindings = new KeyBindings(textField);
}
类键绑定{
public KeyBindings(JTextField textField){
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i < textFields.length; i++){
JTextField textField = textFields[i];
for(int j=0;j < textFields.length; j++){
textFields[j].selectAll();
textFields[j].transferFocus();
}
}
}
};
String keyStrokeAndKey = "control A";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
textField.getInputMap().put(keyStroke, keyStrokeAndKey);
textField.getActionMap().put(keyStrokeAndKey, action);
}
}
以及如何使未聚焦的字段也显示选择?