我将JComboBox设置为可编辑,我希望用户在按下回车键后能够跳转到下一个控件。我已经尝试了很多方法,但没有一个工作,其中一个事件被成功激活(EditorCompoment.keyRelease)但是方法“transferFocus()”不会将焦点转移到下一个控件。 任何帮助深表感谢。 感谢
public static void addEnterKeyListener(final javax.swing.JComboBox field)
{
field.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
field.setFocusTraversalKeysEnabled(false);
Action myAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
field.transferFocus();
}
};
field.getActionMap().put("enter-action", myAction);
field.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "enter-action");
field.addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(final KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("Pressed enter inside JComboBox");
field.transferFocus();
}
}
});
field.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(final KeyEvent e)
{
System.out.println("Pressed enter inside JComboBox #2");
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
field.transferFocus();
/*This will fire but will not transfer the focus to the next control*/
System.out.println("Transfered the focus from JComboBox");
}
}
});
field.getEditor().addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent arg0)
{
field.transferFocus();
}
});
System.out.println("Added enter events to JComboBox");
}
答案 0 :(得分:1)
将ActionListener应用于组合编辑器的editorComponent(JTextField):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxDemo implements Runnable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new JComboBoxDemo());
}
public void run()
{
JComboBox comboBox = new JComboBox(new String[]{"A", "B", "C"});
comboBox.setEditable(true);
final JTextField editorComponent = (JTextField) comboBox.getEditor().getEditorComponent();
editorComponent.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
editorComponent.transferFocus();
}
});
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JLabel("Field 1"));
panel.add(comboBox);
panel.add(new JLabel("Field 2"));
panel.add(new JTextField(10));
panel.add(new JLabel("Field 3"));
panel.add(new JTextField(10));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
Container c = frame.getContentPane();
c.setLayout(new BorderLayout());
c.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}