2016-11-28 16 views
2

안녕하세요, 저는 클라이언트 프로그램에서 java.lang의 채팅 서버 프로젝트를 작성하고 있습니다. 두 개의 텍스트 영역을 사용합니다. 클라이언트간에 대화를 표시합니다. 다른 하나는 클라이언트의 메시지를 입력합니다. 처음에는 TextField를 사용했지만 여러 줄을 입력하고 싶습니다. 그래서 마침내 textarea를 사용했습니다. 여러 줄을위한 다른 선택 사항이 없습니다. 보낼 단추를 클릭하거나 입력을 밀어 넣을 때 텍스트를 보내고 싶습니다. 이미 그 코드와 다른 모든 것들을 보내는 코드를 알고 있지만, textarea에 actionListener를 추가하려고 할 때마다 컴파일러가 텍스트 영역을 정의하지 않는다고 말하면서 나에게 허용합니다. 텍스트 필드를 사용할 때와 똑같이 할 것이라고 생각했습니다. 그런 일 :자바에서 버튼을 클릭했을 때 textArea (java) 텍스트를 얻는 방법

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

다음

inputTextArea.addActionListener(sendListener); 

도움 바랍니다 ..

+0

대답하는 편집을 유의하시기 바랍니다. –

+0

'inputTextArea'가 아닌'sendButton'에 액션을 추가하기를 원합니다. – AxelH

답변

1

알아 내고있는 것처럼 JTextArea에 ActionListener를 추가 할 수 없습니다. 가장 좋은 방법은 Key Binding을 사용하여 JTextArea의 VK_ENTER 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()); 
    } 
} 

편집 : 새 버전이 이제 Enter 키를 원래처럼 작동하는 키 조합을 Ctrl 키를 입력 할 수 있습니다. 이것은 원래받는 지금 키 입력에 매핑 작업 매핑하여 작동 키 Ctrl 키를 - 입력 :

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

정말 좋은 솔루션이지만 이것은 실제로 문제가 아니 었습니다. 문제는 버튼을 언급하고 ... 코드는'sendButton'을 사용합니다 ... OP는 단지 잘못된 Component에 Action을 추가하려했습니다. – AxelH