正如您所注意到的,即使面板本身不可访问,也没有公共API可以访问DefaultSwatchChooserPanel中的最新颜色。
由于您将需要一些逻辑/
bean来保持和重置最近的颜色(以及扩展的鼠标交互),因此滚动自己的方式是可行的。为了获得一些指导,请看一下样本面板的实现(咳嗽…
c&p所需的内容,并修改不需要的内容)。基本上,像
// a bean that keeps track of the colorspublic static class ColorTracker extends AbstractBean { private List<Color> colors = new ArrayList<>(); public void addColor(Color color) { List<Color> old = getColors(); colors.add(0, color); firePropertyChange("colors", old, getColors()); } public void setColors(List<Color> colors) { List<Color> old = getColors(); this.colors = new ArrayList<>(colors); firePropertyChange("colors", old, getColors()); } public List<Color> getColors() { return new ArrayList<>(colors); }}// a custom SwatchChooserPanel which takes and listens to the tracker changespublic class MySwatchChooserPanel ... { ColorTracker tracker; public void setColorTracker(....) { // uninstall old tracker .... // install new tracker this.tracker = tracker; if (tracker != null) tracker.addPropertyChangeListener(.... ); updateRecentSwatchPanel() } protected void updateRecentSwatchPanel() { if (recentSwatchPanel == null) return; recentSwatchPanel.setMostRecentColors(tracker != null ? tracker.getColors() : null); }// the mouseListener which updates the tracker and triggers the doubleClickAction// if availableclass MainSwatchListener extends MouseAdapter implements Serializable { @Override public void mousePressed(MouseEvent e) { if (!isEnabled()) return; if (e.getClickCount() == 2) { handleDoubleClick(e); return; } Color color = swatchPanel.getColorForLocation(e.getX(), e.getY()); setSelectedColor(color); if (tracker != null) { tracker.addColor(color); } else { recentSwatchPanel.setMostRecentColor(color); } } private void handleDoubleClick(MouseEvent e) { if (action != null) { action.actionPerformed(null); } }}}// client pre can install the custom panel on a JFileChooser, passing in a trackerprivate JColorChooser createChooser(ColorTracker tracker) { JColorChooser chooser = new JColorChooser(); List<AbstractColorChooserPanel> choosers = new ArrayList<>(Arrays.asList(chooser.getChooserPanels())); choosers.remove(0); MySwatchChooserPanel swatch = new MySwatchChooserPanel(); swatch.setColorTracker(tracker); swatch.setAction(doubleClickAction); choosers.add(0, swatch); chooser.setChooserPanels(choosers.toArray(new AbstractColorChooserPanel[0])); return chooser;}关于doubleClick处理:增强swatchChooser采取的操作,并在适当时从mouseListener调用该操作。



