当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Drawing images onto AWT and initialising Graphics

问题描述:

I'll start off by telling you what Im trying to do if thats OK, as Im not certain the route Im struggling with is even the best way of achieving my ends.

I have a JFrame containing two JPanels. One contains a number of buttons (buttonPanel), the other is, initially, blank (displayPane). When buttons are pressed the stuff shown in displayPanel changes. The way this is working is each press of a button creates a new object that extends JPanel and then adds that to displayPane

So all the above is working fine and dandy (although I freely admit it may not be the best way of doing it) except for one particular case.

In this particular case I need to create a JLayeredPanel and then draw a clipped image on it. JLayeredPanel because I want to draw some stuff on top of it, clipped because I only want to show part of the area (which exact part is passed to the constructor).

Now, the problem Im having is this. The only way I know to draw a clipped image is through g=thingie.getGraphics(), g.setClip(Shape shape), g.drawImage(various). However, all of that relies on being able to get graphics. But because I am assembling the object first there is no graphics object associated with the JLayeredPane (because its not displayed) so getGraphics is returning null and g.setClip() is throwing a Null Pointer Exception.

Obviously I am doing this wrong somehow and somewhere. Any help would be appreciated, sorry if the question is confusing. I tried to include as much detail as possible and now I am a little concerned I've muddied the issue. I'll keep an eye on this and clarify if required.

网友答案:

Warning!: Wrong answer, see below the line

Why don't you just create a new Graphics object, paint on it and then use it with the update() method?

Graphics g = new Graphics();
g.drawStuff();
thingie.update(g);

This showd be correct

As stated on the comments the previous solution was wrong but it can be done with an Double buffer, create a buffered image and draw on it, then override the paint method of the jLayeredPane pane to draw the image.

    private void addStuff() {            
        BufferedImage bi =
            new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics bufferedGraphics = bi.getGraphics();
        //Paint stuff
        bufferedGraphics.drawLine(0, 0, 50, 50);
        javax.swing.JLayeredPane layered;
        layered = new JLayeredPane() {
            @Override
            public void paint(Graphics g) {
                g.drawImage(bi, 0, 0, null);
            }
        };        
        this.add(layered);        
        this.validate();
        this.repaint();
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: