-2

I have created a JTextArea in which I have created a variable which is incremented when a button is clicked. However I want the incremented number to be displayed in the next Line and the old value stay in the previous line.

Till now I have coded the following for action listener and it is incrementing but replaces the old value and does not display on next line:

 public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
      if(e.getActionCommand().equals("Inc")) 
    {

      String h = "/n";
      int result = Integer.parseInt(area.getText())+1;
      String aString = Integer.toString(result);

      area.setText(String.valueOf(aString));
    }
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Splasher
  • 47
  • 5
  • read here [Add a new line to the end of a JtextArea](http://stackoverflow.com/questions/2088016/add-a-new-line-to-the-end-of-a-jtextarea) – Ben Win Feb 25 '15 at 09:31

2 Answers2

1

Use the JTextArea append(String str) method:

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
  if(e.getActionCommand().equals("Inc")) 
{
  String text=area.getText();
  int lastValue=Integer.parseInt(text.charAt(text.length())); //gets the last value of the JTextArea text
  String aString = Integer.toString(lastValue+1); //Increment this value      
  area.append("\n"+String.valueOf(aString)); //Append this value to the JTextArea
}

It appends the given text to the end of the JTextArea and with the "\n" it inserts a new line.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
-1

You are displaying the incremented result, which you are storing first in result and its String version in aString. Whatever, the original value(unincremented one) is getting lost. Try something like:

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
      if(e.getActionCommand().equals("Inc")) 
    {

      String h = "/n";
      int result = Integer.parseInt(area.getText())+1;
      String aString = Integer.toString(result);
      String toBeDisplayed = Integer.toString(result-1) + h + aString.  

      area.setText(String.valueOf(toBeDisplayed ));
    }
Andromeda
  • 1,370
  • 2
  • 10
  • 15