【问题标题】:Show JOptionPane on Enter key being pressed while JTextPane has input focus在 JTextPane 具有输入焦点时按下 Enter 键时显示 JOptionPane
【发布时间】:2017-07-08 02:01:58
【问题描述】:

我有一个JTextPane 组件,用于输出一些文本并允许用户向同一组件输入数据。有没有办法实现这样的功能,如果用户按 Enter 键,显示JOptionPane

【问题讨论】:

  • 当用户按下回车键时,哪个组件应该具有焦点,文本窗格还是按钮?如果是文本窗格,则按钮与它无关。如果是按钮,文本窗格与它无关。
  • 我误读了这个问题。哦!
  • 它的文本面板
  • @HovercraftFullOfEels,我猜 OP 的意思是“键盘上的 Enter 键”,因此为 Enter KeyStroke 创建自定义键绑定的解决方案是正确的。
  • @camickr:谢谢你

标签: java swing jtextpane enter


【解决方案1】:

考虑在 JTextPane 上设置键绑定,这样当按下回车键 KeyEvent.VK_ENTER 时,它会触发一个显示 JOptionPane 的 AbstractAction。与所有键绑定一样,这意味着获取 JTextPanes InputMap 和 ActionMap 并将它们与一些常量键 String 绑定在一起。

您可以在此处找到键绑定教程:Key Bindings

例如,

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TextPaneBinding extends JPanel {
    private JTextPane textPane = new JTextPane();

    public TextPaneBinding() {

        // get the enter key stroke and create a key String for binding from it
        KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        String bindingKey = enterKeyStroke.toString();

        // get our input map and action map
        int condition = JComponent.WHEN_FOCUSED;
        InputMap inputMap = textPane.getInputMap(condition); // only want when focused
        ActionMap actionMap = textPane.getActionMap();

        // set up the binding of the key stroke to the action
        inputMap.put(enterKeyStroke, bindingKey);
        actionMap.put(bindingKey, new MyAction());

        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(300, 300));
        add(new JScrollPane(textPane));
    }

    private class MyAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            String message = "This is the JOptionPane Message";
            String title = "My Title";
            int messageType = JOptionPane.INFORMATION_MESSAGE;
            JOptionPane.showMessageDialog(textPane, message, title, messageType);
        }
    }

    private static void createAndShowGui() {
        TextPaneBinding mainPanel = new TextPaneBinding();

        JFrame frame = new JFrame("TextPaneBinding");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    相关资源
    最近更新 更多