简体   繁体   English

在左侧对齐JList项目(JPanels)

[英]Align JList items (JPanels) on the left

I`m having problems figuring out how to align my JPanels in my JList to the left side. 我在弄清楚如何将JList中的JPanels对齐到左侧时遇到问题。

I´m using a custom ListCellRenderer, so the JPanels render at all. 我使用的是自定义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;
    }
}

And thats how I create the 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);

This results in this, where the JPanels are aligned in the center rather than on the left side. 结果是,JPanel在中心而不是在左侧对齐。

Jpanels以JList为中心

And the updating of the list: 以及列表的更新:

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

Your FileTab has no LayoutManager assigned (default is FlowLayout). 您的FileTab没有分配LayoutManager(默认为FlowLayout)。 So the two components you add (Checkbox and Label) are centered by default. 因此,默认情况下,您添加的两个组件(复选框和标签)居中。

Maybe this helps: JList text alignment 也许有帮助: JList文本对齐

By default a JPanel use a FlowLayout which by default is center aligned . 默认情况下,JPanel使用FlowLayout (默认情况下center aligned Change the JPanel to use a FlowLayout that is right aligned : 更改JPanel以使用right alignedFlowLayout

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM