【问题标题】:Nimbus L & F: Setting different background colors of a Check-Boxes in a CheckBox ListNimbus L & F:在复选框列表中设置复选框的不同背景颜色
【发布时间】:2012-02-09 12:27:07
【问题描述】:

我有一个复选框列表,我想在每个复选框上设置不同的颜色。 以下代码不会改变背景颜色

checkBox[i] = new JCheckBox();
checkBox[i].setEnabled(false);
checkBox[i].setBackground(Color.GREEN);

请告诉我设置背景颜色的方法

【问题讨论】:

    标签: java swing colors checkbox nimbus


    【解决方案1】:

    例如

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.event.*;
    
    public class JListDisabledItemDemo implements ItemListener, Runnable {
    
        private JFrame f = new JFrame("Colors");
        private static final String ITEMS[] = {" black ", " blue ", " green ",
            " orange ", " purple ", " red ", " white ", " yellow "};
        private JList jList;
        private JCheckBox[] checkBoxes;
        private boolean[] enabledFlags;
    
        @Override
        public void run() {
            JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
            pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
            checkBoxes = new JCheckBox[ITEMS.length];
            enabledFlags = new boolean[ITEMS.length];
            for (int i = 0; i < ITEMS.length; i++) {
                checkBoxes[i] = new JCheckBox(ITEMS[i]);
                checkBoxes[i].setSelected(true);
                checkBoxes[i].addItemListener(this);
                enabledFlags[i] = true;
                pnlEnablers.add(checkBoxes[i]);
            }
            jList = new JList(ITEMS);
            jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            jList.setSelectionModel(new DisabledItemSelectionModel());
            jList.setCellRenderer(new DisabledItemListCellRenderer());
            jList.addListSelectionListener(new ListSelectionListener() {
    
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                        System.out.println("selection");
                    }
                }
            });
            JScrollPane scroll = new JScrollPane(jList);
            scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new GridLayout(1, 2));
            contentPane.add(pnlEnablers);
            contentPane.add(scroll);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocation(240, 280);
            UIManager.put("List.background", Color.lightGray);
            UIManager.put("List.selectionBackground", Color.orange);
            UIManager.put("List.selectionForeground", Color.blue);
            UIManager.put("Label.disabledForeground", Color.magenta);
            SwingUtilities.updateComponentTreeUI(f);
            f.pack();
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    f.setVisible(true);
                }
            });
        }
    
        @Override
        public void itemStateChanged(ItemEvent event) {
            JCheckBox checkBox = (JCheckBox) event.getSource();
            int index = -1;
            for (int i = 0; i < ITEMS.length; i++) {
                if (ITEMS[i].equals(checkBox.getText())) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                enabledFlags[index] = checkBox.isSelected();
                jList.repaint();
            }
        }
    
        public static void main(String args[]) {
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    System.out.println(info.getName());
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            }
            SwingUtilities.invokeLater(new JListDisabledItemDemo());
        }
    
        private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
    
            private static final long serialVersionUID = 1L;
    
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                Component comp = super.getListCellRendererComponent(list, value, index, false, false);
                JComponent jc = (JComponent) comp;
                if (enabledFlags[index]) {
                    if (isSelected & cellHasFocus) {
                        comp.setForeground(Color.black);
                        comp.setBackground(Color.red);
                    } else {
                        comp.setBackground(Color.white);
                        comp.setForeground(Color.black);
                    }
                    if (!isSelected) {
                        if ((value.toString()).trim().equals("yellow")) {
                            comp.setForeground(Color.blue);
                            comp.setBackground(Color.yellow);
                        } else if ((value.toString()).trim().equals("black")) {
                            comp.setForeground(Color.red);
                            comp.setBackground(Color.black);
                        }else if ((value.toString()).trim().equals("orange")) {
                            comp.setForeground(Color.blue);
                            comp.setBackground(Color.orange);
                        }
                    }
                    return comp;
                }
                comp.setEnabled(false);
                return comp;
            }
        }
    
        private class DisabledItemSelectionModel extends DefaultListSelectionModel {
    
            private static final long serialVersionUID = 1L;
    
            @Override
            public void setSelectionInterval(int index0, int index1) {
                if (enabledFlags[index0]) {
                    super.setSelectionInterval(index0, index0);
                } else {
                    /*The previously selected index is before this one,
                     * so walk forward to find the next selectable item.*/
                    if (getAnchorSelectionIndex() < index0) {
                        for (int i = index0; i < enabledFlags.length; i++) {
                            if (enabledFlags[i]) {
                                super.setSelectionInterval(i, i);
                                return;
                            }
                        }
                    } /*
                     * Otherwise, walk backward to find the next selectable item.
                     */ else {
                        for (int i = index0; i >= 0; i--) {
                            if (enabledFlags[i]) {
                                super.setSelectionInterval(i, i);
                                return;
                            }
                        }
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 据我了解的问题,它是关于更改 checkbox 的背景与更改列表中项目的背景(在此处回答)...
    • Nimbus 和 Aqua,例如,不显示按钮的背景颜色。 +1 因为这是一个有趣的选择。另请参阅 ButtonTest,它使用封闭面板。
    • 你能在 OSX 上贴一张 Nimbus 和 Aqua 的照片吗,真的是时候省点钱买 OSX 的东西了
    • @mKorbel 感谢您的回复。但我的问题是关于设置“复选框”列表而不是列表中项目的背景颜色。
    • @Anuj Mehta 将 JCheckbox 放到 JTable 中,用一列(最简单和舒适的方式)而不是 JList,那么这与我的示例相同,内置渲染器可以做到这一点
    【解决方案2】:

    尝试将 CheckBox Opacity 设置为 true。

    myCheckBox.setOpaque(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 2012-09-07
      • 2013-11-29
      相关资源
      最近更新 更多