gpt4 book ai didi

java - 将 JList 项目 (JPanel) 左对齐

转载 作者:行者123 更新时间:2023-11-30 03:52:15 25 4
gpt4 key购买 nike

我在弄清楚如何将 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 居中对齐,而不是左侧对齐。

Jpanels centered in JList

以及列表的更新:

list.clear();
for (FileProperties props : files) {
list.addElement(props);
}
fileList.setCellRenderer(new FileTab(getWidth() - 30, 30));

最佳答案

默认情况下,JPanel 使用FlowLayout,默认情况下是中心对齐。更改 JPanel 以使用右对齐FlowLayout:

JPanel panel = new JPanel( new FlowLayout(...) ); // Read FlowLayout API for proper parameter

关于java - 将 JList 项目 (JPanel) 左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24145876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com