I'm trying my hand at using Swing and decided to focus on using JList in conjunction with an arraylist of Objects.
I wanted to create a program that displayed a blank JList that when a button is pressed would display the contents of the arraylist as well as allow single selection that would print out what ever was selected.
My current code does all of the above however when I click on a single entry on the JList it prints it out twice. I feel like this is a simple mistake that could be easily rectified but I've been reading through it and my brain has stopped cooperating.
Any help will be greatly appreciated. Thanks in advance :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.event.*;
public class textarea {
ArrayList <Pet> petList = new ArrayList <Pet> ();
DefaultListModel model = new DefaultListModel();
JList list = new JList();
public static void main (String [] args){
textarea gui = new textarea();
gui.go();
}
public void go(){
petList.add(new Pet("Lucy","Dog",5));
petList.add(new Pet("Geoff","Cat",2));
petList.add(new Pet("Hammond","Hamster",1));
model = new DefaultListModel();
for(Pet p:petList){
model.addElement(p.toString());
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("view pets");
button.addActionListener(new ButtonListener());
JScrollPane scroller = new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
list.setVisibleRowCount(4);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
String selection = (String) list.getSelectedValue();
System.out.println(selection);
}
});
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.setSize(350,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end go()
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
list.setModel(model);
}
}//end ButtonListener
}
SwingUtilities.invokeLater()
. – Krasnodar