Results 1 to 11 of 11
  1. #1
    SuperWoman's Avatar
    SuperWoman is offline Member
    Join Date
    Sep 2014
    Posts
    12
    Rep Power
    0

    Question Java2D -> ArrayList + Button click = drawing on JPanel

    Hello there,

    I am trying to do something that should be fairly simple, or so I'm told.
    I'm just starting to learn Java, btw.


    You're using Eclipse and you created a Java Swing Application window.
    You added an ArrayList of rectangles, a button to the left, and a custom JPanel to the right.

    Note that the arraylist is not defined in the button or custom jpanel class. The reason is that its defined by user input. You see, in this app (pdf imposition app) I wrote some code that calculates the best imposition on a sheet for a given pdf and the arraylist holds the position and dimensions for each pdf rectangle/shape.

    Now, you're the programmer...
    Here's here's the scenario you want to see happening.

    1-) The user click the impose button.
    2-) The custom JPanel clears itself of any previous drawings and draws the rectangles as seen in the ArrayList of rectangles.

    So you have three separate things to contend with: an ArrayList of stuff to draw, a button to initiate the drawing, and a custom jpanel to draw on.

    How do you do this?

    Thanks,


    ps: On the internet, most code examples refer to painting that's controlled either at the class creation time or by mouse events inside the component (usually a jpanel) itself. I didn't find any examples where an external component, like a button, controls through its click event the drawing on another component that in turns draws stuff that is defined outside its own class data.

    ps2: I would donate a Starbucks card for someone showing me a working example. Smile | :)


    Java Code:
    import java.awt.*;
    import java.awt.EventQueue;
    import java.util.*;
    import javax.swing.*;
    
    import java.awt.BorderLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    
    
    public class Mainframe 
    {
    
    	private JFrame frame;
    	private ArrayList<PdfShape> PdfShapes;
    
    	private class PdfShape
    	{
    		private Rectangle rect;
    		private int xPos, yPos;		
    	}
    	
    	public static void main(String[] args)  { EventQueue.invokeLater(new Runnable() { public void run()  { try  { Mainframe window = new Mainframe(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }});}
    
    	public Mainframe() {initialize();}
    
    
    	private void initialize() 
    	{
    		
    		frame = new JFrame();
    		frame.setBounds(100, 100, 900, 600);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		JButton btnAdd = new JButton("Add");
    		btnAdd.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseClicked(MouseEvent arg0) 
    			{
    				DrawOnCanvas();
    			}
    		});
    		frame.getContentPane().add(btnAdd, BorderLayout.WEST);
    		
    		SheetCanvas canvas = new SheetCanvas();
    		canvas.setBackground(Color.WHITE);
    		frame.getContentPane().add(canvas,BorderLayout.CENTER);
    		
    	}
    	
    	private void DrawOnCanvas()
    	{
    		
    	}
    
    	public class SheetCanvas extends JPanel
    	{
    		public void paint(Graphics e)
    		{
    			super.paint(e);
    
    		}
    		
    	}
    }
    Last edited by SuperWoman; 09-02-2014 at 01:10 AM. Reason: Add the code

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    I suggest you try doing each part separately.

    1. First, create an ArrayList of some rectangles.
    2. Create a button with an actionListener and have it print something when you press it.
    How to Use Buttons, Check Boxes, and Radio Buttons (The JavaTutorials > Creating a GUI With JFC/Swing > Using Swing Components)
    3. Try and paint something in a JPanel by default without using any buttons).
    Lesson: Performing Custom Painting (The JavaTutorials > Creating a GUI With JFC/Swing)

    After you do all those and understand how they work, then you need to integrate them. Once you do that
    if you are having problems, the forum can help.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    SuperWoman's Avatar
    SuperWoman is offline Member
    Join Date
    Sep 2014
    Posts
    12
    Rep Power
    0

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Hi Jim,

    Thanks for your time. I've read your links and links of those links.
    It did not answer the question.

    Let's be clear: I'm not trying to figure out how to use a button. And I'm also not trying to figure out how to override the paint method of a component.

    I'm trying to figure out how to override the paint method of a custom jpanel from the click event of a button.


    Here's a screenshot of the app I'm writing...
    Java2D -&gt; ArrayList + Button click = drawing on JPanel-pdf-imposition-monster-early-.png

    As seen in the screenshot, working with event handlers to change the values of defined properties of other components is normal business.
    I also can overwrite the paint method of a component.
    How to do these things is well referenced in your links.

    What is apparently not documented is what I asked in my question: How to call the overridden paint method of another component?

    Thanks for letting me know,

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    How to call the overridden paint method of another component?
    The usual way to call a method is get a reference to an instance of the class and use it to call the method.

    Normal code doesn't call the paint() method. A request is made for the system to call it by calling the repaint() method.

    It would help others to understand what the code is supposed to do if it had some comments.
    Last edited by Norm; 09-02-2014 at 07:12 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    SuperWoman's Avatar
    SuperWoman is offline Member
    Join Date
    Sep 2014
    Posts
    12
    Rep Power
    0

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Hi Norm,

    Thank you for your time.
    Here's what I'm trying to do: Get a custom jpanel to paint some rectangles that are stuffed in an arraylist once the user clicks on a button.

    I know how to create an arraylist.
    I know how to work the click event of a button.
    I know how to create a custom jpanel.
    I know how to override the paint method of a component.

    But yeah, Norm, I have no idea and I've looking for days, on how to get a button to tell a jpanel to paint some stuff that's in an arraylist.

    Hope you have an idea! :)

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    how to get a button to tell a jpanel to paint some stuff that's in an arraylist.
    Pass info about what to draw (the arraylist??) to the object that has the paint method and call that object's repaint() method. When paint() is called, do the drawing.

    BTW You should use the paintComponent() method for Swing class objects, not paint().
    Last edited by Norm; 09-02-2014 at 07:50 PM.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    SuperWoman's Avatar
    SuperWoman is offline Member
    Join Date
    Sep 2014
    Posts
    12
    Rep Power
    0

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Hi Norm,

    "If you don't understand my response, don't ignore it, ask a question."
    Being new is hard on self esteem sometimes ...

    Okay, so thanks for the tip about painComponent(), I'll use that instead.

    Correct me if I'm wrong, but I can't access the repaint method of my custom jpanel from somewhere else than the custom jpanel?

    Say the user clicks on the button:

    Java Code:
    		btnAdd.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseClicked(MouseEvent arg0) 
    			{
    				DrawOnCanvas();
    			}
    		});
    My function DrawOnCanvas() doesn't have access to the custom jpanel.

    Java Code:
    	private void DrawOnCanvas()
    	{
    		//how do I access myCustomJPanel.paintComponent() from here?
    	}

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Change the location of the variable that holds the reference to the custom component to be at the class level instead of local to the initialize() method. Then any method in the class will be able to use it.

    You do not call the paintComponent() method. You call the repaint() method which will cause the JVM to call the paintComponent() method soon.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Quote Originally Posted by SuperWoman View Post
    My function DrawOnCanvas() doesn't have access to the custom jpanel.
    Then pass it one. In any event, the tutorials provided many examples of doing what you are trying to do.
    And if frame.repaint() is invoked then it will repaint all of its components.

    Regards,
    Jim
    Last edited by jim829; 09-02-2014 at 09:39 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    SuperWoman's Avatar
    SuperWoman is offline Member
    Join Date
    Sep 2014
    Posts
    12
    Rep Power
    0

    Lightbulb Re: Java2D -> ArrayList + Button click = drawing on JPanel

    Thank you Norm and everyone for helping a newbie. I took the time to learn more about OOP, variable scope, the super() method from YouTube and now in hindsight, thanks to your guidance I've solved my problem and it looks easy... in hindsight...

    Here's my code sample that solved what I was trying to do. Please let me know how you would improve it. Thank you guys.


    Java Code:
    package views;
    
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.util.ArrayList;
    import java.util.Iterator;
    
    import javax.swing.*;
    
    
    
    public class appMainWindow extends JFrame
    {
    	class PdfLocation
    	{
    		public double xPos;
    		public double yPos; 
    	}
    	
    	class DrawCanvas extends JPanel
    	{
    	      @Override
    	      public void paintComponent(Graphics g) 
    	      {
    	         super.paintComponent(g);
    	         for (PdfLocation p : PdfLocations)
    	         {
    	        	 g.drawRect((int)p.xPos, (int)p.yPos, 35, 20);
    	        	 repaint();
    	         }
    	      }
    	}
    	
    	public void AddRectangle()
    	{
    		PdfImagesCount++;
    		lblPdfcount.setText(Integer.toString(PdfImagesCount));
    		
    		PdfLocation rect = new PdfLocation();
    		
    		if (PdfLocations.isEmpty() == false)
    		{
    			PdfLocation spot = PdfLocations.get(PdfLocations.size() - 1);
    			rect.xPos = spot.xPos + 45;
    			rect.yPos = 10;
    		}	
    		else
    		{
    			rect.xPos = 10;
    			rect.yPos = 10;			
    		}
    		PdfLocations.add(rect);				
    	}
    
    	private JFrame frame;
    	public ArrayList<PdfLocation> PdfLocations = new  ArrayList<PdfLocation>();
    	public int PdfImagesCount = 0;
    
    	
    	public static final int CANVAS_HEIGHT = 700;
    	public static final int CANVAS_WIDTH = 1000;
    	
    	private DrawCanvas canvas;
    	private JLabel lblPdfcount;
    	
    	public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { appMainWindow window = new appMainWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
    
    	public appMainWindow() 
    	{ 
    		
    		// Set up a custom drawing JPanel
    	    canvas = new DrawCanvas();
    	    canvas.setBackground(Color.WHITE);
    	    canvas.setBounds(150, 25, CANVAS_WIDTH, CANVAS_HEIGHT);
    		initialize(); 
    	}
    
    	private void initialize() 
    	{
    		frame = new JFrame();
    		frame.setBounds(100, 100, 1280, 850);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(null);
    		
    		JButton btnAddARectangle = new JButton("Add a rectangle");
    		btnAddARectangle.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) 
    			{
    				AddRectangle();
    				repaint();
    			}
    		});
    		btnAddARectangle.setBounds(0, 6, 151, 29);
    		frame.getContentPane().add(btnAddARectangle);
    		
    		
    		frame.getContentPane().add(canvas);
    		
    		lblPdfcount = new JLabel("PdfCount");
    		lblPdfcount.setBounds(10, 43, 61, 16);
    		frame.getContentPane().add(lblPdfcount);
    	}
    
    }

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Java2D -> ArrayList + Button click = drawing on JPanel

    You should NOT call repaint() from inside the paintComponent() method. That will cause an infinite loop: each call to repaint will cause a call to paintComponent() which will call repaint which ...

    Each statement should be on a separate line. Otherwise they can be hidden and hard to see.
    Last edited by Norm; 09-09-2014 at 06:49 PM.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. practicing java2D drawing, need guidance.
    By trey in forum AWT / Swing
    Replies: 3
    Last Post: 03-23-2012, 01:47 AM
  2. Replies: 8
    Last Post: 02-23-2012, 06:08 PM
  3. Replies: 3
    Last Post: 02-23-2012, 05:50 PM
  4. Replies: 4
    Last Post: 09-25-2010, 09:03 AM
  5. Button click for drawing geometry shape
    By nnur in forum AWT / Swing
    Replies: 5
    Last Post: 05-15-2010, 07:48 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
  •