Populate JList from JTextField

How to populate list above from the textfields?

Firstly, create the GUI using your preferred IDE (i used netbeans).

Next, add these method from actionPerformed event called from addButton and removeButton

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
addToList();
}
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
removeFromList();
}

Next, we define the methods.

void addToList() {
String name = txtIPAddress.getText();
Target participants;
//User didn't type in a unique name
if (name.equals("") || alreadyInList(name)) {
Toolkit.getDefaultToolkit().beep();
txtIPAddress.requestFocusInWindow();
txtIPAddress.selectAll();
return;
}
String input = txtIPAddress.getText() + " video: " + txtPortVideo.getText()
+ " audio: " + txtPortAudio.getText();
listModel.addElement(input);
txtIPAddress.setText("");
txtPortAudio.setText("");
txtPortVideo.setText("");
}


void removeFromList() {
int index = listParticipant.getSelectedIndex();
listModel.remove(index);

int size = listModel.getSize();

if (size == 0) { //Nobody's left, disable firing.
btnRemove.setEnabled(false);

}
else { //Select an index.
if (index == listModel.getSize()) {
//removed item in last position
index--;
}

listParticipant.setSelectedIndex(index);
listParticipant.ensureIndexIsVisible(index);
}
}


boolean alreadyInList(String name) {
if (listModel.contains(name)) {
//add import.javax.swing.JOptionPane first
JOptionPane.showMessageDialog(this, "The participant is already exists");
return true;
}
return false;
}


public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {

if (listParticipant.getSelectedIndex() == -1) {
//No selection, disable fire button.
btnRemove.setEnabled(false);

} else {
//Selection, enable the fire button.
btnRemove.setEnabled(true);
}
}
}

In the class declaration, we implements ListSelectionListenerInterface. Moreover, we declare an instance variable called listModel of type DefaultListModel. Our coding actually manipulate this listModel because we cannot manipulate JList directly. So, we add these code:

public class Tx extends javax.swing.JFrame implements ListSelectionListener {
private DefaultListModel listModel = new DefaultListModel();
public Tx() {
initComponents();
listParticipant.setModel(listModel);
listParticipant.addListSelectionListener(this);
}

That is how you populate JList from JTextField.

Post a Comment