首页  >  文章  >  Java  >  如何使用 Java 中的操作为 JButton 分配快捷键?

如何使用 Java 中的操作为 JButton 分配快捷键?

DDD
DDD原创
2024-10-23 23:53:30353浏览

How Can I Assign a Shortcut Key to a JButton Using an Action in Java?

如何在 Java 中使用 JButton 的快捷键

为 JButton 分配快捷键时,您希望按钮能够响应当没有鼠标按下某个键时。这可以通过为按钮创建一个操作来实现。然后,Action 由 ActionListener 配置,并连接到 KeyStroke。

请参阅 Swing 教程以获取各种资源,包括以下部分:

  • 如何使用操作
  • 如何使用按键绑定

示例:

<code class="java">import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
// Use Action here
    private JTextField display;

    public CalculatorPanel()
    {
// Implement Action here
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                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(30, 30) );
            buttonPanel.add( button );

// Implement KeyStroke here
            InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            buttonPanel.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
        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();
            }
        });
    }
}</code>

以上是如何使用 Java 中的操作为 JButton 分配快捷键?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn