Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Cool Basic Q: passing to drawRect() in an applet

    so i feel like this is just missing something SLIGHTlY it will run in appletviewer, the 4 question boxes work and recieve the user defined values, but im not understanding something with passing them to the drawrect. i know thats where im going wrong, because when i remove this:

    g.drawRect ( x, y, width, height );

    and put in:

    g.drawRect ( 15, 15, 200, 25 );

    i get a rectangle! but obivously not the size or location the user has defined. what little thing am i missing here?

    Java Code:
    //exercise 23.9 DrawRectApplet.java
    //Write an applet that allows the user to input values for the arguments
    //required by method drawRect, then draws a rectangle using the four input values.
    
    import java.awt.Graphics;
    import javax.swing.JApplet;
    import javax.swing.JOptionPane;
    
    public class DrawRectApplet extends JApplet
    {
    	private int x;      // x axis
    	private int y;      // y axis
    	private int width;  //width of rect
    	private int height; //height of rect
    	
    	// initialize applet by obtaining values from user
    	public void init()
    	{
    		// obtain x/y axis start values from user
    		String firstNumber = JOptionPane.showInputDialog (
    			"Enter the horizontal start location of the Rectangle" );
    		
    		String secondNumber = JOptionPane.showInputDialog (
    			"Enter the vertical start location of the Rectangle" );
    			
    		// obtain size of rectangle from user
    		String thirdNumber = JOptionPane.showInputDialog (
    			"Enter the desired width of the Rectangle" );
    			
    		String fourthNumber = JOptionPane.showInputDialog (
    			"Enter the desired height of the Rectangle" );
    		
    		//convert numbers from String to int
    		int x = Integer.parseInt ( firstNumber );
    		int y = Integer.parseInt ( secondNumber );
    		int width = Integer.parseInt ( thirdNumber );
    		int height = Integer.parseInt ( fourthNumber ); 
    	
    	} // end method init()
    	
    	public void paint ( Graphics g )
    	{
    		super.paint ( g ); // call superclass version of method paint
    		
    		// draw desired rectangle
    		g.drawRect ( x, y, width, height );
    	} // end method drawRect
    }// end class DrawRectApplet
    i've got to be close right?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Don't paint directly in the JApplet's paint method itself but rather in a JPanel's paintComponent method, and then add the JPanel into the JApplet's contentPane. You'll likely want to call repaint() on the JPanel after changing x, y, width, and height.

  3. #3
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    this is only my second day learning about paint, Graphics g drawRect etc, any background on whats doing what?

    like in:
    public void paint ( Graphics g )

    what does Graphics g mean/do?

    super.paint ( g );
    i realize this is calling to the superclass, but again, what does (g) mean?

    do i even need the "paint" method? or do i just need to somehow create a drawRect method?

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    this is only my second day learning about paint, Graphics g drawRect etc, any background on whats doing what?

    g is a graphics context: a toolbox that contains methods that paintComponent() can call do do actual painting (draw rectangles, print text etc). This toolbox is also useful for the superclass paintComponent() which may have code for "filling in" the component if it is supposed to be opaque.

    There is discussion of this in the A Closer Look at the Painting Mechanism section of Oracle's Tutorial. That page - and the whole section it is part of - gives a detailed example of the painting process. It might be more than you need at the moment, but it is there if you want.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    The Graphics object is a tool that is used to render the image. It is not stable and thus the one that is passed into the paintComponent should be the one used. But again, draw in the paintComponent method of a JPanel, not in the paint method of the JApplet.

    For details on painting in Swing and AWT, please check out this article: Painting in AWT and Swing

  6. #6
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    so something like:
    Java Code:
    public void paintComponent ( Graphics g )
    	{
    		super.paintComponent ( g ); // call superclass
    		
    		// draw desired rectangle
    		g.drawRect ( x, y, width, height );
    instead of:
    Java Code:
    public void paint ( Graphics g )
    	{
    		super.paint ( g ); // call superclass version of method paint
    		
    		// draw desired rectangle
    		g.drawRect ( x, y, width, height );
    why if as currently constituted in my first post, if i remove the x,y,width,height variables, and insert numbers, does it work?

  7. #7
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    and im assuming the same use of code for when i will need to use drawOval, next?

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    It works because the data is there when the applet starts up. You are changing the data after start up and need to call repaint.

  9. #9
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    so is the change in code in my post above correct?

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  11. #11
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    maybe its just late in the day or something, but im not understanding what your saying by calling repaint()

    again, this is all new to me as of yesterday. so i apologize.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You shouldn't call paint or paintComponent directly, but the question is, when you change the class's data, the x, y, width and height values, how does the GUI know that it should repaint itself to display the changes? The answer is to call repaint on the component that's doing the painting. So if it is a JPanel, you call repaint() on the JPanel object.

  13. #13
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    i dont know why this is not making any sense to me. as much as i don't want you to give me the answer, can you just show me the structure of how the code should look for that part?

  14. #14
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    if you look here http://www.timlin.net/csm/cis254/Chapter23.pdf on pages 38-39 (fig23.9) that is what im supposed to use as a "guide" for what im building. however, it seems from reading the links you guys gave me im getting way over my head with some of the details you guys posted.....

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    This is code is similar to your program, but different in that it uses a MouseAdapter (MouseListener and MouseMotionListener combined) to set x, y and width and height. The key is to set these variables and then call repaint() on the JPanel that does the drawing. Since I'm drawing in a JPanel, the code for the JApplet itself is very simple -- it simply initializes the applet and adds the drawing JPanel to the JApplet's contentPane and nothing more.

    Since I'm calling repaint from inside of the DrawingPanel class, I call it on the current instance of DrawingPanel, or "this". But since it is being done from inside of a private inner class, I must specify that it's the DrawingPanel "this" that I want, not the MouseAdapter "this", and I do this by using DrawingPanel.this.repaint().


    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    
    public class RectangleInApplet extends JApplet {
       private static final long serialVersionUID = 1L;
    
       public void init() {
          try {  // create our JApplet on the EDT per Java recommendations
             javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                   createGUI();
                }
             });
          } catch (Exception e) {
             System.err.println("createGUI didn't successfully complete");
          }
       }
    
       private void createGUI() {
          // add the DrawingPanel JPanel to the JApplet's contentPane
          getContentPane().add(new DrawingPanel());
       }
    }
    
    class DrawingPanel extends JPanel {
       private static final long serialVersionUID = 1L;
       private static final Color RECT_COLOR = Color.blue.brighter();
       
       // variables we use to do drawing with
       private int x, y;
       private int width, height;
       
       public DrawingPanel() {
          // create mouse listener (mouse adapter actually)
          MyMouseAdapter myMAdapter = new MyMouseAdapter();
          addMouseListener(myMAdapter); // and add it to JPanel as MouseListener
          addMouseMotionListener(myMAdapter);  // and as MouseMotionListener
       }
       
       // draw in the JPanel's paintComponent method
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          if (width != 0 && height != 0) {
             g.setColor(RECT_COLOR);
             g.drawRect(x, y, width, height);
          }
       }
       
       // acts as both a MouseListener and a MouseMotionListener
       private class MyMouseAdapter extends MouseAdapter {
          private Point p1 = null;
          
          @Override
          public void mousePressed(MouseEvent e) {
             p1 = e.getPoint();
          }
          
          @Override
          public void mouseDragged(MouseEvent e) {
             Point p2 = e.getPoint();
             
             // use p1 and p2 to set x, y, width and height
             x = Math.min(p1.x, p2.x);
             y = Math.min(p1.y, p2.y);
             width = Math.abs(p1.x - p2.x);
             height = Math.abs(p1.y - p2.y);
             
             // now call repaint on the DrawingPanel JPanel
             // since "this" in the inner class refers to the MyMouseAdapter instance
             // we must explicitly call DrawingPanel.this to get the instance of DrawingPanel.
             DrawingPanel.this.repaint();
          }
       }
    }

  16. #16
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    anytime i try to implement the changes i just get numerous compile errors, i don't understand how i can be so far off on something appearing so simple.

    i assume i use this portion of what you showed?
    Java Code:
    @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
    and what i had of:
    Java Code:
    g.drawRect ( x, y, width, height);
    and then after that method add?:
    Java Code:
    public void DrawingPanel()
    	{
    		DrawingPanel.this.repaint();
        }
    normally i don't need stuff spelled out so badly, but this just seems really odd to me. its totally different than everything i just read in my book this chapter. feel free to just lay it out for me a guess on this one if you would. trying to pretend i understood the info you have given me, i modified my previous code to this: but not its error's everywhere.

    Java Code:
    //exercise 23.9 DrawRectApplet.java
    //Write an applet that allows the user to input values for the arguments
    //required by method drawRect, then draws a rectangle using the four input values.
    
    import java.awt.Graphics;
    import javax.swing.JApplet;
    import javax.swing.JOptionPane;
    
    public class DrawRectApplet extends JApplet
    {
    	private int x;      // x axis
    	private int y;      // y axis
    	private int width;  //width of rect
    	private int height; //height of rect
    	
    	// initialize applet by obtaining values from user
    	public void init()
    	{
    		// obtain x/y axis start values from user
    		String firstNumber = JOptionPane.showInputDialog (
    			"Enter the horizontal start location of the Rectangle" );
    		
    		String secondNumber = JOptionPane.showInputDialog (
    			"Enter the vertical start location of the Rectangle" );
    			
    		// obtain size of rectangle from user
    		String thirdNumber = JOptionPane.showInputDialog (
    			"Enter the desired width of the Rectangle" );
    			
    		String fourthNumber = JOptionPane.showInputDialog (
    			"Enter the desired height of the Rectangle" );
    		
    		//convert numbers from String to int
    		int x = Integer.parseInt ( firstNumber );
    		int y = Integer.parseInt ( secondNumber );
    		int width = Integer.parseInt ( thirdNumber );
    		int height = Integer.parseInt ( fourthNumber ); 
    	
    	} // end method init()
    	
    	@Override 
    	public void paintComponent ( Graphics g )
    	{
    		super.paintComponent( g ); // call superclass version of method paint
    		
    		// draw desired rectangle
    		g.drawRect ( x, y, width, height );
    	
    	} // end method paint
    	
    	public void DrawingPanel()
    	{
    		DrawingPanel.this.repaint();
        }
    }// end class DrawRectApplet

  17. #17
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    the latest, i have tried this and it compiles, but still doesn't draw the rectangle.

    Java Code:
    //exercise 23.9 DrawRectApplet.java
    //Write an applet that allows the user to input values for the arguments
    //required by method drawRect, then draws a rectangle using the four input values.
    
    import java.awt.Graphics;
    import javax.swing.JApplet;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    public class DrawRectApplet extends JApplet
    {
    	private int x;      // x axis
    	private int y;      // y axis
    	private int width;  //width of rect
    	private int height; //height of rect
    	
    	// initialize applet by obtaining values from user
    	public void init()
    	{
    		// obtain x/y axis start values from user
    		String firstNumber = JOptionPane.showInputDialog (
    			"Enter the horizontal start location of the Rectangle" );
    		
    		String secondNumber = JOptionPane.showInputDialog (
    			"Enter the vertical start location of the Rectangle" );
    			
    		// obtain size of rectangle from user
    		String thirdNumber = JOptionPane.showInputDialog (
    			"Enter the desired width of the Rectangle" );
    			
    		String fourthNumber = JOptionPane.showInputDialog (
    			"Enter the desired height of the Rectangle" );
    		
    		//convert numbers from String to int
    		int x = Integer.parseInt ( firstNumber );
    		int y = Integer.parseInt ( secondNumber );
    		int width = Integer.parseInt ( thirdNumber );
    		int height = Integer.parseInt ( fourthNumber ); 
    	
    	} // end method init()
    	
    	private class DrawRectPanel extends JPanel
    	{
    		public void paintComponent ( Graphics g )
    		{
    			super.paintComponent ( g );
    			
    			g.drawRect ( x, y, width, height );
    			
    			DrawRectPanel.this.repaint ();
    		}
    	}
    	
    }// end class DrawRectApplet

  18. #18
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    Quote Originally Posted by hayden06f4i View Post
    if you look here http://www.timlin.net/csm/cis254/Chapter23.pdf on pages 38-39 (fig23.9) that is what im supposed to use as a "guide" for what im building. however, it seems from reading the links you guys gave me im getting way over my head with some of the details you guys posted.....
    i keep going back to this example that i am working off from. "paint" is all that we have been taught so far, so it seems like that is what im supposed to use.

    and you mentioned that the reason why when i just input numbers in the drawRect () instead of variables, that it works, is because it knows them in advance? well if thats the case, then why in that example it is able to access and display the sum, using g.drawString? under paint (g)?

    sorry for all these questions, i gotta learn somehow. hopefully you can tell these are genuine, and not lazy questions, i always scour google until i here back from you great guys!

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    1) you would never call repaint from inside of paint or paintComponent. If the JVM weren't smart, this would only cause an infinite loop.
    2) You instead call it after you change data.
    3) You're shadowing your data by re-declaring x, y, width, and height in the init method. Declare these variables in the class (as you're doing), but don't re-declare them since the variables declared in the method will only be visible in the method and no where else. This is probably your major problem.

  20. #20
    hayden06f4i is offline Senior Member
    Join Date
    Oct 2010
    Posts
    119
    Rep Power
    0

    Default

    a slight breakthrough, or at least realizing something.....somehow the correct int values are not being passed, because i went back to paint (g), and added a line in the public void paint ( Graphics g ) stating:
    g.drawRect ( x,y,width,height); (as i had before)
    g.drawString ( "The Rectangle is " + x + y + width + height, 50, 50 ); (added this)

    and when i ran the program i get this:

    The Rectangle is 0000

    also noticed a 1 pixel dot in the 0,0 location, meaning its drawing a rectangle alright, a 1 pixel rectangle at location 0,0 because all the values being passed are zeroes...is there a problem with my conversion somehow?

Page 1 of 2 12 LastLast

Similar Threads

  1. Basic Java applet error, cant figure it out!
    By alacn in forum Java Applets
    Replies: 3
    Last Post: 08-03-2010, 06:25 PM
  2. Random drawRect
    By Wallsurfer in forum New To Java
    Replies: 5
    Last Post: 03-10-2009, 09:20 AM
  3. passing value from jsp to applet
    By bhupendrabjain in forum Java Applets
    Replies: 4
    Last Post: 10-07-2008, 01:55 PM
  4. Basic Applet
    By jkswebsite in forum Java Applets
    Replies: 4
    Last Post: 01-13-2008, 09:14 PM
  5. Basic graphics applet
    By Godzilla in forum New To Java
    Replies: 3
    Last Post: 08-08-2007, 09:50 AM

Posting Permissions

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