Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法清除JTextArea(在按下enter键时使用actionlistener。文本区域留下新行(\n))_Java_Swing - Fatal编程技术网

Java 无法清除JTextArea(在按下enter键时使用actionlistener。文本区域留下新行(\n))

Java 无法清除JTextArea(在按下enter键时使用actionlistener。文本区域留下新行(\n)),java,swing,Java,Swing,我正在为我的大学作业做一个小项目。我正在制作一个本地聊天应用程序,通过局域网进行聊天。除了一个小问题,一切都很好。我正在使用文本区域一个可编辑,另一个不可编辑。我正在使用enter键将文本从可编辑文本区域发送到不可编辑文本区域。之后,我希望可编辑的文本区域被清除。我使用的代码是 textmsg.setText(""); 我也用过 textmsg.setText(null); 及 但可编辑文本区域留下了一条新行(“\n”)。 输出如下所示: 我想要的是,当我按下enter键时,如果有文本,消

我正在为我的大学作业做一个小项目。我正在制作一个本地聊天应用程序,通过局域网进行聊天。除了一个小问题,一切都很好。我正在使用文本区域一个可编辑,另一个不可编辑。我正在使用enter键将文本从可编辑文本区域发送到不可编辑文本区域。之后,我希望可编辑的文本区域被清除。我使用的代码是

textmsg.setText("");
我也用过

textmsg.setText(null);

但可编辑文本区域留下了一条新行(“\n”)。 输出如下所示:

我想要的是,当我按下enter键时,如果有文本,消息将进入不可编辑的文本区域。如果它是空的,那么我不希望任何事情发生。 我在程序中使用的确切代码是:

private void send(String message) {
    if(message.equals("")) return;
    console(message);
    textmsg.setText("");
}

public void console(String message) {
    txtHistory.append(message+"\n");
}
textmsg是可编辑的JTextArea。txtHistory是不可编辑的文本区域。 单击按钮和按enter键都可以调用发送功能。 当我使用按钮时,它工作正常,但当我使用enter键时,它工作不正常。

建议:

  • 用于允许可编辑文本区域对enter键做出反应。这将使用Swing自己的绑定
  • 切勿在JTextComponent上添加KeyListener,因为这会干扰文本组件的功能。键绑定更安全、更干净(请参见上面的教程链接)
  • 在绑定中使用的操作中,获取可编辑文本区域的文本,将其附加到其他文本区域,通过调用
    .setText(“”)
比如:

// get text from editable text area
String text = editableTA.getText();
// append to non-editble text area
nonEditableTA.append(text + "\n");
editableTA.setText("");  // clear editable
editableTA.requestFocusInWindow(); // give it focus
比如说

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class RespondToEnter extends JPanel {
    private static final int COLS = 40;
    private JTextArea nonEditableTA = new JTextArea(15, COLS);
    private JTextArea editableTA = new JTextArea(5, COLS);
    private EnterAction enterAction = new EnterAction("Submit");
    // private JButton submitButton = new JButton(enterAction);

    public RespondToEnter() {

        // first set up bindings
        int condition = JComponent.WHEN_FOCUSED; // only want this when textarea has focus
        InputMap inputMap = editableTA.getInputMap(condition); // get input and action maps
        ActionMap actionMap = editableTA.getActionMap();
        // bind to the enter key stroke:
        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        String key = enterStroke.toString();  // key to bind input to action
        // bind the enter key stroke to the enter action:
        inputMap.put(enterStroke, key);
        actionMap.put(key, enterAction);

        // allow word wrap
        nonEditableTA.setWrapStyleWord(true);
        nonEditableTA.setLineWrap(true);
        editableTA.setWrapStyleWord(true);
        editableTA.setLineWrap(true);

        nonEditableTA.setFocusable(false); // this is enough to prevent editing
        JScrollPane nonEdScrollPane = new JScrollPane(nonEditableTA);
        nonEdScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JScrollPane edScrollPane = new JScrollPane(editableTA);
        edScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setLayout(new BorderLayout());
        add(nonEdScrollPane, BorderLayout.CENTER);
        add(edScrollPane, BorderLayout.PAGE_END);       
    }

    // action used in our key bindings
    private class EnterAction extends AbstractAction {
        public EnterAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);  // allow an alt-keystroke mnemonic key
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // get text from editable text area
            String text = editableTA.getText();
            // append to non-editble text area
            nonEditableTA.append(text + "\n");
            editableTA.setText("");  // clear editable
            editableTA.requestFocusInWindow(); // give it focus
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        RespondToEnter mainPanel = new RespondToEnter();
        JFrame frame = new JFrame("Respond To Enter Key");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

是什么触发了上述行为?您的JTextArea如何“知道”已按下enter键?就我自己而言,我会为这个.textmsg.addKeyListener使用键绑定(new KeyAdapter(){public void keyppressed(KeyEvent arg0){if(arg0.getKeyCode()==KeyEvent.VK_ENTER){send(textmsg.getText();}});这就是我实现keylistener的方式。一切正常发送函数被调用消息被追加到txtHistory文本区域。但是textmsg区域保留了新的行,任何人都不能使用添加到文本组件的KeyListener,因为这是非常不干净的,可能会破坏文本组件的固有功能。使用键绑定,如下所示。请查看以了解更多信息。同时避免在注释中显示代码,因为它无法格式化且难以阅读。相反,您的原始问题显示了新代码。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class RespondToEnter extends JPanel {
    private static final int COLS = 40;
    private JTextArea nonEditableTA = new JTextArea(15, COLS);
    private JTextArea editableTA = new JTextArea(5, COLS);
    private EnterAction enterAction = new EnterAction("Submit");
    // private JButton submitButton = new JButton(enterAction);

    public RespondToEnter() {

        // first set up bindings
        int condition = JComponent.WHEN_FOCUSED; // only want this when textarea has focus
        InputMap inputMap = editableTA.getInputMap(condition); // get input and action maps
        ActionMap actionMap = editableTA.getActionMap();
        // bind to the enter key stroke:
        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        String key = enterStroke.toString();  // key to bind input to action
        // bind the enter key stroke to the enter action:
        inputMap.put(enterStroke, key);
        actionMap.put(key, enterAction);

        // allow word wrap
        nonEditableTA.setWrapStyleWord(true);
        nonEditableTA.setLineWrap(true);
        editableTA.setWrapStyleWord(true);
        editableTA.setLineWrap(true);

        nonEditableTA.setFocusable(false); // this is enough to prevent editing
        JScrollPane nonEdScrollPane = new JScrollPane(nonEditableTA);
        nonEdScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JScrollPane edScrollPane = new JScrollPane(editableTA);
        edScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setLayout(new BorderLayout());
        add(nonEdScrollPane, BorderLayout.CENTER);
        add(edScrollPane, BorderLayout.PAGE_END);       
    }

    // action used in our key bindings
    private class EnterAction extends AbstractAction {
        public EnterAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);  // allow an alt-keystroke mnemonic key
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // get text from editable text area
            String text = editableTA.getText();
            // append to non-editble text area
            nonEditableTA.append(text + "\n");
            editableTA.setText("");  // clear editable
            editableTA.requestFocusInWindow(); // give it focus
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        RespondToEnter mainPanel = new RespondToEnter();
        JFrame frame = new JFrame("Respond To Enter Key");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}