在JTextPane具有输入焦点

时间:2017-02-18 14:47:58

标签: java swing jtextpane enter

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

1 个答案:

答案 0 :(得分:3)

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

您可以在此处找到Key Bindings教程: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());
    }
}
相关问题