setVisibleRowCount
使用and setLayoutOrientation
on得到了意想不到的结果JList
。我在JList
组件上有以下代码:
public class JListDemo extends JPanel {
private DefaultListModel listModel;
private JList list;
private JButton jbAdd;
private JButton jbRemove;
public JListDemo() {
super();
init();
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("JList Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new JListDemo());
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void init() {
listModel = new DefaultListModel();
list = new JList(listModel);
//list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisibleRowCount(6);
list.setLayoutOrientation(JList.VERTICAL_WRAP);
JScrollPane scrollList = new JScrollPane(list);
jbAdd = new JButton("Add");
jbRemove = new JButton("Remove");
JPanel buttonPanel = new JPanel();
buttonPanel.add(jbAdd);
buttonPanel.add(jbRemove);
Box displayBox = Box.createVerticalBox();
displayBox.add(scrollList);
displayBox.add(buttonPanel);
add(displayBox);
bindListeners();
}
private void bindListeners() {
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
jbRemove.setEnabled(false);
} else {
jbRemove.setEnabled(true);
}
}
}
});
jbAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = JOptionPane.showInputDialog(JListDemo.this, "Enter name for list:", "", JOptionPane.PLAIN_MESSAGE);
listModel.addElement(name);
}
});
jbRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
JList
当 GUI 出现时,我只在组件处看到一条直线。如果我注释掉方法setLayoutOrientation(JList.VERTICAL_WRAP)
,那么我可以看到JList
有 6 个空行可见的组件。为什么会这样?(注:JList
为空)。