简体   繁体   中英

Populate JTextField with data from XML using JComboBox ItemStateChanged listener

Unfortunatly I am unable to provide code to this site due to where I work. With that said I will be as detailed as I can. I am working on using aan XML file to populate a JcomboBox based of the "Name" element. I have that part working. The way I am doing this is by using DOM method and I create in Object for each of the Nodes and then I uset set methods to grab the attributes that I require.

Where I am now is I need to populate a text field based off of what was selected. I am struggling to figure out how to associate what is selected to what I need. For instance let say I have a node called "Reference_Point_ID" and I needed to pull the child node called "Latitude" to populate the JTextField. How would I associate the child node with the parent node to pull the correct data?

Again I am sorry I cannout provide the code but any help will be much appreciated. Thank you.

UPDATE - SOLUTION For anyone else that may need this info.

In order to pull the data for what I needed into the JComboBox I had to modify the model like so:

public TestReferencePointXMLReaderGUI()
{
    initComponents();
    ReferencePointReader referencePointReader = new ReferencePointReader("path to your xml file");

    List<ReferencePointObject> listOfData = referencePointReader.getData();
    DefaultComboBoxModel<ReferencePointObject> model =
        (DefaultComboBoxModel<ReferencePointObject>) jComboBoxRefPointSelector.getModel();
    for (ReferencePointObject referencePointObject : listOfData)
    {
        model.addElement(referencePointObject);
    }

}

The following shows how I changed the data in the text fields based off of what was selected. There is something I would like to mention. Unless you want the ItemStateChanged to return the previous selection as well as the new selection you need to be sure to add the if check statement.

    private void jComboBoxRefPointSelectorItemStateChanged(java.awt.event.ItemEvent evt)                                                           
{                                                               
    if (evt.getStateChange() == ItemEvent.SELECTED)
    {
        Object selected = jComboBoxRefPointSelector.getSelectedItem();
        ReferencePointObject selectedReferencePoint = (ReferencePointObject) selected;
        jTextFieldLat.setText(selectedReferencePoint.getLat());
        jTextFieldLong.setText(selectedReferencePoint.getLng());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM