Java事件KeyPress键盘

时间:2014-05-05 09:17:07

标签: java swing events key-bindings

我有这门课。这个类描绘了3个按钮,我有一个与每个按钮相关的事件。我需要为键盘创建一个事件,按一个键就像按下其中一个按钮一样。这是我的班级:

public class ShapedDialog extends JDialog implements KeyListener, ActionListener {

private final MainWindow parent;

public ShapedDialog(MainWindow parent, String title) {
    super(parent, title, true);
    this.parent = parent;

    if (parent != null) {
        Dimension parentSize = parent.getSize();
        Point p = parent.getLocation();
        setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
    }

    JPanel messagePane = new JPanel();
    messagePane.add(new JLabel());
    getContentPane().add(messagePane);

    JPanel buttonPane = new JPanel();

    //JButton1
    JButton jButton1 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton1.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    //JButton2
    JButton jButton2 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton2.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    //JButton3
    JButton jButton3 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton3.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    //Add buttons in the panel
    buttonPane.setLayout(new GridLayout(3, 3));
    buttonPane.add(jButton1);
    buttonPane.add(jButton2);
    buttonPane.add(jButton3);

    getContentPane().add(buttonPane, BorderLayout.SOUTH);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    pack();
    setVisible(true);
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 1");
    dispose();
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 2");
    dispose();
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 3");
    dispose();
}

@Override
public void actionPerformed(ActionEvent e) {
    setVisible(false);
    parent.setMyPackage("Type Package");
    dispose();
}

    public static void main(String[] a) {
        JTextField component = new JTextField();
        component.addKeyListener(new MyKeyListener());

        ShapedDialog dlg = new ShapedDialog((MainWindow) new JFrame(), "title");
    }

    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

class MyKeyListener extends KeyAdapter {
    public void keyPressed(KeyEvent evt) {
        if (evt.getKeyChar() == 'a') {
            System.out.println("Check for key characters: " + evt.getKeyChar());
        }
        if (evt.getKeyCode() == KeyEvent.VK_HOME) {
            System.out.println("Check for key codes: " + evt.getKeyCode());
        }
    }
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

  

我需要为键盘创建一个事件,按一个键就像按下其中一个键一样。

你需要:

  1. 创建每个按钮使用的Action。请参阅How to Use Actions
  2. 使用Action
  3. 创建JButton
  4. Key BindingsAction创建KeyStroke。请参阅How to Use Key Bindings
  5. 简单示例:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class CalculatorPanel extends JPanel
    {
        private JTextField display;
    
        public CalculatorPanel()
        {
            Action numberAction = new AbstractAction()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    display.setCaretPosition( display.getDocument().getLength() );
                    display.replaceSelection(e.getActionCommand());
                }
            };
    
            setLayout( new BorderLayout() );
    
            display = new JTextField();
            display.setEditable( false );
            display.setHorizontalAlignment(JTextField.RIGHT);
            add(display, BorderLayout.NORTH);
    
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout( new GridLayout(0, 5) );
            add(buttonPanel, BorderLayout.CENTER);
    
            for (int i = 0; i < 10; i++)
            {
                String text = String.valueOf(i);
                JButton button = new JButton( text );
                button.addActionListener( numberAction );
                button.setBorder( new LineBorder(Color.BLACK) );
                button.setPreferredSize( new Dimension(50, 50) );
                buttonPanel.add( button );
    
                KeyStroke pressed = KeyStroke.getKeyStroke(text);
                InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                inputMap.put(pressed, text);
                button.getActionMap().put(text, numberAction);
            }
        }
    
        private static void createAndShowUI()
        {
    //      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );
    
            JFrame frame = new JFrame("Calculator Panel");
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.add( new CalculatorPanel() );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }