Doubt on line removal in JTextArea

Hi All,
I have 3 lines which are on the JTextArea like
sample.pl
sample1.pl
sample2.pl
So i want to remove the whole from Jtextarea..how is it possible??
thanks in advance.
regards,
Viswanadh

TechnicalGuy7 wrote:
Thanks for the reply.
If suppose i want to remove only the middle line..How can i do???
regards,
Viswanadh
Edited by: TechnicalGuy7 on Feb 16, 2009 5:21 AMI've written a simple example which will remove the second line of the input when you press a button. Obviously you can manipulate the logic to remove whatever line you want (programmatically determining where the middle lines is, removing odd lines etc).
package tester;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Tester extends JFrame implements WindowListener {
     private JTextArea textArea;
     public static void main(String[] args) {
          new Tester();
     public Tester() {
          textArea = new JTextArea();
          JButton checkTextButton = new JButton("Click to remove the second line");
          checkTextButton.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    checkTextButton_actionPerformed(e);
          this.setLayout(new BorderLayout());
          this.add(textArea, BorderLayout.CENTER);
          this.add(checkTextButton, BorderLayout.SOUTH);
          this.setTitle("Second Line Remover");
          this.setSize(500, 500);
          this.addWindowListener(this);
          this.setVisible(true);
     private void checkTextButton_actionPerformed(ActionEvent e) {
          // Get the text from the text area
          String inputText = textArea.getText();
           * Split the text into lines using the new line character as the split point. lines[0] is
           * the first line, lines[1] is the second and so on...
          String[] lines = inputText.split("\n");
          // If there aren't 2 or more lines we can't do anything
          if(lines.length < 2) {
               JOptionPane.showMessageDialog(this, "Cannot remove the second line because it doesn't exist.");
               return;
          StringBuilder outputString = new StringBuilder();
          for(int i=0; i<lines.length; i++) {
               // Append all lines except from the second line to the new text to put in the area
               if(i != 1) {
                    outputString.append(lines[i]+"\n");
          // Set the new text in the area to be the input minus the second line
          textArea.setText(outputString.toString());
     @Override
     public void windowActivated(WindowEvent e) {}
     public void windowClosed(WindowEvent e) {}
     public void windowClosing(WindowEvent e) {
          System.exit(0);
     public void windowDeactivated(WindowEvent e) {}
     public void windowDeiconified(WindowEvent e) {}
     public void windowIconified(WindowEvent e) {}
     public void windowOpened(WindowEvent e) {}
}Sample interaction (before and after pressing the button:
http://img4.imageshack.us/img4/4307/beforeandafterva5.jpg

Similar Messages

  • Finding the end of a line in a JTextArea and inserting a comma

    Hi,
    At the moment I am reading in a comma delimited file into a JTextArea.
    This part is ok I can see the file in the window correctly.
    The problem that I am having now is that I want to add a comma to the end of each line in the JTextArea.
    Does anyone know how to do this?
    Thank you

    Well you have to get the String value of the JTextField.
    String text = YourJTextField.getText()
    Then you have to make a loop and check each single character if it equals '\n', that means "RETURN" or "NEW LINE".
    That is the direction I would go. Inform yourself about String manipulations first, like how to look for character, how to compare them and how to add them.

  • Getting a single line from a JTextArea

    I have a JTextArea with a fixed size. I've used the .setLineWrap(true) and .setWrapStyleWord(true) on this JTextArea, so when the user types in some text, that's longer that the JTextArea, it will wrap unto the next line. I need to get each visible line from the JTextArea. That is not each line of text, that is seperated by a newline (when the user type Enter), but every line, that is visibly seperated in the JTextArea.
    How can i do that.

    The javax.swing.text.Utilities class can help:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TestUtility extends JFrame
         public TestUtility()
              final JTextArea textArea = new JTextArea( "one two three four five", 5, 10 );
              textArea.setLineWrap( true );
              textArea.setWrapStyleWord( true );
              JScrollPane scrollPane = new JScrollPane( textArea );
              getContentPane().add( scrollPane );
              textArea.addCaretListener( new CaretListener()
                   public void caretUpdate(CaretEvent e)
                        int pos = textArea.getCaretPosition();
                        try
                             int start =  Utilities.getRowStart(textArea, pos);
                             int end =  Utilities.getRowEnd(textArea, pos);
                             System.out.println( start + " : " + end );
                        catch (BadLocationException ble) {}
         public static void main(String[] args)
              TestUtility frame = new TestUtility();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);

  • Why is blurred lines removed from itunes

    why is blurred lines removed from Robin Thicke's Album?

    Interesting, looks like some sort of weird glitch in the iTunes Store. Track 10 is showing up twice, and track 1 is not showing up at all. I would venture to guess that it would download correctly if someone actually purchased the album, but I won't be the one to test that theory. Hopefully they get it resolved soon.
    Here is what the OP is talking about:

  • Line limit for JTextArea - Urgent

    Hi All,
    I would like to have 80 character limit for each line displayed in JTextArea. The linewrap along with wordwrap have been enabled for JTextArea but that solves a part of the problem. The no. of characters that can be entered per line depends on the width of the component and the font size. For this component there is no upper limit for the total no. charaters that can be entered. Basically, it supports text editing feature(cut, copy, paste). One way it could have been done by fixing the width of component so that it could accomodate only 80 characters, but again the factors like screen resolution, font's advance width keeps changing. I tried with overriding insertString() of PlainDocument class, but didn't know how to wrap the characters after 80 position to next line if text is inserted in the middle of a line. At the same time the whole text needs a reformatiing. Same behavior is desirable while doing cut/paste operations.
    A hint or sample code will be highly appreciated as it has been a long time I am looking to solve this problem.
    Thanks
    Ritwick.

    You are correct it is not easy to override the default behaviour of the JTextArea. So my suggestion is to use a monospaced font. The code would then be:
    JTextArea.textArea = new JTextArea( "some text", 10, 80 );
    textArea.setFont( new Font("monospaced", Font.PLAIN, 12) );
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    JScrollPane scrollPane = new JScrollPane( textArea );
    scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );If using a monospaced font is not possible, then please explain why wrapping at exactly 80 characters is so important, maybe there is a different approach to take.

  • Getting the visible lines from a JTextArea

    I'm using a JTextArea with a fixed size. I've used the setLineWrap(true) and setWrapStyleWord(true) methods on this JTextArea, so when the user types in some text longer than the visible width, it will wrap into the next line. I need to get each visible line from the JTextArea to create a String array of text lines.
    I mean visible text lines (lines visibly separated in the JTextArea), not real text lines separated by a line break character as "\n".
    How can I do this?

    This information is supposed to be contained in the View information of the component. But as far as I can tell it doesn't work for a JTextArea.
    So if you can use a JTextPane then check out the "getWrappedLines" method in this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
    Basically, a View exists for each line in the Document and then each line may have multiple views if the line needs to wrap. So the basic code just count the number of views within each line but you can change the code to get each view separately. Once you have each view you can get the start and end of the text from the document that this View represents.
    Or if you need to use a JTextArea then you can calculate the starting offset of each each line with respect to the model. You can use the viewToModel(..) method to get the starting offset of each line. We know that each line in a text area is a fixed height, so the starting offset of the first line would be modelToView(0, 0); If the line height is 16, then the starting offset of the second line would be modelToView(0, 16), etc. Once you know the starting offset of each line you can subString out the text for each line.

  • How can we get the selected line number from JTextArea ?

    how can we get the selected line number from JTextArea ? and want to insert line/string given line number into JTextArea??? is it possible ?

    Praitheesh wrote:
    how can we get the selected line number from JTextArea ?
    textArea.getLineOfOffset(textArea.getCaretPosition());
    and want to insert line/string given line number into JTextArea??? is it possible ?
    int lineToInsertAt = 5; // Whatever you want.
    int offs = textArea.getLineStartOffset(lineToInsertAt);
    textArea.insert("Text to insert", offs);

  • How do i read new line char in jtextarea.getText()?

    guys, how do i read new line character in jTextArea.getText()? i'll appreciate ur help tnx..:))

    Use a StringRead, then you can treat the text file a file.

  • HELP !! change the line height in JTextArea ??

    can anyone tell me , how to change (set) the line height in JTextArea ???

    Looking at the source code for JTextArea, the rowHeight is taken from the font's FontMetrics and is used to set the preferred size of the ta, as you can see in the following app. Also, only three properties are maintained by the default PlainDocument as shown in the output. Might be worth your while to check out JTextPane.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TARowHeight {
      public static void main(String[] args) {
        final CustomTextArea ta = new CustomTextArea(5,10);
        ta.addPropertyChangeListener(new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            System.out.println(e.getPropertyName() + " changed to " + e.getNewValue());
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setFont(new Font("lucida sans regular" , Font.PLAIN, 16));
        JPanel centerPanel = new JPanel();
        centerPanel.add(ta);
        SpinnerNumberModel model = new SpinnerNumberModel(20,8,36,1);
        final JSpinner spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            int height = ((Integer)spinner.getValue()).intValue();
            ta.setRowHeight(height);
            ta.revalidate();
            ta.repaint();
        JPanel southPanel = new JPanel();
        southPanel.add(spinner);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(centerPanel), "Center");
        f.getContentPane().add(southPanel, "South");
        f.setSize(300,200);
        f.setLocation(400,400);
        f.setVisible(true);
        System.out.println(ta.getRowHeight());
        Dictionary names = ((AbstractDocument)ta.getDocument()).getDocumentProperties();
        Enumeration keys = names.keys();
        Enumeration values = names.elements();
        while(keys.hasMoreElements())
          System.out.println("key: " + keys.nextElement() +
                             " value: " + values.nextElement());
    class CustomTextArea extends JTextArea {
      private int rowHeight;
      public CustomTextArea(int rows, int cols) {
        super(rows, cols);
      protected int getRowHeight() {
            if (rowHeight == 0) {
                FontMetrics metrics = getFontMetrics(getFont());
                rowHeight = metrics.getHeight();
            return rowHeight;
      protected void setRowHeight(int rowHeight) {
        int oldVal = this.rowHeight;
        this.rowHeight = rowHeight;
        firePropertyChange("rowHeight", oldVal, rowHeight);
    }

  • How do i append each String on a different line in a JTextArea

    Hi,
    I have the following lines of code and I would like each line to append into the JTextArea on a separate line. I know I need to use \n but i forgot how to do it with the following code:
    invoiceJTextArea.append(FirstName);
    invoiceJTextArea.append(Surname);
    invoiceJTextArea.append(Age);
    At the moment, it prints right next to each other like this: JohnSmith28
    Thanks for your help.

    A JTextComponent will accept "\r\n", and it will seem
    to work, but the "\r" will not be treated as part of
    the line separator. And "\r" alone won't function as
    a line separator--in fact, it won't be displayed at
    all.
    When you read text into a JTextComponent from a file
    via the built-in read() method, all line separators
    are converted to "\n". The type of separator used in
    the file is saved as a property of the Document, and
    when you write the text back to the file, they are
    reconverted. Text pasted in from the clipboard also
    undergoes this conversion (but I don't think it gets
    reconverted when you copy or cut).
    The issue of line separators is meant to be
    completely transparent to the user. Programmers
    usually don't have to think about it either, but we
    do have the power to insert any whitespace character
    into a text component. We need to be aware that only
    spaces, tabs and linefeeds will render as expected.First off, I apologize for being a bit curt or dogmatic ... I was in a bit of a hurry.
    Note thought that I did not state: Don't use '\n'.
    What I did state as being wrong was your statement of:
    "No, don't use the system line separator. JTextArea can only use "\n" as a line separator"
    I have tried used the system line separator and it works. So I am not saying one should not use '\n', only that should not say the system line sep does not work.

  • How to implement Line number in JTextArea

    Hi
    I have seen some JTextArea with Line numbers How to do it
    Thankx

    I'm playing around with trying to make a Line Number component that will work with JTextArea, JTextPane, JTable etc. I'm not there yet, but this version works pretty good with JTextArea. At least it will give you some ideas.
    Good luck.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class LineNumber extends JComponent
         private final static Color DEFAULT_BACKGROUND = new Color(230, 163, 4);
         private final static Color DEFAULT_FOREGROUND = Color.black;
         private final static Font DEFAULT_FONT = new Font("monospaced", Font.PLAIN, 12);
         // LineNumber height (abends when I use MAX_VALUE)
         private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
         // Set right/left margin
         private final static int MARGIN = 5;
         // Line height of this LineNumber component
         private int lineHeight;
         // Line height of this LineNumber component
         private int fontLineHeight;
         private int currentRowWidth;
         // Metrics of this LineNumber component
         private FontMetrics fontMetrics;
         *     Convenience constructor for Text Components
         public LineNumber(JComponent component)
              if (component == null)
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( DEFAULT_FONT );
              else
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( component.getForeground() );
                   setFont( component.getFont() );
              setPreferredSize( 9999 );
         public void setPreferredSize(int row)
              int width = fontMetrics.stringWidth( String.valueOf(row) );
              if (currentRowWidth < width)
                   currentRowWidth = width;
                   setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
         public void setFont(Font font)
              super.setFont(font);
              fontMetrics = getFontMetrics( getFont() );
              fontLineHeight = fontMetrics.getHeight();
         * The line height defaults to the line height of the font for this
         * component. The line height can be overridden by setting it to a
         * positive non-zero value.
         public int getLineHeight()
              if (lineHeight == 0)
                   return fontLineHeight;
              else
                   return lineHeight;
         public void setLineHeight(int lineHeight)
              if (lineHeight > 0)
                   this.lineHeight = lineHeight;
         public int getStartOffset()
              return 4;
         public void paintComponent(Graphics g)
              int lineHeight = getLineHeight();
              int startOffset = getStartOffset();
              Rectangle drawHere = g.getClipBounds();
    //          System.out.println( drawHere );
    // Paint the background
    g.setColor( getBackground() );
    g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
              // Determine the number of lines to draw in the foreground.
    g.setColor( getForeground() );
              int startLineNumber = (drawHere.y / lineHeight) + 1;
              int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
              int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
    //          System.out.println( startLineNumber + " : " + endLineNumber + " : " + start );
              for (int i = startLineNumber; i <= endLineNumber; i++)
                   String lineNumber = String.valueOf(i);
                   int width = fontMetrics.stringWidth( lineNumber );
                   g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
                   start += lineHeight;
              setPreferredSize( endLineNumber );
         public static void main(String[] args)
              JFrame frame = new JFrame("LineNumberDemo");
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              JPanel panel = new JPanel();
              frame.setContentPane( panel );
              panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
              panel.setLayout(new BorderLayout());
              JTextArea textPane = new JTextArea();
              JScrollPane scrollPane = new JScrollPane(textPane);
              panel.add(scrollPane);
              scrollPane.setPreferredSize(new Dimension(300, 250));
              LineNumber lineNumber = new LineNumber( textPane );
              lineNumber.setPreferredSize(99999);
              scrollPane.setRowHeaderView( lineNumber );
              frame.pack();
              frame.setVisible(true);

  • Maximum line length in JTextAreas/Documents ?

    Hi there,
    apparently JTextAreas may not hold text with lines more than 32776 characters
    (with line length I mean distance between line breaks :-). Is this a documented limitation or did I trap into a bug?
    (Happened with 1.3.x and 1.4.x, Linux and Windows).
    Kind Regards,
    --Holger Klwitter                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    See: [http://kenhamady.com/cru/archives/1240|http://kenhamady.com/cru/archives/1240]

  • Command Line - Remove user and group updates

    I am remote at the moment and not able to access the GUI on a number of OS X server boxes. How do I remove a user and the user from group via the command line.
    Thanks

    I am remote at the moment and not able to access the GUI on a number of OS X server boxes. How do I remove a user and the user from group via the command line.
    Thanks

  • Doubt to be Clarified on JTextArea appending a string

    Hi All,
    Here is the actual code.
    String msg="Settings Details Will be Produced after the Connection is Successful";
                        String msg1=      "-------------------------------------------------------------------------";
                        String comdetails="1)Comport Enabled is:";
                        String baudratedetails="2)BaudRate Selected is:";
                        String databitdetails="3)DataBit is:";
                        String paritybitdetails="4)ParityBit is:";
                        String stopbitdetails="5)Stopbit is:";
    contentarea.setText("");
                           contentarea.append(msg);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(comdetails);contentarea.append(cv);
                        contentarea.append("\r\n");
                        contentarea.append(baudratedetails);contentarea.append(bv);
                        contentarea.append("\r\n");
                        contentarea.append(databitdetails);contentarea.append(dv);
                        contentarea.append("\r\n");
                        contentarea.append(paritybitdetails);contentarea.append(pv);
                        contentarea.append("\r\n");
                        contentarea.append(stopbitdetails);contentarea.append(sv);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);I have a JTextArea which is basically linked up with a JBUtton.So when i click on JButton in the JTextArea thte following will be displayed.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitSo my question when i again click on the same JButton the same data which is highlighted in the code tags need to be displayed again from the next end line of the previous data instead of overriding operation.Can any one help me out in doing this???
    Thanks in advance.
    regards,
    Viswanadh

    Hi toodburch,
    Thanks for the reply.My requirement is for every click on the JButton it should be in the following way.Assume i have pressed 3 times.then it should be displayed as shown.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitThanks
    regards,
    Viswanadh

  • Change purchase order draft line removes G/L account data

    We created a purchase order and saved it as a draft.  We entered all information including G/L account and distribution rule but left delivery date blank.  When we go into the saved draft and input the delivery date, it removes the G/L account number.  There are many lines on this order and now we have to go back and input the G/L account number.
    Any suggestions?
    Thank you
    Lori

    Hi,
    Please clarify- same scenario was tested in 8.81 PL10 that, GL account is still remain, if copy draft to PO with changing delivery date for both item and service type PO.
    Note: checked only for GL account not for distribution rule
    Thanks & Regards,
    Nagarajan

Maybe you are looking for

  • Internal Order Group & Internal order wise report

    Hi All Any Standard reports are available to display the internal order group name and internal order. Any Standard Function module or standard table are available to retrieve the order group and internal order details. Please confirm. Regards K.Guna

  • XML Unbounded values into one field - Message Mapping

    Dear All, I am trying to convert an unbounded multifield XML structure to a 0.1 field so that the maltiple values are mapped into a single fields in semi-colon seperated fasion. The source: <MT_dates>    <date>05-10-2011</date>    <date>10-11-2011</d

  • How to get an UFL into Crystal Reports 2008

    Hello, I created an UFL in Visual Basic, built .dll, registered it successfuly with RegAsm and added to GAC. Yet I still can't see the functions in Additional Functions. DLL source code: <Runtime.InteropServices.ComVisible(True)> Public Class Class1

  • Media offline - no it's not!

    In my timeline several clips display as Media Offline. But they aren't really. Playback of the sequence is fine. If I click on the clip and select Reveal in Finder, it does just that. It's not lost. If I select Reconnect Media for the individual clip

  • Log4j level inheritance concept doubt

    log.properties file log4j.debug=true log4j.rootLogger=ERROR, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%m%n log4j.logger.logging.basics=WAR