【问题标题】:Align JList items (JPanels) on the left在左侧对齐 JList 项 (JPanels)
【发布时间】: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


    【解决方案1】:

    默认情况下,JPanel 使用FlowLayout,默认情况下是center aligned。将 JPanel 更改为使用 FlowLayout,即 right aligned

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

    【讨论】:

    • 我猜你的意思是左对齐。
    • 是的,有时手指不会输入大脑在想什么 :)
    【解决方案2】:

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

    也许这有帮助:JList text alignment

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 2016-01-04
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      相关资源
      最近更新 更多