【发布时间】:2014-07-31 12:06:15
【问题描述】:
我在弄清楚如何将 JList 中的 JPanel 与左侧对齐时遇到问题。
我正在使用自定义 ListCellRenderer,所以 JPanel 完全渲染。
public class FileTab extends JPanel implements ListCellRenderer<FileProperties> {
public FileTab(int w, int h) {
setSize(w, h);
}
private void initComponents(FileProperties prop, boolean selected) {
removeAll();
JCheckBox checkBoxSelection = new JCheckBox();
checkBoxSelection.setBounds(10, 10, 10, 10);
add(checkBoxSelection);
checkBoxSelection.setSelected(selected);
System.out.println("Draw: " + prop.getFileName());
JLabel labelFileName = new JLabel(prop.getFileName());
labelFileName.setBounds(5, 70, getWidth() - 85, 20);
labelFileName.setFont(new Font("Consolas", Font.ITALIC, 20));
add(labelFileName);
}
@Override
public Component getListCellRendererComponent(JList<? extends FileProperties> list, FileProperties prop, int index,
boolean isSelected,
boolean cellHasFocus) {
initComponents(prop, isSelected);
return this;
}
}
这就是我创建列表的方式:
JScrollPane scroll = new JScrollPane();
scroll.setBounds(5, 5, getWidth() - 10, getHeight() - 110);
list = new DefaultListModel<>();
fileList = new JList<>(list);
fileList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
fileList.setCellRenderer(new FileTab(getWidth() - 30, 30));
scroll.setViewportView(fileList);
add(scroll);
这会导致 JPanel 在中心而不是左侧对齐。
以及列表的更新:
list.clear();
for (FileProperties props : files) {
list.addElement(props);
}
fileList.setCellRenderer(new FileTab(getWidth() - 30, 30));
【问题讨论】:
标签: java swing jpanel alignment jlist