Delete only selected text in the text area

I want to remove selected text in the text area using Java Swing, but I could not find a way to do this. At some point, I thought about using textArea.setText("");, but when I do this, it clears everything. Can someone help me with this?

Here is the code that I have written so far,

public class DeleteTest extends JFrame implements ActionListener {

JPanel panel;
JTextArea textArea;
JButton button;

public DeleteTest() {

    setVisible(true);
    setSize(500, 500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    panel = new JPanel();
    panel.setBackground(getBackground().BLACK);
    textArea = new JTextArea(300, 300);
    button = new JButton("clear");

    button.addActionListener(this);

    panel.add(button);

    add(textArea, BorderLayout.CENTER);
    add(panel, BorderLayout.SOUTH);

}

@Override
public void actionPerformed(ActionEvent arg0) {
    if (arg0.getSource()==button){
        String selected=textArea.getSelectedText();
        if(!selected.equals("")){


        }
    }

}

public static void main(String[] args) {
    Runnable r = new Runnable() {

        @Override
        public void run() {
            DeleteTest de = new DeleteTest();

        }
    };

    SwingUtilities.invokeLater(r);

}

}

+4
source share
2 answers

If you want to delete only the selected text, try the following:

textArea.setText(textArea.getText().replace(textarea.getSelectedText(),""));

Hope this helps.

+1
source
txtArea.replaceSelection("");

it should be shorter and more efficient.

+37
source

All Articles