Hi folks. I'm new here so appologies if I'm not posting in the correct place. Here's my issue. I want to paint independent graphics on the same JPanel. I thought that I could create a method that paints my image(s) then call this in the constructor, but not sure what the arguments for the constructor should be. Example code below:

package myPaCKAGE;

import java.awt.Color;
import java.awt.Graphics;

public class image
{

    private int width, height;
    private Object square;

    public Picture(int width, int height)
    {
        this.width = width;
        this.height = height;
        this.square();
    }
   
    }
    public void square(Graphics g)
    {
        g.drawRect(10, 10,10, 10);
        g.setColor(Color.red);
    }     
}

Problem lies with the line:

this.square();

as I'm not passing arguments to the method. What do I need to tell the constructor what the argument is in relation to the Graphics method?

Thanks in advance.

Jazzer

Member Avatar for ztini

You'll want to create a class that extends JPanel and add a helper method to add shapes as you need them. You'll add this JPanel to your JFrame, so basically something like this:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Frame extends JFrame {
    
	private static final long serialVersionUID = 1L;

	public Frame() {
    	
		ShapePanel panel = new ShapePanel();
		panel.addRectangle(50, 50, 100, 100);
		panel.addRectangle(150, 150, 50, 50);
		panel.addRectangle(200, 75, 75, 75);
    	
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setMinimumSize(new Dimension(500, 500));
		setLocation(new Point(50, 50));
		getContentPane().add(panel, BorderLayout.CENTER);
		pack();
	}

	class ShapePanel extends JPanel {
    	
		private static final long serialVersionUID = 1L;
		private List<Shape> shapes = new ArrayList<Shape>();
        
		public ShapePanel() {
			super();
		}
        
		public void addRectangle(int x, int y, int w, int h) { 
			shapes.add(new Rectangle2D.Float(x, y, w, h));
		}
        
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			Graphics2D g2 = (Graphics2D) g;
			for (Shape shape : shapes)
				g2.draw(shape);
		} 
	}
    
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Frame().setVisible(true);
			}
		});
	}
}

There are lots of tutorials on 2D painting in Java. I personally like Oracle's guide: http://docs.oracle.com/javase/tutorial/2d/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.