我正在尝试使用 Swing,并决定专注于将 JList 与对象数组列表结合使用。
我想创建一个显示空白 JList 的程序,当按下按钮时将显示 arraylist 的内容,并允许单选打印出曾经选择的内容。
我当前的代码执行上述所有操作,但是当我单击 JList 上的单个条目时,它会打印两次。我觉得这是一个很容易纠正的简单错误,但我一直在阅读它,我的大脑已经停止合作。
任何帮助将不胜感激。提前致谢 :)
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
}