在处理了非常相似的问题之后,我鼓励想要在 JDialog 的组件中添加侦听器的人遵循here 所示的方法。它允许对组件进行更多控制。
以下示例演示了一个自定义对话框,该对话框使用KeyListener 在每次文本更改时验证用户的输入。
public class DialogWithListener extends JDialog {
private JTextField textField = new JTextField();
private boolean userPressedOk = false;
/**
* Creates a dialog that lets the user enter text in a text field.
* <p>
* Each time the user presses a key, the text is validated using the
* {@link Predicate}s in {@code predsAndMsgs}. If the text doesn't satisfy
* all predicates, the dialog shows the message associated with the first
* unsatisfied predicate.
*
* @param predsAndMsgs
* a map from {@link Predicate}s to the messages we'll show to
* users if the text they entered doesn't satisfy the predicates
*/
public DialogWithListener(Map<Predicate<String>, String> predsAndMsgs) {
JLabel textFieldLabel = new JLabel("Enter text:");
// Show this if the text the user entered satisfies our predicates
String okText = "All good";
JLabel statusLabel = new JLabel(okText);
Object[] paneContent = { textFieldLabel, textField, statusLabel };
JButton okButton = new JButton("OK");
okButton.addActionListener(e -> {
userPressedOk = true;
setVisible(false);
});
Object[] options = { okButton };
JOptionPane optionPane = new JOptionPane(paneContent,
JOptionPane.QUESTION_MESSAGE, JOptionPane.DEFAULT_OPTION, null,
options);
getContentPane().add(optionPane);
setLocationRelativeTo(optionPane.getParent());
setFocusTo(textField);
// Check the user input each time a key is released
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent event) {
validate(predsAndMsgs, textField.getText(), okText,
statusLabel, okButton);
}
});
setModal(true);
setResizable(false);
pack();
}
/**
* Validates the {@code textToValidate}.
* <p>
* The {@link Predicate}s in {@link predsAndMsgs} determine whether the text
* is valid. If the text is invalid, we show the message that is associated
* with the predicate and disable this dialog's OK button.
*
* @param predsAndMsgs
* a map from {@link Predicate}s that must hold for the
* {@code textToValidate} to the messages we'll show to the user
* if a predicate is not satisfied.
* @param textToValidate
* we validate this text against the {@link Predicate}s in
* {@link predsAndMsgs}
* @param okText
* this text is shown if the {@code textToValidate} satisfies all
* predicates
* @param statusLabel
* a {@link JLabel} that either shows the {@link okText} or the
* message of the first predicate that doesn't hold true for the
* {@link textToValidate}
* @param okButton
* we enable and disable this button depending on whether the
* {@link textToValidate} is valid
*/
private void validate(Map<Predicate<String>, String> predsAndMsgs,
String textToValidate, String okText, JLabel statusLabel,
JButton okButton) {
// Get the first predicate that the text to validate doesn't satisfy
Optional<Predicate<String>> unsatisfiedPredMaybe = predsAndMsgs
.keySet().stream().filter(pred -> !pred.test(textToValidate))
.findFirst();
// At least one predicate was not satisfied
if (unsatisfiedPredMaybe.isPresent()) {
// Tell the user the text they entered can't be accepted
String msg = predsAndMsgs.get(unsatisfiedPredMaybe.get());
statusLabel.setText(msg);
okButton.setEnabled(false);
} else {
statusLabel.setText(okText);
okButton.setEnabled(true);
}
pack();
}
private void setFocusTo(JComponent comp) {
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
comp.requestFocusInWindow();
}
});
}
public Optional<String> display() {
userPressedOk = false;
// Because the dialog is modal it will block here
setVisible(true);
String dialogResult = null;
if (userPressedOk) {
dialogResult = textField.getText();
}
return Optional.ofNullable(dialogResult);
}
}
这就是您创建和显示对话框的方式:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
JButton showDialogButton = new JButton("Show Dialog");
// Define the predicates that the user entered-text should satisfy and
// the messages shown to the user if it doesn't
Map<Predicate<String>, String> predicatesAndMessages = new HashMap<>();
Predicate<String> dontMentionHisName = text -> !text
.contains("Voldemort");
predicatesAndMessages.put(dontMentionHisName,
"Sssh! You can't say that!");
DialogWithListener dialog = new DialogWithListener(
predicatesAndMessages);
dialog.setTitle("My dialog");
showDialogButton.addActionListener(e -> dialog.display().ifPresent(
userText -> System.out.println(userText)));
frame.getContentPane().add(showDialogButton);
frame.pack();
frame.setVisible(true);
}