【问题标题】:Deleting a single Line through a JButton in a TextArea通过 TextArea 中的 JButton 删除单行
【发布时间】:2014-02-10 19:27:28
【问题描述】:

我想通过 Jframe 中的 JButton 删除一行。 但是我不知道怎么... 我已经试过了:

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

但它不起作用... 我感谢各种帮助:)) 或者有人知道解决这个问题的另一种方法吗?

【问题讨论】:

  • 这只是设置count变量的值。忘记粘贴代码了吗?
  • 我不这么认为......而且我不知道如何修复程序:P 它也显示了 get 行,但我不确定它是如何工作的
  • 定义“行” - 这是物理行,用“\n”分隔,换行还是文本区域中出现的文本行?
  • TextArea 中的一行。意味着有多行,我想用 jbutton1 删除第一行,用 jbutton2 删除 2cnd 等,但我不知道如何。

标签: java jframe textarea line jbutton


【解决方案1】:

您需要使用 GetText() 来获取 TextArea 中已有的内容,然后删除该行。修改文本后,您可以使用 SetText() 将其放回原处。

当然,这可以在一行中完成,但将步骤分开有助于易读性。

【讨论】:

  • 它几乎可以正常工作,但我想删除一行,这不适用于 getText() 因为如果你有例如该区域的 2 件事: asdf1 asdf2 您可以将文本设置为 ("") 但不仅 asdf1 被删除,而且 asdf2 对不起我的英语不好,很抱歉偷了你的时间:D
  • 在你的例子中 asdf1 和 asdf2 都在同一行。如果您只想摆脱一个,您可以使用 String.split() 将它们分开。详情请见stackoverflow.com/questions/3481828/…
  • 别担心你没有偷走我的时间。如果您觉得我的回答解决了您的问题,您可以使用复选标记接受它。这笔钱就够了!
  • 我肯定会使用复选标记... ;) asdf1 和 asfd2 在 textarea 的不同行中,但使用 set text("") 会删除 textarea 中的所有文本:O
  • 假设您要删除第一行: String s = texArea.getText().substring(s.indexOf('\n')+1);
【解决方案2】:

答案取决于“线”的定义。例如,如果您使用的是包裹式 JTextArea,其中一行连续的文本环绕视图,则可以将一行视为从视图一侧到另一侧的文本。

这种情况下需要深入模型,根据视图计算文本的偏移量,基本去掉两点之间的内容,例如...

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);
            }
        });
    }

}

现在,如果您不关心换行并且只想删除整行(从一个新行到另一行),您可以使用...

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;
}

要计算行的开始和结束位置,请计算文本的长度并将其从Document 中删除,这可能看起来更像...

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);

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2011-04-29
    相关资源
    最近更新 更多