Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting only a selected text in a text area

I want to delete selected text in a text area using Java Swing, but I couldn't find a way to do that. At some point I thought of using textArea.setText(""); but, when I do, it clears out everything. Can some one please help me with this?

Here is the code I've 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);

}

}

like image 486
Pavithra Gunasekara Avatar asked Mar 10 '11 04:03

Pavithra Gunasekara


2 Answers

txtArea.replaceSelection("");

this should be shorter and more effective.

like image 157
secmask Avatar answered Oct 01 '22 19:10

secmask


If you wanna remove only selected text then try this:

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

Hope this helps.

like image 38
Harry Joy Avatar answered Oct 01 '22 20:10

Harry Joy