我可以保持JDialog关闭转义/输入按下吗?

时间:2015-04-19 18:49:12

标签: java swing jdialog

我创建了一个对话框,用户可以通过用户击键来更改菜单项的键绑定。我想输入和转义为用户可以绑定的键,但它们都关闭对话框。这些印刷机怎么能被拦截?

编辑: 使用JOptionPane和自定义组件

创建对话框
GetKeyComponent comp = new GetKeyComponent(accels, menuItem);
Object[] array = { comp };
JOptionPane optionPane = new JOptionPane(array, 
    JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);

1 个答案:

答案 0 :(得分:5)

  

编辑:使用JOptionPane和自定义组件

创建对话框

一个解决方案:不要这样做。创建自己的模态JDialog,设置其KeyBindings并使用它。如,

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;    
import javax.swing.*;

public class JDialogTest {
   private static void createAndShowGUI() {
      final JFrame frame = new JFrame("JDialogTest");

      JPanel panel = new JPanel();
      panel.add(new JButton(new AbstractAction("Push Me") {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            final JTextArea textArea = new JTextArea(15, 30);
            textArea.setFocusable(false);
            JDialog dialog = new JDialog(frame, "Dialog", true);

            int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
            JPanel contentPane = (JPanel) dialog.getContentPane();
            InputMap inputMap = contentPane.getInputMap(condition);
            ActionMap actionMap = contentPane.getActionMap();

            KeyStroke enterKs = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            inputMap.put(enterKs, enterKs.toString());
            actionMap.put(enterKs.toString(), new AbstractAction() {

               @Override
               public void actionPerformed(ActionEvent arg0) {
                  textArea.append("Enter pushed\n");
               }
            });

            KeyStroke escKs = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
            inputMap.put(escKs, escKs.toString());
            actionMap.put(escKs.toString(), new AbstractAction() {

               @Override
               public void actionPerformed(ActionEvent arg0) {
                  textArea.append("Escape pushed\n");
               }
            });


            dialog.add(new JScrollPane(textArea));
            dialog.pack();
            dialog.setVisible(true);
         }
      }));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(panel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}