Reputation: 817
So I've tried to write some pixels using MemoryImageSource and display it in a frame. Here's the code:
public class ImageDraw extends JPanel {
Image img;
public void ImageDraw(){
//super();
int w=600;
int h=400;
int pixels[] = new int[w*h];
int i=0;
for(i=0;i<w*h;i++){
//pixels[i++]=0;
pixels[i]=255;
}
img = createImage(new MemoryImageSource(w,h,pixels,0,w));
}
public void paint(Graphics g){
g.drawImage(img, 0, 0, this);
}
}
and the main code
public class FuncTest {
public static void main(String[] args) {
JFrame frame = new JFrame("Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
ImageDraw pan = new ImageDraw();
frame.getContentPane().add(pan);
frame.setVisible(true);
}
}
It just displays an empty frame. Why? My aim is to learn how to draw pixel by pixel, so this is only a test image I was drawing to see whether it works.
Thanks.
Upvotes: 1
Views: 232
Reputation: 39217
There are two issues with your code. First
public void ImageDraw() { ... }
is a method and not the constructor. The method is not called in your code at all. Change this line to
public ImageDraw() { ... }
without the void
to make it the default constructor.
Second you need to set the alpha-value of your pixel data:
pixels[i] = 255 + 0xFF000000;
And two more points:
paint(...)
but paintComponent(...)
instead. JFrame
but override the component's method getPreferredSize()
and use frame.pack()
.Upvotes: 5