2015-09-05 126 views
0
public JoinChatClient(String serverAddress, String chatName) 
    { 
     chatWindow.getContentPane().add(sendButton, "South"); 
     chatWindow.getContentPane().add(splitPane, "Center"); 
     chatWindow.setSize(800,500); 
     sendButton.addActionListener(this); 
     chatWindow.setTitle("Chat Room"); 
     chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     splitPane.setDividerLocation(350); 
     sendButton.setBackground(Color.gray); 
     sendButton.setForeground(Color.red); 
     outChatTextArea.setEditable(false); 
     inChatTextArea.setFont (new Font("default",Font.ITALIC,20)); 
     outChatTextArea.setFont(new Font("default",Font.BOLD,20)); 
     inChatTextArea.setLineWrap(true); 
     outChatTextArea.setLineWrap(true); 
     inChatTextArea.setWrapStyleWord(true); 
     outChatTextArea.setWrapStyleWord(true); 
     inChatTextArea.setText("Enter text to be sent here."); 
     outChatTextArea.setText("You can move the separator bar!"); 
     inChatTextArea.addFocusListener(new FocusListener() { 
      public void focusGained(FocusEvent e) { 
       if(inChatTextArea.getText().equals("Enter text to be sent here.")) 
       { 
        inChatTextArea.setText(""); 
        inChatTextArea.setFont(new Font("default",Font.BOLD,20)); 
       } 
      } 
      public void focusLost(FocusEvent e) { 
       if(inChatTextArea.getText().isEmpty()) 
       { 
        inChatTextArea.setFont (new Font("default",Font.ITALIC,20)); 
        inChatTextArea.setText("Enter text to be sent here."); 
       } 
      } 
     }); 
     chatWindow.getRootPane().setDefaultButton(sendButton); 
     chatWindow.setVisible(true); 
    } 

我看過了所有的線程我能找到關於這一點,我想不通爲什麼按下回車鍵不激活連接到sendButton actionPerformed方法。是否因爲文本字段有FocusListener?setDefaultButton工作不正常

事情我已經嘗試:

  • 改變語句來針對特定的文本字段(inChatTextArea)
  • 移動調用setVisible語句結束
  • 按下回車鍵時,有針對性的GUI的不同部分

請記住,我只包含構建GUI的代碼,以減少浪費時間。

我想要什麼:理想情況下,我想保留我的FocusListener(或類似的東西),以便我可以顯示「文本字段提示」。我希望能夠在inChatTextArea字段集中時按ENTER發送用戶的文本。

回答

1

如果JFrame上的某個組件具有焦點,並且可以接受一個Enter鍵的按下,例如其中一個JTextAreas,則輸入按將轉到該組件,而不是默認按鈕。對於默認按鈕的工作,然後JFrame或按鈕或其他組件不接受輸入按鍵,需要有焦點。我猜你的一個JTextAreas已經偷走了焦點,而這讓你感到困惑。