如何在java中单击按钮时获取textArea的文本

时间:2016-11-28 23:36:22

标签: java swing keystroke

大家好我正在用java编写聊天服务器项目。在我的客户端程序中,我使用了两个文本区域。一个用于显示客户端之间的对话,另一个用于输入客户端消息。起初我使用了TextField,但我想要输入多行,所以我最后使用了textarea,因为没有多行的另一种选择..当点击发送按钮或按下输入时我想获取文本并发送它..我已经知道发送它和所有其他东西的代码,但每次我尝试将actionListener添加到textarea时,编译器不允许我说它没有为textareas定义,我想我会像使用textfield那样做 类似的东西:

ActionListener sendListener = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
          if (e.getSource() == sendButton){
                String str = inputTextArea.getText();}
    }
};

然后

inputTextArea.addActionListener(sendListener);

任何帮助请...

1 个答案:

答案 0 :(得分:2)

当您发现时,您无法将ActionListener添加到JTextArea。最好的办法是使用Key Bindings绑定到JTextArea的VK_ENTER KeyStroke,并将您的代码放在用于绑定的AbstractAction中。 Key Binding教程将向您展示详细信息:Key Binding Tutorial

例如:

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

import javax.swing.*;

@SuppressWarnings("serial")
public class KeyBindingEg extends JPanel {
    private static final int LARGE_TA_ROWS = 20;
    private static final int TA_COLS = 40;
    private static final int SMALL_TA_ROWS = 3;
    private JTextArea largeTextArea = new JTextArea(LARGE_TA_ROWS, TA_COLS);
    private JTextArea smallTextArea = new JTextArea(SMALL_TA_ROWS, TA_COLS);
    private Action submitAction = new SubmitAction("Submit", KeyEvent.VK_S);
    private JButton submitButton = new JButton(submitAction);

    public KeyBindingEg() {
        // set up key bindings
        int condition = JComponent.WHEN_FOCUSED; // only bind when the text area is focused
        InputMap inputMap = smallTextArea.getInputMap(condition);
        ActionMap actionMap = smallTextArea.getActionMap();
        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        inputMap.put(enterStroke, enterStroke.toString());
        actionMap.put(enterStroke.toString(), submitAction);

        // set up GUI            
        largeTextArea.setFocusable(false); // this is for display only
        largeTextArea.setWrapStyleWord(true);
        largeTextArea.setLineWrap(true);
        smallTextArea.setWrapStyleWord(true);
        smallTextArea.setLineWrap(true);
        JScrollPane largeScrollPane = new JScrollPane(largeTextArea);
        JScrollPane smallScrollPane = new JScrollPane(smallTextArea);
        largeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        smallScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(smallScrollPane, BorderLayout.CENTER);
        bottomPanel.add(submitButton, BorderLayout.LINE_END);

        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        setLayout(new BorderLayout(3, 3));
        add(largeScrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class SubmitAction extends AbstractAction {
        public SubmitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = smallTextArea.getText();
            smallTextArea.selectAll(); // keep text, but make it easy to replace
            // smallTextArea.setText(""); // or if you want to clear the text
            smallTextArea.requestFocusInWindow();

            // TODO: send text to chat server here

            // record text in our large text area
            largeTextArea.append("Me> ");
            largeTextArea.append(text);
            largeTextArea.append("\n");
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Key Binding Eg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new KeyBindingEg());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

编辑:新版本现在允许Ctrl-Enter组合键作为Enter键最初工作。这可以通过将最初映射到Enter键击的Action映射到Ctrl-Enter键击:

来实现
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class KeyBindingEg extends JPanel {
    private static final int LARGE_TA_ROWS = 20;
    private static final int TA_COLS = 40;
    private static final int SMALL_TA_ROWS = 3;
    private JTextArea largeTextArea = new JTextArea(LARGE_TA_ROWS, TA_COLS);
    private JTextArea smallTextArea = new JTextArea(SMALL_TA_ROWS, TA_COLS);
    private Action submitAction = new SubmitAction("Submit", KeyEvent.VK_S);
    private JButton submitButton = new JButton(submitAction);

    public KeyBindingEg() {
        // set up key bindings
        int condition = JComponent.WHEN_FOCUSED; // only bind when the text area
                                                 // is focused
        InputMap inputMap = smallTextArea.getInputMap(condition);
        ActionMap actionMap = smallTextArea.getActionMap();

        // get enter and ctrl-enter keystrokes
        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        KeyStroke ctrlEnterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK);

        // get original input map key for the enter keystroke
        String enterKey = (String) inputMap.get(enterStroke);
        // note that there is no key in the map for the ctrl-enter keystroke --
        // it is null

        // extract the old action for the enter key stroke
        Action oldEnterAction = actionMap.get(enterKey);
        actionMap.put(enterKey, submitAction); // substitute our new action

        // put the old enter Action back mapped to the ctrl-enter key
        inputMap.put(ctrlEnterStroke, ctrlEnterStroke.toString());
        actionMap.put(ctrlEnterStroke.toString(), oldEnterAction);

        largeTextArea.setFocusable(false); // this is for display only
        largeTextArea.setWrapStyleWord(true);
        largeTextArea.setLineWrap(true);
        smallTextArea.setWrapStyleWord(true);
        smallTextArea.setLineWrap(true);
        JScrollPane largeScrollPane = new JScrollPane(largeTextArea);
        JScrollPane smallScrollPane = new JScrollPane(smallTextArea);
        largeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        smallScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(smallScrollPane, BorderLayout.CENTER);
        bottomPanel.add(submitButton, BorderLayout.LINE_END);

        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        setLayout(new BorderLayout(3, 3));
        add(largeScrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class SubmitAction extends AbstractAction {
        public SubmitAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = smallTextArea.getText();
            smallTextArea.selectAll(); // keep text, but make it easy to replace
            // smallTextArea.setText(""); // or if you want to clear the text
            smallTextArea.requestFocusInWindow();

            // TODO: send text to chat server here

            // record text in our large text area
            largeTextArea.append("Me> ");
            largeTextArea.append(text);
            largeTextArea.append("\n");
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Key Binding Eg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new KeyBindingEg());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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