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);
}
}
txtArea.replaceSelection("");
this should be shorter and more effective.
If you wanna remove only selected text then try this:
textArea.setText(textArea.getText().replace(textArea.getSelectedText(),""));
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With