下面列出了怎么用java.awt.GraphicsConfiguration的API类实例代码及写法,或者点击链接到github查看源代码。
public boolean updateGraphicsData(GraphicsConfiguration gc) {
int oldVisual = -1, newVisual = -1;
if (graphicsConfig != null) {
oldVisual = graphicsConfig.getVisual();
}
if (gc != null && gc instanceof X11GraphicsConfig) {
newVisual = ((X11GraphicsConfig)gc).getVisual();
}
// If the new visual differs from the old one, the peer must be
// recreated because X11 does not allow changing the visual on the fly.
// So we even skip the initGraphicsConfiguration() call.
// The initial assignment should happen though, hence the != -1 thing.
if (oldVisual != -1 && oldVisual != newVisual) {
return true;
}
initGraphicsConfiguration();
doValidateSurface();
return false;
}
@Override
protected Image getBackBuffer(boolean clear) {
int w = window.getWidth();
int h = window.getHeight();
GraphicsConfiguration gc = peer.getGraphicsConfiguration();
if (viBB == null || viBB.getWidth() != w || viBB.getHeight() != h ||
viBB.validate(gc) == IMAGE_INCOMPATIBLE)
{
flush();
if (gc instanceof AccelGraphicsConfig) {
AccelGraphicsConfig agc = ((AccelGraphicsConfig)gc);
viBB = agc.createCompatibleVolatileImage(w, h,
TRANSLUCENT,
RT_PLAIN);
}
if (viBB == null) {
viBB = gc.createCompatibleVolatileImage(w, h, TRANSLUCENT);
}
viBB.validate(gc);
}
return clear ? clearImage(viBB) : viBB;
}
/**
* Creates a software-based surface (of type BufImgSurfaceData).
* The software representation is only created when needed, which
* is only during some situation in which the hardware surface
* cannot be allocated. This allows apps to at least run,
* albeit more slowly than they would otherwise.
*/
protected SurfaceData getBackupSurface() {
if (sdBackup == null) {
GraphicsConfiguration gc = vImg.getGraphicsConfig();
AffineTransform tx = gc.getDefaultTransform();
double scaleX = tx.getScaleX();
double scaleY = tx.getScaleY();
BufferedImage bImg = vImg.getBackupImage(scaleX, scaleY);
// Sabotage the acceleration capabilities of the BufImg surface
SunWritableRaster.stealTrackable(bImg
.getRaster()
.getDataBuffer()).setUntrackable();
sdBackup = BufImgSurfaceData.createData(bImg, scaleX, scaleY);
}
return sdBackup;
}
private void runTest() {
GraphicsConfiguration gc = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
if (gc.getColorModel().getPixelSize() < 16) {
System.out.println("8-bit desktop depth found, test passed");
return;
}
VolatileImage vi = gc.createCompatibleVolatileImage(R_WIDTH, R_HEIGHT);
BufferedImage bi = null;
do {
vi.validate(gc);
Graphics2D g = vi.createGraphics();
render(g, vi.getWidth(), vi.getHeight());
bi = vi.getSnapshot();
} while (vi.contentsLost());
checkBI(bi);
System.out.println("Test PASSED.");
}
/**
* Creates an Image from the specified Icon
*
* @param icon
* that should be converted to an image
* @return the new image
*/
public static Image iconToImage(Icon icon) {
if (icon instanceof ImageIcon) {
return ((ImageIcon) icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
public static void main(String[] args) {
boolean iaeThrown = false;
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsConfiguration gc = ge.getDefaultScreenDevice().
getDefaultConfiguration();
try {
VolatileImage volatileImage = gc.createCompatibleVolatileImage(0, 0);
} catch (IllegalArgumentException iae) {
iaeThrown = true;
}
if (!iaeThrown) {
throw new RuntimeException ("IllegalArgumentException not thrown " +
"for createCompatibleVolatileImage(0,0)");
}
}
private static BufferedImage makeUnmanagedBI(GraphicsConfiguration gc,
int type) {
BufferedImage img = gc.createCompatibleImage(SIZE, SIZE, type);
Graphics2D g2d = img.createGraphics();
g2d.setColor(RGB);
g2d.fillRect(0, 0, SIZE, SIZE);
g2d.dispose();
final DataBuffer db = img.getRaster().getDataBuffer();
if (db instanceof DataBufferInt) {
((DataBufferInt) db).getData();
} else if (db instanceof DataBufferShort) {
((DataBufferShort) db).getData();
} else if (db instanceof DataBufferByte) {
((DataBufferByte) db).getData();
} else {
try {
img.setAccelerationPriority(0.0f);
} catch (final Throwable ignored) {
}
}
return img;
}
private static void testVolatileImage(GraphicsConfiguration cfg,
boolean accelerated)
{
VolatileImage dst = null;
try {
dst = cfg.createCompatibleVolatileImage(640, 480,
new ImageCapabilities(accelerated));
} catch (AWTException e) {
System.out.println("Unable to create volatile image, skip the test.");
return;
}
renderToVolatileImage(dst);
}
static Image getBMImage(GraphicsConfiguration gc,
int w, int h)
{
Image image =
gc.createCompatibleImage(w, h, Transparency.BITMASK);
initImage(gc, image);
return image;
}
private static void testGC(GraphicsConfiguration gc) {
if (!(gc instanceof AccelGraphicsConfig)) {
System.out.println("Test passed: no hw accelerated configs found.");
return;
}
System.out.println("AccelGraphicsConfig exists, testing.");
AccelGraphicsConfig agc = (AccelGraphicsConfig) gc;
printAGC(agc);
testContext(agc);
VolatileImage vi = gc.createCompatibleVolatileImage(10, 10);
vi.validate(gc);
if (vi instanceof DestSurfaceProvider) {
System.out.println("Passed: VI is DestSurfaceProvider");
Surface s = ((DestSurfaceProvider) vi).getDestSurface();
if (s instanceof AccelSurface) {
System.out.println("Passed: Obtained Accel Surface");
printSurface((AccelSurface) s);
}
Graphics g = vi.getGraphics();
if (g instanceof DestSurfaceProvider) {
System.out.println("Passed: VI graphics is " +
"DestSurfaceProvider");
printSurface(((DestSurfaceProvider) g).getDestSurface());
}
} else {
System.out.println("VI is not DestSurfaceProvider");
}
testVICreation(agc, CAPS_RT_TEXTURE_ALPHA, TRANSLUCENT, RT_TEXTURE);
testVICreation(agc, CAPS_RT_TEXTURE_OPAQUE, OPAQUE, RT_TEXTURE);
testVICreation(agc, CAPS_RT_PLAIN_ALPHA, TRANSLUCENT, RT_PLAIN);
testVICreation(agc, agc.getContextCapabilities().getCaps(), OPAQUE,
TEXTURE);
testForNPEDuringCreation(agc);
}
/**
* Constructor for the solitary "page setup" dialog
*/
public ServiceDialog(GraphicsConfiguration gc,
int x, int y,
PrintService ps,
DocFlavor flavor,
PrintRequestAttributeSet attributes,
Dialog dialog)
{
super(dialog, getMsg("dialog.pstitle"), true, gc);
initPageDialog(x, y, ps, flavor, attributes);
}
/**
* Need to override the default behavior because Pixmaps-based
* images are accelerated but not volatile.
*/
@Override
public ImageCapabilities getCapabilities(GraphicsConfiguration gc) {
if (isConfigValid(gc) && isAccelerationEnabled()) {
return new ImageCapabilities(true);
}
return new ImageCapabilities(false);
}
public static void main(final String[] args) {
final GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final VolatileImage vi =
gc.createCompatibleVolatileImage(SIZE, SIZE, TRANSLUCENT);
final BufferedImage bi = makeUnmanagedBI(gc, TRANSLUCENT);
final int expected = bi.getRGB(2, 2);
int attempt = 0;
BufferedImage snapshot;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
final Graphics2D g2d = vi.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.scale(2, 2);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.drawImage(bi, 0, 0, null);
g2d.dispose();
snapshot = vi.getSnapshot();
if (vi.contentsLost()) {
continue;
}
break;
}
final int actual = snapshot.getRGB(2, 2);
if (actual != expected) {
System.err.println("Actual: " + Integer.toHexString(actual));
System.err.println("Expected: " + Integer.toHexString(expected));
throw new RuntimeException("Test failed");
}
}
public static void main(String[] args) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
testGC(gc);
if (failed) {
throw new RuntimeException("Test FAILED. See err output for more");
}
System.out.println("Test PASSED.");
}
/**
* Need to override the default behavior because Pixmaps-based
* images are accelerated but not volatile.
*/
@Override
public ImageCapabilities getCapabilities(GraphicsConfiguration gc) {
if (isConfigValid(gc) && isAccelerationEnabled()) {
return new ImageCapabilities(true);
}
return new ImageCapabilities(false);
}
/**
* Constructor for the solitary "page setup" dialog
*/
public ServiceDialog(GraphicsConfiguration gc,
int x, int y,
PrintService ps,
DocFlavor flavor,
PrintRequestAttributeSet attributes,
Frame frame)
{
super(frame, getMsg("dialog.pstitle"), true, gc);
initPageDialog(x, y, ps, flavor, attributes);
}
public static void main(final String[] args) throws IOException {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsConfiguration gc = ge.getDefaultScreenDevice()
.getDefaultConfiguration();
AffineTransform at;
for (final int size : SIZES) {
for (final int scale : SCALES) {
final int sw = size * scale;
at = AffineTransform.getScaleInstance(sw, sw);
for (Shape clip : SHAPES) {
clip = at.createTransformedShape(clip);
for (Shape to : SHAPES) {
to = at.createTransformedShape(to);
// Prepare test images
VolatileImage vi = getVolatileImage(gc, size);
BufferedImage bi = getBufferedImage(sw);
// Prepare gold images
BufferedImage goldvi = getCompatibleImage(gc, size);
BufferedImage goldbi = getBufferedImage(sw);
draw(clip, to, vi, bi, scale);
draw(clip, to, goldvi, goldbi, scale);
validate(bi, goldbi);
}
}
}
}
}
public static void main(String[] args) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
VolatileImage vi = gc.createCompatibleVolatileImage(16, 16);
vi.validate(gc);
BufferedImage bi =
new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB);
int data[] = ((DataBufferInt)bi.getRaster().getDataBuffer()).getData();
data[0] = 0x0000007f;
data[1] = 0x0000007f;
data[2] = 0xff00007f;
data[3] = 0xff00007f;
Graphics2D g = vi.createGraphics();
g.setComposite(AlphaComposite.SrcOver.derive(0.999f));
g.drawImage(bi, 0, 0, null);
bi = vi.getSnapshot();
if (bi.getRGB(0, 0) != bi.getRGB(1, 1)) {
throw new RuntimeException("Test FAILED: color at 0x0 ="+
Integer.toHexString(bi.getRGB(0, 0))+" differs from 1x1 ="+
Integer.toHexString(bi.getRGB(1,1)));
}
System.out.println("Test PASSED.");
}
private static VolatileImage makeVI(final int type) {
final GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
return gc.createCompatibleVolatileImage(SIZE, SIZE, type);
}
/**
* Invokes the given Runnable on the OGL QueueFlusher thread with the
* "shared" OpenGL context (corresponding to the given
* GraphicsConfiguration object) made current. This method is typically
* used when the Runnable needs a current context to complete its
* operation, but does not require that the context be made current to
* a particular surface. For example, an application may call this
* method so that the given Runnable can query the OpenGL capabilities
* of the given GraphicsConfiguration, without making a context current
* to a dummy surface (or similar hacky techniques).
*
* In order to avoid deadlock, it is important that the given Runnable
* does not attempt to acquire the AWT lock, as that will be handled
* automatically as part of the <code>rq.flushAndInvokeNow()</code> step.
*
* @param config the GraphicsConfiguration object whose "shared"
* context will be made current during this operation; if this value is
* null or if OpenGL is not enabled for the GraphicsConfiguration, this
* method will return false
* @param r the action to be performed on the QFT; cannot be null
* @return true if the operation completed successfully, or false if
* there was any problem making the shared context current
*/
public static boolean
invokeWithOGLSharedContextCurrent(GraphicsConfiguration config,
Runnable r)
{
if (!(config instanceof OGLGraphicsConfig)) {
return false;
}
OGLRenderQueue rq = OGLRenderQueue.getInstance();
rq.lock();
try {
// make the "shared" context current for the given GraphicsConfig
OGLContext.setScratchSurface((OGLGraphicsConfig)config);
// invoke the given runnable on the QFT
rq.flushAndInvokeNow(r);
// invalidate the current context so that the next time we render
// with Java 2D, the context state will be completely revalidated
OGLContext.invalidateCurrentContext();
} finally {
rq.unlock();
}
return true;
}
public static void main(final String[] args) {
final GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final VolatileImage vi =
gc.createCompatibleVolatileImage(SIZE, SIZE, TRANSLUCENT);
final BufferedImage bi = makeUnmanagedBI(gc, TRANSLUCENT);
final int expected = bi.getRGB(2, 2);
int attempt = 0;
BufferedImage snapshot;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
final Graphics2D g2d = vi.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.scale(2, 2);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.drawImage(bi, 0, 0, null);
g2d.dispose();
snapshot = vi.getSnapshot();
if (vi.contentsLost()) {
continue;
}
break;
}
final int actual = snapshot.getRGB(2, 2);
if (actual != expected) {
System.err.println("Actual: " + Integer.toHexString(actual));
System.err.println("Expected: " + Integer.toHexString(expected));
throw new RuntimeException("Test failed");
}
}
public static Rectangle2D getFullScreenBounds() {
// NOTE! main monitor must be top left, otherwise, override x+y position
Rectangle2D result = new Rectangle2D.Double();
GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();
for (GraphicsDevice gd : localGE.getScreenDevices()) {
for (GraphicsConfiguration graphicsConfiguration : gd.getConfigurations()) {
Rectangle2D.union(result, graphicsConfiguration.getBounds(), result);
}
}
return result;
}
/**
* Need to override the default behavior because Pixmaps-based
* images are accelerated but not volatile.
*/
@Override
public ImageCapabilities getCapabilities(GraphicsConfiguration gc) {
if (isConfigValid(gc) && isAccelerationEnabled()) {
// accelerated but not volatile
return new ImageCapabilities(true);
}
// neither accelerated nor volatile
return new ImageCapabilities(false);
}
public static void main(final String[] args) {
final GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
final VolatileImage vi =
gc.createCompatibleVolatileImage(SIZE, SIZE, TRANSLUCENT);
final BufferedImage bi = makeUnmanagedBI(gc, TRANSLUCENT);
final int expected = bi.getRGB(2, 2);
int attempt = 0;
BufferedImage snapshot;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
final Graphics2D g2d = vi.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.scale(2, 2);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.drawImage(bi, 0, 0, null);
g2d.dispose();
snapshot = vi.getSnapshot();
if (vi.contentsLost()) {
continue;
}
break;
}
final int actual = snapshot.getRGB(2, 2);
if (actual != expected) {
System.err.println("Actual: " + Integer.toHexString(actual));
System.err.println("Expected: " + Integer.toHexString(expected));
throw new RuntimeException("Test failed");
}
}
private void calcImageBufferSize() {
GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
BufferedImage buff = config.createCompatibleImage(1, 1, Transparency.TRANSLUCENT);
Graphics2D g2 = buff.createGraphics();
g2.setFont(font);
LineMetrics lm = font.getLineMetrics(String.valueOf(icon), g2.getFontRenderContext());
iconWidth = g2.getFontMetrics().charWidth(icon.getChar());
iconHeight = (int) lm.getHeight();
iconBaseline = (int) (lm.getHeight() - lm.getLeading() - lm.getDescent());
g2.dispose();
}
private SunVolatileImage(Component comp,
GraphicsConfiguration graphicsConfig,
int width, int height, Object context,
ImageCapabilities caps)
{
this(comp, graphicsConfig,
width, height, context, Transparency.OPAQUE, caps, UNDEFINED);
}
private void runTest(Graphics g) {
int status = IMAGE_OK;
int count1 = 0;
do {
GraphicsConfiguration gc = getGraphicsConfiguration();
int count2 = 0;
while (vi == null || (status = vi.validate(gc)) != IMAGE_OK) {
if (++count2 > LOOP_THRESHOLD) {
System.err.println("Infinite loop detected: count2="+count2);
failed = true;
return;
}
if (vi == null || status == IMAGE_INCOMPATIBLE) {
if (vi != null) { vi.flush(); vi = null; }
vi = gc.createCompatibleVolatileImage(100, 100);
continue;
}
if (status == IMAGE_RESTORED) {
Graphics gg = vi.getGraphics();
gg.setColor(Color.green);
gg.fillRect(0, 0, vi.getWidth(), vi.getHeight());
break;
}
}
g.drawImage(vi, getInsets().left, getInsets().top, null);
if (++count1 > LOOP_THRESHOLD) {
System.err.println("Infinite loop detected: count1="+count1);
failed = true;
return;
}
} while (vi.contentsLost());
}
private static VolatileImage getVolatileImage(GraphicsConfiguration gc,
int size) {
VolatileImage vi = gc.createCompatibleVolatileImage(size, size);
Graphics2D g2d = vi.createGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(0, 0, size, size);
return vi;
}
/**
* Constructor for the solitary "page setup" dialog
*/
public ServiceDialog(GraphicsConfiguration gc,
int x, int y,
PrintService ps,
DocFlavor flavor,
PrintRequestAttributeSet attributes,
Frame frame)
{
super(frame, getMsg("dialog.pstitle"), true, gc);
initPageDialog(x, y, ps, flavor, attributes);
}
public static void main(String[] args) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
testGC(gc);
if (failed) {
throw new RuntimeException("Test FAILED. See err output for more");
}
System.out.println("Test PASSED.");
}