Displays a dialog for renaming or creating a new tab
(String prompt, String oldName)
| 364 | * Displays a dialog for renaming or creating a new tab |
| 365 | */ |
| 366 | protected void promptForTabName(String prompt, String oldName) { |
| 367 | final JTextField field = new JTextField(oldName); |
| 368 | |
| 369 | field.addKeyListener(new KeyAdapter() { |
| 370 | // Forget ESC, the JDialog should handle it. |
| 371 | // Use keyTyped to catch when the feller is actually added to the text |
| 372 | // field. With keyTyped, as opposed to keyPressed, the keyCode will be |
| 373 | // zero, even if it's enter or backspace or whatever, so the key char |
| 374 | // should be used instead. Grr. |
| 375 | public void keyTyped(KeyEvent event) { |
| 376 | //System.out.println("got event " + event); |
| 377 | char ch = event.getKeyChar(); |
| 378 | |
| 379 | //noinspection StatementWithEmptyBody |
| 380 | if ((ch == '_') || (ch == '.') || // allow.pde and .java |
| 381 | (('A' <= ch) && (ch <= 'Z')) || (('a' <= ch) && (ch <= 'z'))) { |
| 382 | // These events are allowed straight through. |
| 383 | |
| 384 | } else if (ch == ' ') { |
| 385 | String t = field.getText(); |
| 386 | int start = field.getSelectionStart(); |
| 387 | int end = field.getSelectionEnd(); |
| 388 | field.setText(t.substring(0, start) + "_" + t.substring(end)); |
| 389 | field.setCaretPosition(start + 1); |
| 390 | event.consume(); |
| 391 | |
| 392 | } else if ((ch >= '0') && (ch <= '9')) { |
| 393 | // getCaretPosition == 0 means that it's the first char |
| 394 | // and the field is empty. |
| 395 | // getSelectionStart means that it *will be* the first |
| 396 | // char, because the selection is about to be replaced |
| 397 | // with whatever is typed. |
| 398 | if (field.getCaretPosition() == 0 || |
| 399 | field.getSelectionStart() == 0) { |
| 400 | // number not allowed as first digit |
| 401 | event.consume(); |
| 402 | } |
| 403 | } else if (ch == KeyEvent.VK_ENTER) { |
| 404 | // Slightly ugly hack that ensures OK button of the dialog consumes |
| 405 | // the Enter key event. Since the text field is the default component |
| 406 | // in the dialog, OK doesn't consume Enter key event, by default. |
| 407 | Container parent = field.getParent(); |
| 408 | while (!(parent instanceof JOptionPane pane)) { |
| 409 | parent = parent.getParent(); |
| 410 | } |
| 411 | final JPanel pnlBottom = (JPanel) |
| 412 | pane.getComponent(pane.getComponentCount() - 1); |
| 413 | for (int i = 0; i < pnlBottom.getComponents().length; i++) { |
| 414 | Component component = pnlBottom.getComponents()[i]; |
| 415 | if (component instanceof final JButton okButton) { |
| 416 | if (okButton.getText().equalsIgnoreCase("OK")) { |
| 417 | ActionListener[] actionListeners = |
| 418 | okButton.getActionListeners(); |
| 419 | if (actionListeners.length > 0) { |
| 420 | actionListeners[0].actionPerformed(null); |
| 421 | event.consume(); |
| 422 | } |
| 423 | } |
no test coverage detected