Search code examples
javaswingnetbeansuitextfieldjtextfield

Java Textfield printing query


Hi I would like to loop from number 1 to 10 and print them all under each other in my netbeans TextField.

I tried placing the textfield within the loop, but it over-writes the last value and so it doesn't work. Any idea how I may solve this issue? Thanks

Code:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {

 String test = null;
 int i = 0;

    while(i<10){
     test = String.valueOf(i);
     test = test+"/n"
    }

    jTextField3.setText(test); 

  } 

Solution

  • Suppose a JTextArea is what you are looking for. Try something like this:

    JTextArea textArea = new JTextArea();
    for(int i=0;i<10;i++)
       textArea.append(i+"\n");
    

    A TextField is usually used for input, a "line" where a user can enter something. TextArea is probably what you want. Here you should call the append() method, enter the value you want to append and add a newline with \n

    If it overwrites your last value, make sure that you create the field outside of the loop, and just call the refrence. If you do JTextArea textArea = new JTextArea(); inside the loop, a new area will be created each iteration overwriting the one you had