java自定义colorChooserPanel

时间:2016-07-06 10:26:38

标签: java jcolorchooser

我想在java swing中为ColorChooserPanel创建自定义JcolorChooser

public class ColorPanel  extends AbstractColorChooserPanel {

    public void buildChooser() {
        setLayout(new GridLayout(1, 3));
        makeAddButton("Red", Color.red);
        makeAddButton("Green", Color.green);
        makeAddButton("Blue", Color.blue);  }

        public void updateChooser() {
        }
        public String getDisplayName() {
            return "MyChooserPanel";  }

        public Icon getSmallDisplayIcon() {
            return null;  }

        public Icon getLargeDisplayIcon() {
            return null;  }

        private void makeAddButton(String name, Color color) {
            JButton button = new JButton(name);
            button.setBackground(color);
            button.setAction(new AbstractAction() {
                private static final long serialVersionUID = 1L;

                public void actionPerformed(ActionEvent arg0) {
                    JButton button = (JButton) arg0.getSource();
                    getColorSelectionModel().setSelectedColor(button.getBackground());

            }});
            add(button);  }
}

它应显示3个颜色按钮,但它显示6个按钮。愿有人告诉我哪里弄错了吗?我该如何删除下面的面板。

ColorPanel colorPanel  = new ColorPanel();
colorPanel.buildChooser();
colorChooser =  new JColorChooser();
colorChooser.addChooserPanel(colorPanel);

http://i.stack.imgur.com/u1fag.png

另一个问题:我可以通过色板颜色面板删除最近的窗格。我只想展示颜色托盘。我的意思是"最近"部分如下图所示。

http://i.stack.imgur.com/VfdDJ.png

1 个答案:

答案 0 :(得分:0)

ColorPanel colorPanel  = new ColorPanel();
// colorPanel.buildChooser(); <-- remove this line

colorPanel添加到JChooserPanel时,会调用此方法:

public void installChooserPanel(JColorChooser enclosingChooser) {
    if (chooser != null) {
        throw new RuntimeException ("This chooser panel is already installed");
    }
    chooser = enclosingChooser;
    chooser.addPropertyChangeListener("enabled", enabledListener);
    setEnabled(chooser.isEnabled());
    buildChooser();
    updateChooser();
}

因此,当您将面板添加到colorChooser时,您无需再次“构建”面板。