1 11 package org.eclipse.ant.internal.ui.preferences; 12 13 14 import org.eclipse.swt.SWT; 15 import org.eclipse.swt.events.DisposeEvent; 16 import org.eclipse.swt.events.DisposeListener; 17 import org.eclipse.swt.events.SelectionAdapter; 18 import org.eclipse.swt.events.SelectionEvent; 19 import org.eclipse.swt.graphics.Color; 20 import org.eclipse.swt.graphics.Font; 21 import org.eclipse.swt.graphics.GC; 22 import org.eclipse.swt.graphics.Image; 23 import org.eclipse.swt.graphics.Point; 24 import org.eclipse.swt.graphics.RGB; 25 import org.eclipse.swt.widgets.Button; 26 import org.eclipse.swt.widgets.ColorDialog; 27 import org.eclipse.swt.widgets.Composite; 28 import org.eclipse.swt.widgets.Control; 29 import org.eclipse.swt.widgets.Display; 30 31 import org.eclipse.jface.resource.JFaceResources; 32 33 36 public class ColorEditor { 37 38 private Point fExtent; 39 private Image fImage; 40 private RGB fColorValue; 41 private Color fColor; 42 private Button fButton; 43 44 public ColorEditor(Composite parent) { 45 46 fButton= new Button(parent, SWT.PUSH); 47 fExtent= computeImageSize(parent); 48 fImage= new Image(parent.getDisplay(), fExtent.x, fExtent.y); 49 50 GC gc= new GC(fImage); 51 gc.setBackground(fButton.getBackground()); 52 gc.fillRectangle(0, 0, fExtent.x, fExtent.y); 53 gc.dispose(); 54 55 fButton.setImage(fImage); 56 fButton.addSelectionListener(new SelectionAdapter() { 57 public void widgetSelected(SelectionEvent event) { 58 ColorDialog colorDialog= new ColorDialog(fButton.getShell()); 59 colorDialog.setRGB(fColorValue); 60 RGB newColor = colorDialog.open(); 61 if (newColor != null) { 62 fColorValue= newColor; 63 updateColorImage(); 64 } 65 } 66 }); 67 68 fButton.addDisposeListener(new DisposeListener() { 69 public void widgetDisposed(DisposeEvent event) { 70 if (fImage != null) { 71 fImage.dispose(); 72 fImage= null; 73 } 74 if (fColor != null) { 75 fColor.dispose(); 76 fColor= null; 77 } 78 } 79 }); 80 } 81 82 public RGB getColorValue() { 83 return fColorValue; 84 } 85 86 public void setColorValue(RGB rgb) { 87 fColorValue= rgb; 88 updateColorImage(); 89 } 90 91 public Button getButton() { 92 return fButton; 93 } 94 95 protected void updateColorImage() { 96 97 Display display= fButton.getDisplay(); 98 99 GC gc= new GC(fImage); 100 gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); 101 gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4); 102 103 if (fColor != null) 104 fColor.dispose(); 105 106 fColor= new Color(display, fColorValue); 107 gc.setBackground(fColor); 108 gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5); 109 gc.dispose(); 110 111 fButton.setImage(fImage); 112 } 113 114 protected Point computeImageSize(Control window) { 115 GC gc= new GC(window); 116 Font f= JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT); 117 gc.setFont(f); 118 int height= gc.getFontMetrics().getHeight(); 119 gc.dispose(); 120 Point p= new Point(height * 3 - 6, height); 121 return p; 122 } 123 } 124 | Popular Tags |