更改特定jlist元素的颜色

时间:2018-07-30 15:04:07

标签: java swing jlist renderer

我已经从事Messenger项目已有一段时间了,我需要在JList中设置特定元素的颜色。我已经在互联网上阅读了很多东西,但并没有得到一个简单的解释。确切地说,我正在检查用户是否有未读消息以及是否有未读消息。做一些表明该特定用户有消息的操作。我想到的是更改该元素的颜色,但我还不知道该怎么做。我创建了一个小的可执行代码,在其中我只想更改那些标志为true的代码的颜色。可以生成如下。

任何人都可以在此代码中相应地使用ListCellRenderer,以便我知道该怎么做。

    package newpackage;

    import javax.swing.DefaultListModel;


    public class NewJFrame extends javax.swing.JFrame {
public boolean f0,f1,f2,f3,f4;
/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    f1=f2=f0=true;
    f3=f4=false;
    initComponents();
    lst.setModel(addToList());
}

public DefaultListModel addToList() {
    DefaultListModel<String> dlm = new DefaultListModel<String>();
    for (int i = 0; i < 5; i++) {
        dlm.addElement("Item"+i);
    }
    return dlm;

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    lst = new javax.swing.JList<>();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jScrollPane1.setViewportView(lst);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(277, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(36, 36, 36)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(14, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<String> lst;
// End of variables declaration                   

}

编辑1:好吧,我阅读了文章并设置了自定义渲染器。它按预期运行,但不像我想要的那样。在我的代码中,setCellRenderer方法被多次调用,并且每次都应该更改JList的不同元素的颜色,这样做很好,但是我不希望渲染器更改以前更改的颜色元素以正常方式生成。用短代码重新生成问题将很困难,因此我将举一个小例子来说明。让我们假设我的JList包含4个元素item1,item2,item3,item4。现在第一次调用setCellRenderer方法时,它将item1的颜色更改为只说绿色,而其他所有元素当前都为黑色。现在再次调用setCellRenderer方法时,它更改了元素的颜色,即说item3变为绿色,它不应执行的操作是再次将item1的颜色更改为黑色,使其保持绿色。任何人都可以提出一种解决方法。

0 个答案:

没有答案
相关问题