我在弄清楚如何将我的JPanels中的JList与左边对齐时遇到了问题。
我使用的是自定义ListCellRenderer,所以JPanels完全呈现。
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);这会导致JPanels在中间而不是左侧对齐。

和更新清单:
list.clear();
for (FileProperties props : files) {
list.addElement(props);
}
fileList.setCellRenderer(new FileTab(getWidth() - 30, 30));发布于 2014-06-10 16:27:04
默认情况下,JPanel使用FlowLayout,默认情况下是center aligned。将JPanel更改为使用FlowLayout,即right aligned
JPanel panel = new JPanel( new FlowLayout(...) ); // Read FlowLayout API for proper parameter发布于 2014-06-10 16:21:12
您的FileTab没有分配LayoutManager (默认为FlowLayout)。因此,您添加的两个组件(复选框和标签)在默认情况下是居中的。
也许这有帮助:JList text alignment
https://stackoverflow.com/questions/24145876
复制相似问题