有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java文本区。setText(“”)不会清除JTextArea中的文本

我正在试图清除JTextArea中的文本,看看其他问题,这似乎是在调用textArea。setText(““/null”)将清除文本区域。我的代码似乎没有出现这种情况,它将新文本附加到该区域中已有的文本中。有人能看到我的代码中有什么错误吗

public class morseJFrame extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JTextPane textPane = new JTextPane();
public JTextArea textArea = new JTextArea();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                morseJFrame frame = new morseJFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public morseJFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 508);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    textPane.setBounds(5, 5, 424, 194);
    textPane.setText("Enter your alphanumberic text here to translate.");
    contentPane.add(textPane);

    JButton btnTranslate = new JButton("Translate");
    btnTranslate.setBounds(5, 419, 213, 41);
    btnTranslate.addActionListener(this);
    add(btnTranslate);
    contentPane.add(btnTranslate);

    textArea.setBounds(5, 210, 424, 203);
    contentPane.add(textArea);

    JButton btnPlaySound = new JButton("Play Morse Sound");
    btnPlaySound.setBounds(228, 419, 201, 41);
    contentPane.add(btnPlaySound);
}

public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (command.equals("Translate")) {
        String text = textPane.getText();
        String translatedText = MorseTranslate.doMorse(text);
        textArea.setText("");
        textArea.setText(translatedText);
    }
}

}


共 (2) 个答案

  1. # 1 楼答案

    This does not seem to be happening with my code, and it appends the new text to the text already in the area

    所以基于这个代码

    String text = textPane.getText();
    String translatedText = MorseTranslate.doMorse(text);
    textArea.setText("");
    textArea.setText(translatedText);
    

    我认为问题出在你的MorseTranslate.doMorse上,它可能会返回附加到它自身的文本

    但是,正如你所看到的,这是一个“猜测工作”的问题,因为我们没有完整的代码

    考虑提供一个证明你的问题的runnable example。这不是一个代码转储,而是您正在做的一个示例,它突出了您所遇到的问题。这将减少混乱和更好的响应

  2. # 2 楼答案

    setText("") doesn't clear the text

    是的

    textArea.setText("");
    

    在这里,您正在清除文本区域

        textArea.setText(translatedText);
    

    在下一行中,您将其设置为其他内容