Re[8]: Работа с клавиатурой в java
От: Аноним  
Дата: 15.03.04 09:09
Оценка:
Интересно но при вводе '(' нажимается кнопка Down
не знаю почему


import javax.swing.*;
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);
    JScrollPane sp = new JScrollPane(t1);
 
    public Test() {
        t1.setFocusable(true);
        t1.setEditable(false);

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

        keyRegistry(c, inputMap, '(');
        keyRegistry(c, inputMap, KeyEvent.VK_UP, jButton5);
        keyRegistry(c, inputMap, KeyEvent.VK_DOWN, jButton6);

        jPanel1.add(sp);
        jPanel1.add(jButton5);
        jPanel1.add(jButton6);
        c.add(jPanel1, BorderLayout.CENTER);
        c.setFocusable(true);
    }
    public void keyRegistry(JComponent c1, InputMap inputMap1, char ch) {
        inputMap1.put(KeyStroke.getKeyStroke(ch), "alph" + (int) ch);
        c1.getActionMap().put("alph" + (int) ch, new MyAbstractAction1(ch));
    }
    public void keyRegistry(JComponent c1, InputMap inputMap1, int ch, JButton jb) {
        inputMap1.put(KeyStroke.getKeyStroke(ch, 0), "alph" + ch);
        c1.getActionMap().put("alph" + (int) ch, new MyAbstractAction(jb));
    }

    private class MyAbstractAction extends AbstractAction {
        private JButton jb;
        public MyAbstractAction(JButton jb) {
            this.jb = jb;
        }
        public void actionPerformed(ActionEvent e) {
            jb.doClick();
        }
    }

    private class MyAbstractAction1 extends AbstractAction {
        private char ch = ' ';
        public MyAbstractAction1(char ch) {
            this.ch = ch;
        }
        public void actionPerformed(ActionEvent e) {
            t1.append("" + (char) ch);
        }
    }
    public static void main(String args[]) {
        Test frame = new Test();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(200, 200, 300, 200);
        frame.show();
    }
}
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.