Search code examples
javaswingjframejtextfieldjlist

JFrame Form add from JTextField to JList


I'm trying to make a contact field where you can type in a first name and a last name in two separate text fields and click the "Add" button I created to send it to the list, but I'm unsure of how to do this exactly, being new to jFrame. I was using something in a tutorial that was similar to this using floats (which is shown below), only because I wasn't sure how to use the "String" variation, however this only seems to work when the "setText" command is set on another text field and won't work on a jList.

float num1, num2, result;
num1 = Float.parseFloat(textFieldFirstName.getText());
num2 = Float.parseFloat(textFieldLastName.getText());
result = num1+num2;
listFieldContact.setText(String.valueOf(result));

Are there any ideas or even good resources out there for jFrame? I've looked in a lot of places but they never quite seem to have exactly the information I need.


Solution

  • this only seems to work when the "setText" command is set on another text field and won't work on a jList.

    A JList doesn't have a setText(...) method. You need to update the ListModel.

    Read the section from the Swing tutorial on How to Use Lists for a working example that does almost exactly what you want.

    The example uses a single text field by you should easily be able to get it to work with two text fields.