将JOptionPane.showConfirmDialog用于多个输入:
int result = JOptionPane.showConfirmDialog(null, panel,
prompt, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
该面板按以下方式构建:
JTextField percentField = new JTextField(5);
JComboBox cb = new JComboBox(movingAveragesList);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Enter %:"));
myPanel.add(percentField);
myPanel.add(Box.createHorizontalStrut(5)); // a spacer
myPanel.add(new JLabel("Select MA:"));
myPanel.add(cb);
当用户输入%字段并点击返回时,代码将返回,但不会完成组合框选择。返回键==单击确定按钮。无论如何要解决这个问题,所以OK按钮在返回之前需要点击?
答案 0 :(得分:1)
两个选项:
(可能更多)
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JTextField percentField = new JTextField(5);
// get the JTextField's action and input map
ActionMap actionMap = percentField.getActionMap();
int condition = JComponent.WHEN_FOCUSED; // only interested in the input where we have focus
InputMap inputMap = percentField.getInputMap(condition);
// get the key for the enter key press in the input map
Object enterKey = inputMap.get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
// now re-assign its entry in the action map to tab to next component
actionMap.put(enterKey, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
}
});
String[] myData = { "One", "Two", "Three", "Four" };
JComboBox cb = new JComboBox(myData);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Enter %:"));
myPanel.add(percentField);
myPanel.add(Box.createHorizontalStrut(5)); // a spacer
myPanel.add(new JLabel("Select MA:"));
myPanel.add(cb);
String prompt = "Please Select";
int result = JOptionPane.showConfirmDialog(null, myPanel, prompt,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JTextField percentField = new JTextField(5);
percentField.addActionListener(e -> {
KeyboardFocusManager manager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
});
String[] myData = { "One", "Two", "Three", "Four" };
JComboBox cb = new JComboBox(myData);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Enter %:"));
myPanel.add(percentField);
myPanel.add(Box.createHorizontalStrut(5)); // a spacer
myPanel.add(new JLabel("Select MA:"));
myPanel.add(cb);
String prompt = "Please Select";
int result = JOptionPane.showConfirmDialog(null, myPanel, prompt,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
});
}