Results 1 to 2 of 2
  1. #1
    AvivC is offline Member
    Join Date
    Dec 2013
    Posts
    26
    Rep Power
    0

    Default Drawing to a JPanel-type class, from a different class.

    Hello everyone, now to this forum :)

    I'm fairly new to 2D graphics in Java.
    I learned how to draw simple shapes on a JPanel, using the paintComponent method.

    Now I'm trying to do the same thing, except the drawing should be done from an exterior class, to the class that extends JPanel.

    I tried something that I believe should work, but it doesn't. Could you explain to me the standard way to do such a thing?

    Here is my attempt:

    Class Main:

    Java Code:
    package m;
    
    import java.util.*;
    import java.awt.*;
    import java.awt.Event.*;
    import javax.swing.*;
    
    public class Main extends JFrame {
    
    	public static void main(String[] args) {
    
    		Main m = new Main();
    		
    	}
    	
    	public Main(){
    		
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		setTitle("Bla");
    		setSize(500,500);
    		Surface s = new Surface();
    		add(s);
    		setVisible(true);
    		
    	}
    
    }
    Class Surface:

    Java Code:
    package m;
    
    import java.util.*;
    import java.awt.*;
    import java.awt.Event.*;
    import javax.swing.*;
    
    public class Surface extends JPanel {
    
    	public void paintComponent(Graphics g){
    		
    		super.paintComponent(g);
    		
    		DrawRect d = new DrawRect(this);
    		d.draw();
    		
    	}
    	
    }
    Class DrawRect:

    Java Code:
    package m;
    
    import java.util.*;
    import java.awt.*;
    import java.awt.Event.*;
    import javax.swing.*;
    
    public class DrawRect {
    
    	Surface surface;
    	Graphics g;
    	
    	public DrawRect(Surface surface){
    		this.surface = surface;
    		g = surface.getGraphics();
    	}
    	
        public void draw(){
        g.fillRect(20,20,100,50); // (this won't work).
        }
    
    }
    Thanks a lot :)

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default Re: Drawing to a JPanel-type class, from a different class.

    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 3
    Last Post: 12-08-2013, 09:28 PM
  2. JTextField on JPanel-class within JFrame-class
    By floris in forum AWT / Swing
    Replies: 5
    Last Post: 06-25-2012, 12:54 PM
  3. Replies: 3
    Last Post: 01-26-2012, 11:20 PM
  4. Replies: 0
    Last Post: 12-07-2011, 11:55 AM
  5. Replies: 2
    Last Post: 10-17-2011, 08:04 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •