Java setDefaultButton未按预期工作

Java setDefaultButton未按预期工作,java,swing,Java,Swing,我已经查看了所有与此相关的线程,我不明白为什么按ENTER键不能激活附加到sendButton的actionPerformed方法。是因为文本字段有一个FocusListener吗 我尝试过的事情: 将语句更改为特定文本字段的目标(InChartExtArea) 已将setVisible语句移到末尾 在按enter键时针对GUI的不同部分 请记住,我只提供了构建GUI的代码,以减少您的时间浪费 我想要的:理想情况下,我想保留我的FocusListener(或类似的东西),这样我就可以显示“文

我已经查看了所有与此相关的线程,我不明白为什么按ENTER键不能激活附加到sendButton的actionPerformed方法。是因为文本字段有一个FocusListener吗

我尝试过的事情:

  • 将语句更改为特定文本字段的目标(InChartExtArea)
  • 已将setVisible语句移到末尾
  • 在按enter键时针对GUI的不同部分
请记住,我只提供了构建GUI的代码,以减少您的时间浪费


我想要的:理想情况下,我想保留我的FocusListener(或类似的东西),这样我就可以显示“文本字段提示”。我想能够在InChartExtArea字段聚焦时按ENTER键发送用户的文本。

如果JFrame上的某个组件具有焦点,并且可以接受ENTER键按下,例如一个JTextAreas,然后按enter键将转到该组件,而不是默认按钮。要使默认按钮正常工作,JFrame或按钮或其他不接受enter键的组件需要具有焦点。我猜你的一个JTextArea已经偷走了焦点,这会把你搞砸

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