2016-11-28 56 views
2

嗨,我正在用java編寫一個聊天服務器項目。在我的客戶端程序中,我使用兩個文本區域。一個顯示客戶端之間的對話另一個輸入客戶的消息。起初我使用了一個TextField,但我想要多行輸入,所以我最終使用了textarea,因爲不存在多行的另一種選擇。當發送按鈕被點擊或按鈕輸入被按下時,我想要獲取文本併發送它。已經知道發送它的代碼和所有其他的東西,但每次我嘗試添加actionListener到textarea時,編譯器不允許我說它不是爲textareas定義的,我想我會和textfield一樣做 類似的東西:如何在java中單擊按鈕時獲取textArea(java)的文本

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

然後

inputTextArea.addActionListener(sendListener); 

任何幫助,請..

+0

請注意編輯以回答。 –

+0

因爲您想將操作添加到'sendButton',而不是'inputTextArea'。 – AxelH

回答

1

正如你所發現的,你不能添加一個ActionListener到JTextArea。您最好的選擇是使用鍵綁定綁定到JTextArea的KeyStroke,並將您的代碼放入用於綁定的AbstractAction中。鍵綁定教程將告訴你細節: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按鍵的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()); 
    } 
} 
+0

真的很好的解決方案,但這不是真的問題。這個問題提到了一個Button ...和代碼使用'sendButton' ... OP只是試圖將Action添加到錯誤的組件中。 – AxelH

相關問題