private void newImage(Buffer buffer) { Object data = buffer.getData(); if (!(data instanceof int[])) return; RGBFormat format = (RGBFormat) buffer.getFormat(); DirectColorModel dcm = new DirectColorModel( format.getBitsPerPixel(), format.getRedMask(), format.getGreenMask(), format.getBlueMask()); sourceImage = new MemoryImageSource( format.getLineStride(), format.getSize().height, dcm, (int[]) data, 0, format.getLineStride()); sourceImage.setAnimated(true); sourceImage.setFullBufferUpdates(true); if (component != null) { destImage = component.createImage(sourceImage); component.prepareImage(destImage, component); } }
/** * Create possibly volatile scratch image for fast painting. A scratch image can become * invalidated, when this happens any actions involving it are ignored, and it needs to be * recreated. Use isScratchImageValid() to check this. */ public static Image createScratchImage(int width, int height) { try { Image img = (Image) tryMethod( output_comp, "createVolatileImage", new Object[] {new Integer(width), new Integer(height)}); if (img == null) { // no such method -> create regular image return output_comp.createImage(width, height); } // if (img.validate(output_comp.getGraphicsConfiguration()) // == VolatileImage.IMAGE_INCOMPATIBLE) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); Integer valid = (Integer) tryMethod(img, "validate", new Object[] {gc}); // output_comp.getGraphicsConfiguration() }); if (valid.intValue() == 2) { // I checked, IMAGE_INCOMPATIBLE=2 // Hmm, somehow it didn't work. Create regular image. return output_comp.createImage(width, height); } return img; } catch (java.security.AccessControlException e) { // we're not allowed to do this (we're probably an applet) return output_comp.createImage(width, height); } }
private void hideDropDownButton() { for (Component component : this.getComponents()) { if (component instanceof AbstractButton && component.isVisible()) { component.setVisible(false); this.revalidate(); } } }
public void paint(Graphics g1) { Graphics2D g = (Graphics2D) g1; Component c; Point p; paintComponent(g); for (int i = 0; i < getComponentCount(); i++) { AffineTransform save = g.getTransform(); c = getComponent(i); p = c.getLocation(); g.translate((int) p.getX(), (int) p.getY()); c.paint(g); g.setTransform(save); } }
public JGImage flip(boolean horiz, boolean vert) { @SuppressWarnings("unused") Image flipped = null; JGPoint size = getSize(); int[] buffer = getPixels(); int[] flipbuf = new int[size.x * size.y]; if (vert && !horiz) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[(size.y - y - 1) * size.x + x] = buffer[(y * size.x) + x]; } } } else if (horiz && !vert) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[y * size.x + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } else if (horiz && vert) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[(size.y - y - 1) * size.x + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.x, size.y, flipbuf, 0, size.x))); }
public JGImage crop(int x, int y, int width, int height) { @SuppressWarnings("unused") JGPoint size = getSize(); int[] buffer = getPixels(x, y, width, height); return new JREImage( output_comp.createImage(new MemoryImageSource(width, height, buffer, 0, width))); }
/** * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_ * indexed images. Images are cached: loading an image with the same name twice will get the * cached image the second time. If you want to remove an image from the cache, use purgeImage. * Throws JGError when there was an error. */ @SuppressWarnings({"deprecation", "unchecked"}) public JGImage loadImage(String imgfile) { Image img = (Image) loadedimages.get(imgfile); if (img == null) { URL imgurl = getClass().getResource(imgfile); if (imgurl == null) { try { File imgf = new File(imgfile); if (imgf.canRead()) { imgurl = imgf.toURL(); } else { imgurl = new URL(imgfile); // throw new JGameError( // "File "+imgfile+" not found.",true); } } catch (MalformedURLException e) { // e.printStackTrace(); throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true); } } img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgfile, img); } try { ensureLoaded(img); } catch (Exception e) { // e.printStackTrace(); throw new JGameError("Error loading image " + imgfile); } return new JREImage(img); }
/** for angle, only increments of 90 are allowed */ public JGImage rotate(int angle) { @SuppressWarnings("unused") Image rot = null; JGPoint size = getSize(); int[] buffer = getPixels(); int[] rotate = new int[size.x * size.y]; int angletype = (angle / 90) & 3; if (angletype == 0) return this; if (angletype == 1) { /* 1 2 3 4 9 5 1 * 5 6 7 8 => a 6 2 * 9 a b c b 7 3 * c 8 4 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[x * size.y + (size.y - 1 - y)] = buffer[(y * size.x) + x]; } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.y, size.x, rotate, 0, size.y))); } if (angletype == 3) { /* 1 2 3 4 4 8 c * 5 6 7 8 => 3 7 b * 9 a b c 2 6 a * 1 5 9 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[(size.x - x - 1) * size.y + y] = buffer[(y * size.x) + x]; } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.y, size.x, rotate, 0, size.y))); } if (angletype == 2) { /* 1 2 3 4 c b a 9 * 5 6 7 8 => 8 7 6 5 * 9 a b c 4 3 2 1 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[((size.y - y - 1) * size.x) + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.x, size.y, rotate, 0, size.x))); }
static void enforceComponentOrientation( final Component c, final ComponentOrientation orientation) { c.setComponentOrientation(orientation); if (c instanceof Container) { for (final Component child : ((Container) c).getComponents()) { enforceComponentOrientation(child, orientation); } } }
/* * Create a BufferedImage for AWT components. * * @param component AWT component to create image from * @param fileName name of file to be created or null * @return image the image for the given region * @exception AWTException see Robot class constructors * @exception IOException if an error occurs during writing */ public static BufferedImage createImage(Component component, String fileName) throws AWTException, IOException { Point p = new Point(0, 0); SwingUtilities.convertPointToScreen(p, component); Rectangle region = component.getBounds(); region.x = p.x; region.y = p.y; return ScreenCapture.createImage(region, fileName); }
/** * Turn a (possibly) translucent or indexed image into a display-compatible bitmask image using * the given alpha threshold and render-to-background colour, or display-compatible translucent * image. The alpha values in the image are set to either 0 (below threshold) or 255 (above * threshold). The render-to-background colour bg_col is used to determine how the pixels * overlapping transparent pixels should be rendered. The fast algorithm just sets the colour * behind the transparent pixels in the image (for bitmask source images); the slow algorithm * actually renders the image to a background of bg_col (for translucent sources). * * @param thresh alpha threshold between 0 and 255 * @param fast use fast algorithm (only set bg_col behind transp. pixels) * @param bitmask true=use bitmask, false=use translucent */ public JGImage toDisplayCompatible(int thresh, JGColor bg_col, boolean fast, boolean bitmask) { Color bgcol = new Color(bg_col.r, bg_col.g, bg_col.b); int bgcol_rgb = (bgcol.getRed() << 16) | (bgcol.getGreen() << 8) | bgcol.getBlue(); JGPoint size = getSize(); int[] buffer = getPixels(); // render image to bg depending on bgcol BufferedImage img_bg; if (bitmask) { img_bg = createCompatibleImage(size.x, size.y, Transparency.BITMASK); } else { img_bg = createCompatibleImage(size.x, size.y, Transparency.TRANSLUCENT); } int[] bg_buf; if (!fast) { Graphics g = img_bg.getGraphics(); g.setColor(bgcol); // the docs say I could use bgcol in the drawImage as an // equivalent to the following two lines, but this // doesn't handle translucency properly and is _slower_ g.fillRect(0, 0, size.x, size.y); g.drawImage(img, 0, 0, null); bg_buf = new JREImage(img_bg).getPixels(); } else { bg_buf = buffer; } // g.dispose(); // ColorModel rgb_bitmask = ColorModel.getRGBdefault(); // rgb_bitmask = new PackedColorModel( // rgb_bitmask.getColorSpace(),25,0xff0000,0x00ff00,0x0000ff, // 0x1000000, false, Transparency.BITMASK, DataBuffer.TYPE_INT); // ColorSpace space, int bits, int rmask, int gmask, int bmask, int amask, boolean // isAlphaPremultiplied, int trans, int transferType) int[] thrsbuf = new int[size.x * size.y]; for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { if (((buffer[y * size.x + x] >> 24) & 0xff) >= thresh) { thrsbuf[y * size.x + x] = bg_buf[y * size.x + x] | (0xff << 24); } else { // explicitly set the colour of the transparent pixel. // This makes a difference when scaling! // thrsbuf[y*size.x+x]=bg_buf[y*size.x+x]&~(0xff<<24); thrsbuf[y * size.x + x] = bgcol_rgb; } } } return new JREImage( output_comp.createImage( new MemoryImageSource( size.x, size.y, // rgb_bitmask, img_bg.getColorModel(), // display compatible bitmask bitmask ? thrsbuf : bg_buf, 0, size.x))); }
/** * Returns the native container object of the specified component. This method is necessary * because the parent component might be a lightweight component. * * @param component The component to fetch the native container for. * @return The native container object for this component. */ protected static Container getNativeContainer(Component component) { component = component.getParent(); for (; ; ) { if (component == null) return (null); if (!(component instanceof Container)) { component = component.getParent(); continue; } if (component.getPeer() instanceof LightweightPeer) { component = component.getParent(); continue; } return ((Container) component); } }
/** Processes the data and renders it to a component */ public synchronized int process(Buffer buffer) { if (component == null) return BUFFER_PROCESSED_FAILED; Format inf = buffer.getFormat(); if (inf == null) return BUFFER_PROCESSED_FAILED; if (inf != inputFormat || !buffer.getFormat().equals(inputFormat)) { if (setInputFormat(inf) != null) return BUFFER_PROCESSED_FAILED; } Object data = buffer.getData(); if (!(data instanceof int[])) return BUFFER_PROCESSED_FAILED; if (lastBuffer != buffer) { lastBuffer = buffer; newImage(buffer); } sourceImage.newPixels(0, 0, inWidth, inHeight); Graphics g = component.getGraphics(); if (g != null) { if (reqBounds == null) { bounds = component.getBounds(); bounds.x = 0; bounds.y = 0; } else bounds = reqBounds; g.drawImage( destImage, bounds.x, bounds.y, bounds.width, bounds.height, 0, 0, inWidth, inHeight, component); } return BUFFER_PROCESSED_OK; }
/** * Checks if the component is in an EmbeddedFrame. If so, returns the applet found in the * hierarchy or null if not found. * * @return the parent applet or {@ null} * @since 1.6 */ public static Applet getAppletIfAncestorOf(Component comp) { Container parent = comp.getParent(); Applet applet = null; while (parent != null && !(parent instanceof EmbeddedFrame)) { if (parent instanceof Applet) { applet = (Applet) parent; } parent = parent.getParent(); } return parent == null ? null : applet; }
@SuppressWarnings("deprecation") private void replaceSurfaceDataRecursively(Component c) { if (c instanceof Container) { for (Component child : ((Container) c).getComponents()) { replaceSurfaceDataRecursively(child); } } ComponentPeer cp = c.getPeer(); if (cp instanceof WComponentPeer) { ((WComponentPeer) cp).replaceSurfaceDataLater(); } }
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (image != null && showimage) { // TODO: add ability to scale maintaining aspect ratio fitting to size of parent // TODO: Need to add not zoom all the way, but zoom to a box of aspect ratio 4/3 Graphics2D g2 = (Graphics2D) g; AffineTransform tran = new AffineTransform(1f, 0f, 0f, 1f, 0, 0); float widthscale = (float) c.getWidth() / image.getWidth(); float heightscale = (float) c.getHeight() / image.getHeight(); switch (drawmode) { case DRAW_MODE_ASPECT: float scale; if (widthscale < heightscale) { scale = widthscale; } else { scale = heightscale; } tran.scale(scale, scale); g2.drawImage( image, new AffineTransformOp(tran, AffineTransformOp.TYPE_BILINEAR), (int) (c.getWidth() - image.getWidth() * scale) / 2, (int) (c.getHeight() - image.getHeight() * scale) / 2); break; case DRAW_MODE_WIDTH: tran.scale(widthscale, widthscale); g2.drawImage(image, tran, null); break; case DRAW_MODE_HEIGHT: tran.scale(heightscale, heightscale); g2.drawImage(image, tran, null); break; default: tran.scale(widthscale, heightscale); g2.drawImage(image, tran, null); break; } } }
BufferedImage createImageFromComponent(Component comp) { BufferedImage retImage = null; if (comp == null) return retImage; try { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = genv.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); java.awt.image.ColorModel cm = gc.getColorModel(); boolean hasAlpha = cm.hasAlpha(); int cw = comp.getSize().width; int ch = comp.getSize().height; if (hasAlpha) { retImage = gc.createCompatibleImage(cw, ch); } else { retImage = new BufferedImage(cw, ch, BufferedImage.TYPE_INT_ARGB); } if (retImage == null) return retImage; Graphics og = retImage.getGraphics(); comp.paint(og); og.dispose(); } catch (Throwable t) { } return retImage; }
/** Behaves like loadImage(String). Returns null if there was an error. */ @SuppressWarnings("unchecked") public static JGImage loadImage(URL imgurl) { Image img = (Image) loadedimages.get(imgurl); if (img == null) { img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgurl, img); } try { ensureLoaded(img); } catch (Exception e) { System.err.println("Error loading image " + imgurl); return null; } return new JREImage(img); }
public void setActivo(boolean val) { glass.setVisible(val); setVisible(val); JLayeredPane.getLayeredPaneAbove(glass).moveToFront(glass); if (val) { synchronized (syncMonitor) { try { if (SwingUtilities.isEventDispatchThread()) { EventQueue theQueue = getToolkit().getSystemEventQueue(); while (isVisible()) { AWTEvent event = theQueue.getNextEvent(); Object source = event.getSource(); if (event instanceof ActiveEvent) { ((ActiveEvent) event).dispatch(); } else if (source instanceof Component) { ((Component) source).dispatchEvent(event); } else if (source instanceof MenuComponent) { ((MenuComponent) source).dispatchEvent(event); } else { System.out.println("No se puede despachar: " + event); } } } else { while (isVisible()) { syncMonitor.wait(); } } } catch (InterruptedException ignored) { System.out.println("Excepción de interrupción: " + ignored.getMessage()); } } } else { synchronized (syncMonitor) { setVisible(false); glass.setVisible(false); syncMonitor.notifyAll(); eliminarDelContenedor(); } } }
/** Prepare ball images with different sizes */ private void makeBalls() { balls = new Image[nBalls]; byte red[] = new byte[256]; byte green[] = new byte[256]; byte blue[] = new byte[256]; for (int id = 0; id < nBalls; id++) { // smaller `b' means closer to black // if id == 0 (fartherest from the viewer) // b = 1/(1 + zContrast) // the outer blend() gives a color close to bgGrey // if id == nBalls - 1 (closest to the viewer), // b = 1, the outer blend() gives the color of // the inner blend() double b = (zContrast * id / (nBalls - 1) + 1) / (zContrast + 1); for (int i = maxr; i >= 0; --i) { // closeness to the spotlight double q = 1 - 1. * i / maxr; // dampness of the color along the radius double p = 1 - rContrast * i / maxr; // contrast of the spotlight // if i == 0 (closest to the spotlight), // d = 1.0 - spotlightAmp, the inner // blend() gives a color close to 255 // (if spotlightAmp == 1). // if i == maxr (fartherest from the spotlight), // d = 1.0, the inner blend() gives // the foreground color, i.e., Rl, Gl, Bl // Thus, the inner blend() depends on the distance // from the spotlight, i == 0 means to be closest // to the spotlight double d = 1 - q * spotlightAmp; red[i] = (byte) blend(blend(Rl * p, 255, d), 0, b); green[i] = (byte) blend(blend(Gl * p, 255, d), 0, b); blue[i] = (byte) blend(blend(Bl * p, 255, d), 0, b); } // 256 color model IndexColorModel model = new IndexColorModel(8, maxr + 1, red, green, blue, 0); balls[id] = component.createImage(new MemoryImageSource(R * 2, R * 2, model, data, 0, R * 2)); } }
public void paint( Component c, Graphics2D g, java.util.List gradient, int x, int y, int w, int h, boolean isVertical) { int imageWidth; int imageHeight; if (isVertical) { imageWidth = IMAGE_SIZE; imageHeight = h; } else { imageWidth = w; imageHeight = IMAGE_SIZE; } synchronized (c.getTreeLock()) { this.w = w; this.h = h; paint(c, g, x, y, imageWidth, imageHeight, gradient, isVertical); } }
/** Method to get the previous component for focus */ public Component getComponentBefore(Container focusCycleRoot, Component aComponent) { if (aComponent.equals(colValue)) return rowValue; else return colValue; }
static void fillRect(final Graphics g, final Component c) { fillRect(g, c, c.getBackground(), 0, 0, c.getWidth(), c.getHeight()); }
/** * Invoked when the animated icon indicates that it is time for a repaint. * * @param context Component to refresh * @param key Substructure identification key */ protected void repaint(Component context, Object key) { Rectangle rect = getRepaintRect(context, key); if (rect != null) { context.repaint(rect.x, rect.y, rect.width, rect.height); } }
/* * Convenience function for determining ComponentOrientation. Helps us * avoid having Munge directives throughout the code. */ static boolean isLeftToRight(Component c) { return c.getComponentOrientation().isLeftToRight(); }