开发者

capture key press within frame

开发者 https://www.devze.com 2023-03-16 02:18 出处:网络
This seems like a simp开发者_C百科le behavior, but I\'m having difficulty making it happen.I\'m working on software which graphs data.I want to redraw the graph when the user hits enter.Well more accu

This seems like a simp开发者_C百科le behavior, but I'm having difficulty making it happen. I'm working on software which graphs data. I want to redraw the graph when the user hits enter. Well more accurately I want to draw the graph when the user hits enter and doesn't have a text field selected; but for now I'll be satisfied with drawing whenever the user hits enter.

I tried installing a basic KeyListener to the frame first, but that doesn't work since the JFrame children, not the frame, receive the event.

I then tried to use the KeyEventDispatcher, but it's proving too global a concept. I can have two graphs on screen at once, and an old graph can be closed or replaced with a new graph. With the KeyEventDispatcher I have no easy way of knowing which plot I want to activate out of the multiple plots open at a time and the plots currently open now may not be the plots that were opened when I instantiated the key dispatcher. I know this solution could still work, but it requires my storing extra data as to what plot is currently active that doesn't fit well into the program architecture.

It seems as if there should be an easier method to capture any KeyEvents dispatched to a JFrame/JPanel or any of the JFrame's children; but ignore events dispatched to other frames. Preferable a method that can be added to the frame and thus is automatically disposed when the frame is disposed. Can anyone suggest a simpler method then what I've tried?


Don't use a KeyListener.

Add a Key Binding to the graph panel.


This works very well

this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "fecharAction");
    this.getRootPane().getActionMap().put("fecharAction", new AbstractAction() {
        private static final long serialVersionUID = 1L;
        @Override
        public void actionPerformed(ActionEvent e) {
            int resp = JOptionPane.showConfirmDialog(MainForm.this, "Encerrar sistema?", "Confirmação", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (resp == 0) {
                MainForm.this.setVisible(false);
                MainForm.this.dispose();
            }
        }
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号