Search code examples
javaswingjpaneljlistsprite-sheet

Adding some pictures to a BuffredImage then Save it


My general idea is to make a Sprite-Sheet-Maker I mean the program will:

  1. Collect more than one picture like "1.bmp" , "2.png" and "3.jpg"
  2. Create new BuffredImage variable and draw on it the 3 pictures (and draw the BuffredImage on a JPanel on the same time)
  3. Save the final picture "Final.png"

I'm thinking to make the First step and the Second one in one loop because i have a JList with the paths of all the pictures.

and to do that I used Java window Builder on eclipse, I made my form and I tried to test a simple code on the Panel.

Panel panel = new Panel(); //Work
panel.setBackground(Color.BLUE); //Work
BufferedImage img = new BufferedImage(5,5,5); //Work
Graphics g = null ; //Work
panel.paintComponents(g); //work
g.setColor(Color.BLACK); //ERROR---------------------ERROR
g.fillRect(0, 0, 50, 50);

The problem it's not only in that code but in all the idea so please any of your ideas could help me even a part of solution for a part of my project , so please comment with any idea you've got.


Solution

  •  g.setColor(Color.BLACK);//error
    

    Since

      Graphics g = null ;//null value, you are not create any obeject
    

    Upon null value we can't perform any operation.

    You have to override paintComponent method in JPanel class then you will receive Graphics object.

          JPanel panel = new JPanel() {
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.setColor(Color.BLUE);
                    g.fillRect(0, 0, 100, 100);
                }
            };
            frame.add(panel);//added to frame.
    

    See this link