简体   繁体   English

Java事件KeyPress键盘

[英]Java Event KeyPress Keyboard

I have this class. 我上这堂课 This class paints 3 buttons, and I have an event associated with each button. 此类绘制3个按钮,并且每个按钮都有一个事件。 I need to create an event for the keyboard, pressing a key will be the same as pressing one of the buttons. 我需要为键盘创建一个事件,按下一个键将与按下其中一个按钮相同。 This is my class: 这是我的课:

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());
        }
    }
}

Someone can help me?? 有人可以帮助我吗?

I need to create an event for the keyboard, pressing a key will be the same as pressing one of the buttons. 我需要为键盘创建一个事件,按下一个键将与按下其中一个按钮相同。

You need to: 你需要:

  1. Create an Action to be used by each button. 创建要由每个按钮使用的Action See How to Use Actions 请参阅如何使用动作
  2. Create the JButton using the Action 使用Action创建JButton
  3. Create Key Bindings for the Action and KeyStroke . ActionKeyStroke创建Key Bindings See How to Use Key Bindings 请参阅如何使用键绑定

Simple example: 简单的例子:

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();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM