k.explorer k.explorer - 3 days ago 6
Java Question

how to get the text of a textArea (java) when button is clicked in java

Hi guys i am writing a chat-server project in java.In my client program i use two text areas.One to show the conversation between clients and the other to input for the client's message. At first i used a TextField but i want multiple lines for input so i finally used textarea as there isnt another choice for multiple lines..When send button is clicked or button enter is pushed i want to get the text and send it ..I already know the code to send it and all the other stuff but each time i try to add actionListener to the textarea, compiler doesnt allow me by saying that it is not define for textareas , i thought i would do the same as if with textfield
something like that:

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


and then

inputTextArea.addActionListener(sendListener);


any help please..

Answer

As you're finding out, you can't add an ActionListener to a JTextArea. Your best bet is to use Key Bindings to bind to JTextArea's the VK_ENTER KeyStroke, and put your code in the AbstractAction that you use for the binding. The Key Binding tutorial will show you the details: Key Binding Tutorial

For example:

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

Edit: new version now allow the Ctrl-Enter key combination to work as the Enter key originally did. This works by mapping the Action originally mapped to the Enter keystroke now to the Ctrl-Enter keystroke:

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