对齐左侧的JList项目(JPanels)

时间:2014-06-10 16:11:15

标签: java swing jpanel alignment jlist

我在弄清楚如何将我的JList中的JPanel对齐到左侧时遇到了问题。

我使用自定义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;
    }
}

这就是我创建List的方式:

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在中心而不是在左侧对齐。

Jpanels centered in JList

更新清单:

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

2 个答案:

答案 0 :(得分:1)

您的FileTab没有分配LayoutManager(默认为FlowLayout)。因此,您添加的两个组件(复选框和标签)默认居中。

也许这会有所帮助:JList text alignment

答案 1 :(得分:1)

默认情况下,JPanel使用FlowLayout,默认情况下为center aligned。将JPanel更改为使用FlowLayout的{​​{1}}:

right aligned