
how to get the jlist values into jtextfield after clicking on the value?? plzz help

Here is an example that shows the selected value from the jlist to textfield.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ListAction extends JPanel implements ListSelectionListener {
JList list;
DefaultListModel listModel;
JTextField nameField;
public ListAction() {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("ZEN");
listModel.addElement("Alto");
listModel.addElement("Swift");
listModel.addElement("Centro");
listModel.addElement("Innova");
listModel.addElement("Scorpio");
listModel.addElement("Chevrolet");
listModel.addElement("Honda City");
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
nameField = new JTextField(15);
String name = listModel.getElementAt(list.getSelectedIndex()).toString();
nameField.setText(name);
JPanel panel = new JPanel();
panel.add(nameField);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel,listScrollPane);
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.CENTER);
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
nameField.setText("");
}else if (list.getSelectedIndices().length > 1) {
} else {
nameField.setText(list.getSelectedValue().toString());
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Clear ListData");
JComponent component = new ListAction();
component.setOpaque(true);
frame.setContentPane(component);
component.setMinimumSize(new Dimension(component.getPreferredSize().width, 100));
frame.pack();
frame.setVisible(true);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.