将 JSeparator 添加到 DefaultListModel

发布于 2024-12-20 21:06:19 字数 368 浏览 0 评论 0原文

我想将一些 JSeparators 添加到 JList 中。我正在使用 DefaultListModel,当我尝试时:

((DefaultListModel)myListModel).addElement(new JSeparator());

当我执行时,我将其写入 JList 而不是分隔符:

javax.swing.JSeparator[,0,0,0x0,无效,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@962d513,flags=0,maximumSize=,minimumSize=,preferredSize=,方向=水平]

I want to add some JSeparators to a JList. I am using a DefaultListModel, and when I try:

((DefaultListModel)myListModel).addElement(new JSeparator());

I'm getting this written into the JList instead of the separator when I execute:

javax.swing.JSeparator[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder@962d513,flags=0,maximumSize=,minimumSize=,preferredSize=,orientation=HORIZONTAL]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独自←快乐 2024-12-27 21:06:19

渲染器中有点复杂,但可能,因为 JComboBox 的示例但使用 ListCellRenderer

在此处输入图像描述

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class BlockComboBoxExample extends JFrame {

    private static final long serialVersionUID = 1L;
    final String SEPARATOR = "SEPARATOR";

    public BlockComboBoxExample() {
        super("Block ComboBox Example");
        String[][] str = {{"A", "B", "C"}, {"1", "2", "3"}, {"abc", "def", "ghi"}};
        JComboBox combo = new JComboBox(makeVectorData(str));
        combo.setRenderer(new ComboBoxRenderer());
        combo.addActionListener(new BlockComboListener(combo));
        combo.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXX");
        setLayout(new FlowLayout());
        add(combo);
        pack();
        setVisible(true);
    }

    private Vector<String> makeVectorData(String[][] str) {
        boolean needSeparator = false;
        Vector<String> data = new Vector<String>();
        for (int i = 0; i < str.length; i++) {
            if (needSeparator) {
                data.addElement(SEPARATOR);
            }
            for (int j = 0; j < str[i].length; j++) {
                data.addElement(str[i][j]);
                needSeparator = true;
            }
        }
        return data;
    }

    public static void main(String args[]) {
        try {
        for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(laf.getName())) {
                UIManager.setLookAndFeel(laf.getClassName());
                //UIManager.getLookAndFeelDefaults().put("Panel.background", Color.white);
                //UIManager.getLookAndFeelDefaults().put("Button.contentMargins", new InsetsUIResource(0,0,0,0));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

        BlockComboBoxExample frame = new BlockComboBoxExample();
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    private class ComboBoxRenderer extends JLabel implements ListCellRenderer {

        private static final long serialVersionUID = 1L;
        private JSeparator separator;

        public ComboBoxRenderer() {
            setOpaque(true);
            setBorder(new EmptyBorder(1, 1, 1, 1));
            separator = new JSeparator(JSeparator.HORIZONTAL);
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            String str = (value == null) ? "" : value.toString();
            if (SEPARATOR.equals(str)) {
                return separator;
            }
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setFont(list.getFont());
            setText(str);
            return this;
        }
    }

    private class BlockComboListener implements ActionListener {

        private JComboBox combo;
        private Object currentItem;

        BlockComboListener(JComboBox combo) {
            this.combo = combo;
            combo.setSelectedIndex(0);
            currentItem = combo.getSelectedItem();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String tempItem = (String) combo.getSelectedItem();
            if (SEPARATOR.equals(tempItem)) {
                combo.setSelectedItem(currentItem);
            } else {
                currentItem = tempItem;
            }
        }
    }
}

little bit complicated in the renderer but possible, since example for JComboBox but with ListCellRenderer

enter image description here

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class BlockComboBoxExample extends JFrame {

    private static final long serialVersionUID = 1L;
    final String SEPARATOR = "SEPARATOR";

    public BlockComboBoxExample() {
        super("Block ComboBox Example");
        String[][] str = {{"A", "B", "C"}, {"1", "2", "3"}, {"abc", "def", "ghi"}};
        JComboBox combo = new JComboBox(makeVectorData(str));
        combo.setRenderer(new ComboBoxRenderer());
        combo.addActionListener(new BlockComboListener(combo));
        combo.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXX");
        setLayout(new FlowLayout());
        add(combo);
        pack();
        setVisible(true);
    }

    private Vector<String> makeVectorData(String[][] str) {
        boolean needSeparator = false;
        Vector<String> data = new Vector<String>();
        for (int i = 0; i < str.length; i++) {
            if (needSeparator) {
                data.addElement(SEPARATOR);
            }
            for (int j = 0; j < str[i].length; j++) {
                data.addElement(str[i][j]);
                needSeparator = true;
            }
        }
        return data;
    }

    public static void main(String args[]) {
        try {
        for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(laf.getName())) {
                UIManager.setLookAndFeel(laf.getClassName());
                //UIManager.getLookAndFeelDefaults().put("Panel.background", Color.white);
                //UIManager.getLookAndFeelDefaults().put("Button.contentMargins", new InsetsUIResource(0,0,0,0));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

        BlockComboBoxExample frame = new BlockComboBoxExample();
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    private class ComboBoxRenderer extends JLabel implements ListCellRenderer {

        private static final long serialVersionUID = 1L;
        private JSeparator separator;

        public ComboBoxRenderer() {
            setOpaque(true);
            setBorder(new EmptyBorder(1, 1, 1, 1));
            separator = new JSeparator(JSeparator.HORIZONTAL);
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            String str = (value == null) ? "" : value.toString();
            if (SEPARATOR.equals(str)) {
                return separator;
            }
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setFont(list.getFont());
            setText(str);
            return this;
        }
    }

    private class BlockComboListener implements ActionListener {

        private JComboBox combo;
        private Object currentItem;

        BlockComboListener(JComboBox combo) {
            this.combo = combo;
            combo.setSelectedIndex(0);
            currentItem = combo.getSelectedItem();
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String tempItem = (String) combo.getSelectedItem();
            if (SEPARATOR.equals(tempItem)) {
                combo.setSelectedItem(currentItem);
            } else {
                currentItem = tempItem;
            }
        }
    }
}
稚然 2024-12-27 21:06:19

您可以将 DefaultListModel 包装到 JList 中,并向 JList 添加自定义单元格渲染器。

class MyListCellRenderer implements ListCellRenderer{

   final JLabel jlblCell = new JLabel(" ", JLabel.LEFT);
   Border lineBorder = BorderFactory.createLineBorder(Color.GRAY, 1);

   public Component getListCellRendererComponent(JList jList, Object value, 
        int index, boolean isSelected, boolean cellHasFocus) {

    jlblCell.setOpaque(true);

    if (isSelected) {
        jlblCell.setForeground(jList.getSelectionForeground());
        jlblCell.setBackground(jList.getSelectionBackground());
        jlblCell.setBorder(new LineBorder(Color.BLUE));
    } else {
        jlblCell.setForeground(jList.getForeground());
        jlblCell.setBackground(jList.getBackground());
    }
    jlblCell.setText(value.toString());
    jlblCell.setBorder(lineBorder);
    return jlblCell;
   }
  }

    def renderer = new MyListCellRenderer();
    def listModel = new DefaultListModel();
    def list = new JList(listModel);
    .
    .
    .
 def dialog = new JDialog(ui.frame);
 dialog.add(new JScrollPane(list));

上面是一个groovy代码。
输入图片此处描述

You can wrap the DefaultListModel into a JList, and add a custom cell renderer to the JList.

class MyListCellRenderer implements ListCellRenderer{

   final JLabel jlblCell = new JLabel(" ", JLabel.LEFT);
   Border lineBorder = BorderFactory.createLineBorder(Color.GRAY, 1);

   public Component getListCellRendererComponent(JList jList, Object value, 
        int index, boolean isSelected, boolean cellHasFocus) {

    jlblCell.setOpaque(true);

    if (isSelected) {
        jlblCell.setForeground(jList.getSelectionForeground());
        jlblCell.setBackground(jList.getSelectionBackground());
        jlblCell.setBorder(new LineBorder(Color.BLUE));
    } else {
        jlblCell.setForeground(jList.getForeground());
        jlblCell.setBackground(jList.getBackground());
    }
    jlblCell.setText(value.toString());
    jlblCell.setBorder(lineBorder);
    return jlblCell;
   }
  }

    def renderer = new MyListCellRenderer();
    def listModel = new DefaultListModel();
    def list = new JList(listModel);
    .
    .
    .
 def dialog = new JDialog(ui.frame);
 dialog.add(new JScrollPane(list));

The above is a groovy code.
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文