猿问

JList 组件中 JCheckBox 的边距

我有一个 JList 组件,其中每个项目都有 JCheckBox 渲染器。我想为复选框添加边距,以便它不会粘在左侧。


我试过


checkBox.setMargin(new Insets(0, 10, 0, 0)); //left side spacing

并且也尝试过


checkBox.setAlignmentX(10.0F);

渲染代码


class ListRenderer() {

   public Component getListCellRendererComponent(JList list, Object value,

                int index, boolean isSelected, boolean cellHasFocus) {

    JCheckBox box = new JCheckBox("Married");

    return box;

   }


}

他们两个都没有工作。

宝慕林4294392
浏览 149回答 1
1回答

弑天下

不要尝试使用setMargin方法来完成此操作,而是尝试通过EmptyBorder向渲染器添加 an 来完成此操作。new JCheckBox另外,如果您在应用程序中返回 aListCellRenderer将使用大量内存(它将不会返回到操作系统),因为每次(几乎)组件被事件触发/干扰时,它都会被重新绘制,因此会产生新的 *cells JCheckBox 已创建。相反,创建一个新类extends JCheckBox和implements ListCellRenderer。另外,检查setIconTextGap方法。你可能想使用它:)一个完整的例子:public class CheckBoxInJList extends JFrame {&nbsp; &nbsp; private static final long serialVersionUID = -1662279563193298340L;&nbsp; &nbsp; public CheckBoxInJList() {&nbsp; &nbsp; &nbsp; &nbsp; super("test");&nbsp; &nbsp; &nbsp; &nbsp; setDefaultCloseOperation(EXIT_ON_CLOSE);&nbsp; &nbsp; &nbsp; &nbsp; DefaultListModel<String> model;&nbsp; &nbsp; &nbsp; &nbsp; JList<String> list = new JList<>(model = new DefaultListModel<>());&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 1000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String s = "String: " + i + ".";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; model.addElement(s);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; list.setCellRenderer(new CheckBoxRenderer());&nbsp; &nbsp; &nbsp; &nbsp; add(new JScrollPane(list), BorderLayout.CENTER);&nbsp; &nbsp; &nbsp; &nbsp; setSize(500, 500);&nbsp; &nbsp; &nbsp; &nbsp; setLocationRelativeTo(null);&nbsp; &nbsp; }&nbsp; &nbsp; private static class CheckBoxRenderer extends JCheckBox implements ListCellRenderer<String> {&nbsp; &nbsp; &nbsp; &nbsp; public CheckBoxRenderer() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean isSelected, boolean cellHasFocus) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setText(value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setSelected(isSelected);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; SwingUtilities.invokeLater(() -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new CheckBoxInJList().setVisible(true);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}预览:
随时随地看视频慕课网APP

相关分类

Java
我要回答