drawing your own buffered image on frame

我怕爱的太早我们不能终老 提交于 2019-11-29 15:54:52

As far as I understand what you are trying to achieve (which is 'not a lot'), this might give you some tips. The construction of the frame and image still seems untidy to me, but have a look over this.

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.*;

public class TestImageDraw {

    public static JFrame frame;
    BufferedImage img;
    public static int WIDTH = 800;
    public static int HEIGHT = 600;

    public TestImageDraw() {
    }

    public static void main(String[] a){

        TestImageDraw t=new TestImageDraw();

        frame = new JFrame("WINDOW");
        frame.setVisible(true);

        t.start();
        frame.add(new JLabel(new ImageIcon(t.getImage())));

        frame.pack();
//      frame.setSize(WIDTH, HEIGHT);
        // Better to DISPOSE than EXIT
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public Image getImage() {
        return img;
    }

    public void start(){

        img = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
        int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
        boolean running=true;
        while(running){
            BufferStrategy bs=frame.getBufferStrategy();
            if(bs==null){
                frame.createBufferStrategy(4);
                return;
            }
            for (int i = 0; i < WIDTH * HEIGHT; i++)
                pixels[i] = 0;

            Graphics g= bs.getDrawGraphics();
            g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
            g.dispose();
            bs.show();

        }
    }
}

General Tips

  • Please use a consistent and logical indent for code blocks.
  • Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use it consistently.
  • Give test classes a meaningful name e.g. TestImageDraw.
  • Create and update Swing GUIs on the EDT.
  • Don't mix Swing & AWT components without good reason.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!