【问题标题】:Change font and backgroundcolor of a line in a JList更改 JList 中一行的字体和背景颜色
【发布时间】:2015-01-07 09:32:47
【问题描述】:

我在JOptionPane 中使用JList 在对话框中显示行。 我只是想改变线条的背景颜色和字体(取决于线条的内容)。

我无法实现,也没有找到任何有用的文章。 我的实际问题是,我的以下代码中的方法 getListCellRendererComponent 永远不会被调用。对话框显示为一行“一行的任何文本”,但没有颜色/字体更改。

有人可以帮忙吗?

    final DefaultListModel d = new DefaultListModel();
    final JList list = new JList(d);

    ListCellRenderer renderer = new ListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            JLabel label = new JLabel();
            label.setText(value.toString());

            label.setFont(new Font("Courier New", Font.ITALIC, 12));
            label.setBackground(new Color(12, 12, 12));

            int i = 1 / 0;  // <<<<<<  --- does not throw an error, so it doesn't get into this.
            return label;
        }
    };
    list.setCellRenderer(renderer);

    for (int iList = 0; iList < alSuggestionsText.size(); iList++) {
        // bigList[iList] = alTexte.get(iList);
        d.addElement(alSuggestionsText.get(iList));
        // jlist.add(bigList);
    }

    final String sIgronreText = "any text for one line";

    d.addElement(sIgronreText);

    final JList jlist = new JList(d);

    JOptionPane jpane = new JOptionPane();
    jpane.showMessageDialog(null, jlist, sWikiidtemp, JOptionPane.PLAIN_MESSAGE);

【问题讨论】:

    标签: java swing jlist joptionpane


    【解决方案1】:

    您有两个不同的 JList。第一个设置 ListCellRenderrer。

    list.setCellRenderer(renderer);
    

    还有你在对话框中显示的另一个:

    pane.showMessageDialog(null, jlist, "adsfasdf", JOptionPane.PLAIN_MESSAGE);
    

    添加:

        final JList jlist = new JList(d);
        jlist.setCellRenderer(renderer);
    

    让它工作。

    【讨论】:

    • 天哪。我太傻了!!!!是的你是对的。非常感谢您对它进行如此详细的研究。我现在很高兴:-)
    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2012-08-20
    • 2013-10-02
    • 2012-12-12
    • 2014-07-30
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多