MULTIPLE_INTERVAL_SELECTION用于一次选择一个或多个连续的索引范围。 SINGLE_INTERVAL_SELECTION用于一次选择一个连续的索引范围。 但是这里一次选择一个列表索引。
import javax.swing.*;
import java.awt.event.*;
public class SwingLessonFive extends JFrame {
JButton button1;
JList favoriteMovies, favoriteColors;
DefaultListModel defaultList = new DefaultListModel();
JScrollPane scrollBars;
String infoOnComponent ="";
public static void main(String[] args) {
new SwingLessonFive();
}
public SwingLessonFive() {
this.setSize(400,400);
this.setTitle("My Fifth Frame");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel thePanel = new JPanel();
button1 = new JButton("Get Answer");
ListenForButton lForButton = new ListenForButton();
button1.addActionListener(lForButton);
thePanel.add(button1);
String[] movies = {"Kick","Batman","SpiderMan","Lucy"};
favoriteMovies = new JList(movies);
favoriteMovies.setFixedCellHeight(30);
favoriteMovies.setFixedCellWidth(150);
favoriteMovies.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); //this is the part I didn't undertand
String[] colors = {"Black","Orange","Brown","Pink","Yellow","White","Red"};
for(String color : colors) {
defaultList.addElement(color);
}
defaultList.add(2, "Purple");
favoriteColors = new JList(defaultList);
favoriteColors.setVisibleRowCount(4);
scrollBars = new JScrollPane(favoriteColors,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
favoriteColors.setFixedCellHeight(30);
favoriteColors.setFixedCellWidth(150);
thePanel.add(favoriteMovies);
thePanel.add(scrollBars);
this.add(thePanel);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button1) {
if(defaultList.contains("Black")) {
infoOnComponent += "Black is in the list \n";
}
if(!defaultList.isEmpty()) {
infoOnComponent +="The list isn't empty\n";
}
infoOnComponent += "Elements in the list: "+defaultList.getSize() +"\n";
infoOnComponent += "Last Element: "+defaultList.lastElement() + "\n";
infoOnComponent += "First Element: "+defaultList.firstElement()+"\n";
infoOnComponent += "Get element at index 1 "+defaultList.get(1)+"\n";
defaultList.remove(0);
defaultList.removeElement("Yellow");
Object[] arrayOfList = defaultList.toArray();
for(Object color: arrayOfList) {
infoOnComponent += color +"\n";
}
JOptionPane.showMessageDialog(SwingLessonFive.this,infoOnComponent,"Information",JOptionPane.INFORMATION_MESSAGE);
infoOnComponent = "";
}
}
}
}
答案 0 :(得分:1)
但是这里一次选择一个列表索引。
正确。单击即可选择一行。
要选择多个单行,请在单击
时按住Control键要选择一系列行,请在单击时按住Shift键。
因此选择取决于选择模式,以及是否使用了移位/控制键。
进行实验,直到获得符合要求的正确选择模式。