Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在透明窗口上绘制图像?_Java_Swing_Graphics2d_Bufferstrategy - Fatal编程技术网

Java 如何在透明窗口上绘制图像?

Java 如何在透明窗口上绘制图像?,java,swing,graphics2d,bufferstrategy,Java,Swing,Graphics2d,Bufferstrategy,我正在尝试在JFrame上使用Graphics2D绘制图像。 但此代码仅显示空白背景。 怎么做? Java版本:SE-1.6 IDE:Eclipse 我的代码如下所示: import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferStrategy; import java.awt.geom.Line2D; import java.uti

我正在尝试在JFrame上使用Graphics2D绘制图像。
但此代码仅显示空白背景。
怎么做?

Java版本:SE-1.6
IDE:Eclipse

我的代码如下所示:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.geom.Line2D;
import java.util.TimerTask;

import javax.swing.JFrame;

public class GraphicTest extends JFrame{

    public static void main(String[] args) {
        GraphicTest gt = new GraphicTest();
        gt.start();
    }

    JFrame frame;
    BufferStrategy strategy;

    GraphicTest(){
        int width = 320;
        int height = 240;

        this.frame = new JFrame("test");

        this.frame.setSize(width, height);
        this.frame.setLocationRelativeTo(null);
        this.frame.setLocation(576, 336);
        this.frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        this.frame.setUndecorated(true);
        this.frame.setBackground(new Color(0, 0, 0, 50));

        this.frame.setVisible(true);

        this.frame.setIgnoreRepaint(true);
        this.frame.createBufferStrategy(2);
        this.strategy = this.frame.getBufferStrategy();
    }

    public void onExit(){
        System.exit(0);
    }

    void start(){
        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new RenderTask(), 0, 16);
    }

    class RenderTask extends TimerTask{
        int count = 0;

        @Override
        public void run() {
            GraphicTest.this.render();
        }
    }

    void render() {
        // Some moving images
        Graphics2D g2 = (Graphics2D)this.strategy.getDrawGraphics();
        g2.setStroke(new BasicStroke(5.0f));
        Line2D line = new Line2D.Double(20, 40, 120, 140);
        g2.draw(line);
        this.strategy.show();
    }
}
感谢您提供的任何帮助。

  • BufferStrategy
    通常与重量较重的组件关联,这些组件没有任何透明度概念
  • Java 6不“正式”支持透明和半透明(每alpha像素)
  • 使窗口半透明会影响其他任何绘制到它的效果…这非常烦人,无论您使用的是Java6还是Java7
秘密在于首先使窗口透明,然后覆盖具有特殊“半透明”绘画效果的透明组件

在Java6(我想更新10)下,出现了一个名为
awutilities
的私有API,它提供了使窗口透明或半透明的能力,下面的示例就是基于该API的

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TransparentWindowAnimation {

    public static void main(String[] args) {
        new TransparentWindowAnimation();
    }

    public TransparentWindowAnimation() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                if (supportsPerAlphaPixel()) {
                    try {
                        JFrame frame = new JFrame("Testing");
                        frame.setUndecorated(true);
                        setOpaque(frame, false);
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        frame.setLayout(new BorderLayout());
                        frame.add(new PaintPane());
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    }
                } else {
                    System.err.println("Per pixel alphering is not supported");
                }
            }
        });
    }

    public static boolean supportsPerAlphaPixel() {
        boolean support = false;
        try {
            Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
            support = true;
        } catch (Exception exp) {
        }
        return support;
    }

    public static void setOpaque(Window window, boolean opaque) throws Exception {
        try {
            Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
            if (awtUtilsClass != null) {
                Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
                method.invoke(null, window, opaque);
            }
        } catch (Exception exp) {
            throw new Exception("Window opacity not supported");
        }
    }

    public class PaintPane extends JPanel {

        private BufferedImage img;

        private int xPos, yPos = 100;
        private int xDelta = 0;
        private int yDelta = 0;

        public PaintPane() {
            while (xDelta == 0) {
                xDelta = (int)((Math.random() * 8)) - 4;
            }
            while (yDelta == 0) {
                yDelta = (int)((Math.random() * 8)) - 4;
            }
            setOpaque(false);
            try {
                img = ImageIO.read(new File("AngryBird.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    xPos += xDelta;
                    yPos += yDelta;
                    if (xPos - (img.getWidth() / 2) <= 0) {
                        xPos = img.getWidth() / 2;
                        xDelta *= -1;
                    }
                    if (xPos + (img.getWidth() / 2) >= getWidth()) {
                        xPos = getWidth() - (img.getWidth() / 2);
                        xDelta *= -1;
                    }
                    if (yPos - (img.getHeight() / 2) <= 0) {
                        yPos = img.getHeight() / 2;
                        yDelta *= -1;
                    }
                    if (yPos + (img.getHeight() / 2) >= getHeight()) {
                        yPos = getHeight() - (img.getHeight() / 2);
                        yDelta *= -1;
                    }
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(new Color(128, 128, 128, 128));
            g2d.fillRect(0, 0, getWidth(), getHeight());
            int x = xPos - (img.getWidth() / 2);
            int y = yPos - (img.getHeight()/ 2);
            g2d.drawImage(img, x, y, this);
            g2d.dispose();
        }
    }

}

导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Window;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.image.buffereImage;
导入java.io.File;
导入java.io.IOException;
导入java.lang.reflect.Method;
导入javax.imageio.imageio;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.Timer;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
公共类透明动画{
公共静态void main(字符串[]args){
新的透明动画();
}
公开透明{
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
}
if(supportsPerAlphaPixel()){
试一试{
JFrame=新JFrame(“测试”);
框架。设置未装饰(真实);
set不透明(框,假);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(新的BorderLayout());
frame.add(新的PaintPane());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}捕获(异常扩展){
exp.printStackTrace();
}
}否则{
System.err.println(“不支持每像素alphering”);
}
}
});
}
公共静态布尔支持speralphapixel(){
布尔支持=false;
试一试{
Class awtUtilsClass=Class.forName(“com.sun.awt.AWTUtilities”);
支持=正确;
}捕获(异常扩展){
}
回归支持;
}
公共静态void setOpaque(窗口,布尔不透明)引发异常{
试一试{
Class awtUtilsClass=Class.forName(“com.sun.awt.AWTUtilities”);
如果(awtUtilsClass!=null){
方法Method=awtUtilsClass.getMethod(“setWindow不透明”,Window.class,boolean.class);
调用(null、window、不透明);
}
}捕获(异常扩展){
抛出新异常(“不支持窗口不透明度”);
}
}
公共类PaintPane扩展了JPanel{
专用缓冲图像img;
私有int XPO,YPO=100;
私有int xDelta=0;
私有int yDelta=0;
公共窗格玻璃(){
而(xDelta==0){
xDelta=(int)((Math.random()*8))-4;
}
而(yDelta==0){
yDelta=(int)((Math.random()*8))-4;
}
设置不透明(假);
试一试{
img=ImageIO.read(新文件(“AngryBird.png”);
}捕获(IOEX异常){
例如printStackTrace();
}
计时器计时器=新计时器(40,新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
xPos+=xDelta;
yPos+=yDelta;
如果(xPos-(img.getWidth()/2)=getWidth()){
xPos=getWidth()-(img.getWidth()/2);
xDelta*=-1;
}
如果(yPos-(img.getHeight()/2)=getHeight()){
yPos=getHeight()-(img.getHeight()/2);
yDelta*=-1;
}
重新油漆();
}
});
timer.start();
}
@凌驾
公共维度getPreferredSize(){
返回新维度(200200);
}
@凌驾
受保护组件(图形g){
超级组件(g);
Graphics2D g2d=(Graphics2D)g.create();
设置颜色(新颜色(128、128、128、128));
fillRect(0,0,getWidth(),getHeight());
int x=xPos-(img.getWidth()/2);
int y=yPos-(img.getHeight()/2);
g2d.drawImage(img,x,y,this);
g2d.dispose();
}
}
}
可以看到另一种方式。这可以通过以下方式实现:

frame.setBackground(new Color(0, 0, 0, 0));
....
setOpaque(false);  //for the JPanel being painted on.


我认为您应该理解,
缓冲策略通常与没有透明度概念的重型组件相关……请通过以下链接