Re[3]: Работа с клавиатурой в java
От: Lucker Беларусь http://lucker.intervelopers.com/
Дата: 12.03.04 18:25
Оценка:

import javax.swing.*;
import javax.swing.text.EditorKit;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

public class Test extends JFrame {
    JPanel jPanel1 = new JPanel();
    JButton jButton5 = new JButton("UP");
    JButton jButton6 = new JButton("Down");
    JTextArea t1 = new JTextArea(5, 25);

    public Test() {
        t1.setFocusable(true);
        //t1.setEditable(false);

        JComponent c = (JComponent) getContentPane();
        InputMap inputMap = c.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        Action upButton = keyRegistry(c, inputMap, KeyEvent.VK_UP, jButton5);
        Action downButton = keyRegistry(c, inputMap, KeyEvent.VK_DOWN, jButton6);

        EditorKit editorKit = t1.getUI().getEditorKit(t1);
        if (editorKit instanceof DefaultEditorKit) {
            Action upAtcion = t1.getActionMap().get(DefaultEditorKit.upAction);
            Action downAtion = t1.getActionMap().get(DefaultEditorKit.downAction);

            t1.getActionMap().put(DefaultEditorKit.upAction, new CompoudAction(upAtcion, upButton));
            t1.getActionMap().put(DefaultEditorKit.downAction, new CompoudAction(downAtion, downButton));
        }

        jPanel1.add(t1);
        jPanel1.add(jButton5);
        jPanel1.add(jButton6);
        c.add(jPanel1, BorderLayout.CENTER);
        c.setFocusable(true);
    }

    public Action keyRegistry(JComponent c1, InputMap inputMap1, int ch, JButton jb) {
        final Action action = new MyAbstractAction(jb);
        inputMap1.put(KeyStroke.getKeyStroke(ch, 0), "alph" + ch);
        c1.getActionMap().put("alph" + (int) ch, action);
        return action;
    }

    private class MyAbstractAction extends AbstractAction {
        private JButton jb;

        public MyAbstractAction(JButton jb) {
            this.jb = jb;
        }

        public void actionPerformed(ActionEvent e) {
            jb.doClick();
        }
    }

    private class CompoudAction extends AbstractAction {
        private final Action first, second;

        public CompoudAction(Action firs, Action second) {
            this.first = firs;
            this.second = second;
        }

        public void actionPerformed(ActionEvent e) {
            first.actionPerformed(e);
            second.actionPerformed(e);
        }
    }

    public static void main(String args[]) {
        Test frame = new Test();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(200, 200, 300, 200);
        frame.show();
    }
}

у мнея работает
1.4.2_02 XP
... << RSDN@Home 1.1.3 stable >>
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.