1

I want to delete a single line through a JButton in Jframe. But I don't know how... I allready tried:

 public void button1_ActionPerformed(ActionEvent evt) {
int count = 1;
count = TextArea1.getLineCount();

But it's not working... I appreciate every kind of help :)) Or anyone knews another method to solve this problem?

  • This only sets the value of the count variable. Did you forget to paste some code? – OlivierLi Feb 10 '14 at 19:45
  • I don't think so... and I have no Idea how to fix the program :P it also shows the get line but I am not sure how it works out – user3272186 Feb 10 '14 at 19:46
  • Define "line" - is this a physical line, separated by "\n", new line or the line of text as it appears in the text area? – MadProgrammer Feb 10 '14 at 20:49
  • A line in the TextArea. Means there are multiple lines and I want to delete the first with jbutton1 the 2cnd with jbutton2 etc. but I don't know how. – user3272186 Feb 10 '14 at 20:55

2 Answers2

1

You need to use GetText() to get what is already in the TextArea and then remove the line. Once you have modified the text you can put it back using SetText().

Of course this can be done in one line but separating the steps helps legibility.

OlivierLi
  • 2,798
  • 1
  • 23
  • 30
  • It nearly works fine but I want to delete a single line and that isn't working with getText() because if you got e.g. 2 Things in the area: asdf1 asdf2 you can set the text to ("") but than not only asdf1 is getting deleted but also asdf2 Sorry for my bad english and sorry for stealing your time :D – user3272186 Feb 10 '14 at 20:13
  • In you example both asdf1 and asdf2 are on the same line. If you only want to get rid of one you can use String.split() to separate them. See http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java for details. – OlivierLi Feb 10 '14 at 20:15
  • And don't worry you are not stealing my time. If you feel my answered solved your problem you can use the check mark to accept it. This would be payment enough! – OlivierLi Feb 10 '14 at 20:16
  • I surely will use the check mark... ;) asdf1 and asfd2 are in diferent lines in the textarea but using set text("") deletes all the text in the textarea :O – user3272186 Feb 10 '14 at 20:49
  • Assuming you want to remove the first line : String s = texArea.getText().substring(s.indexOf('\n')+1); – OlivierLi Feb 10 '14 at 21:15
1

The answer depends on the definition of a "line". For example, if you are using a wrapped JTextArea, where a single, contiguous line of text, wraps around the view, a line could be considered the text that runs from one side of the view to the other.

In this case you need to delve into the model and calculate the offsets of the text based on the view and basically remove the content between two points, for example...

Remove Lines

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.Utilities;

public class TestDeleteLine {

    public static void main(String[] args) {
        new TestDeleteLine();
    }

    private JTextArea ta;

    public TestDeleteLine() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ta = new JTextArea(20, 40);
                ta.setWrapStyleWord(true);
                ta.setLineWrap(true);

                JButton deleteLine = new JButton("Delete current line");
                deleteLine.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            int offset = ta.getCaretPosition();

                            int rowStart = Utilities.getRowStart(ta, offset);
                            int rowEnd = Utilities.getRowEnd(ta, offset);

                            Document document = ta.getDocument();

                            int len = rowEnd - rowStart + 1;
                            if (rowStart + len > document.getLength()) {
                                len--;
                            }
                            String text = document.getText(rowStart, len);
                            document.remove(rowStart, len);
                        } catch (BadLocationException ex) {
                            ex.printStackTrace();
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(ta));
                frame.add(deleteLine, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Now, if you don't care about the line wrapping and simple want to remove the entire line (from one new line to another) you could use...

public int getLineByOffset(int offset) throws BadLocationException {
    Document doc = ta.getDocument();
    if (offset < 0) {
        throw new BadLocationException("Can't translate offset to line", -1);
    } else if (offset > doc.getLength()) {
        throw new BadLocationException("Can't translate offset to line", doc.getLength() + 1);
    } else {
        Element map = doc.getDefaultRootElement();
        return map.getElementIndex(offset);
    }
}

public int getLineStartOffset(int line) throws BadLocationException {
    Element map = ta.getDocument().getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", ta.getDocument().getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getStartOffset();
    }
}

public int getLineEndOffset(int line) throws BadLocationException {
    Element map = ta.getDocument().getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", ta.getDocument().getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getEndOffset();
    }
}

public int[] getLineOffsets(int line) throws BadLocationException {
    int[] offsest = new int[2];
    offsest[0] = getLineStartOffset(line);
    offsest[1] = getLineEndOffset(line);
    return offsest;
}

To calculate the line start and end positions, calculate the length of the text and remove it from the Document, which might look more like...

int offset = ta.getCaretPosition();
int line = getLineByOffset(offset);
int[] lineOffsets = getLineOffsets(line);

int len = lineOffsets[1] - lineOffsets[0] - 1;
Document document = ta.getDocument();
String text = document.getText(lineOffsets[0], len);
document.remove(lineOffsets[0], len);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366