Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: how to use graphics g

  1. #1
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default how to use graphics g

    when i make a

    public void paint(Graphics g){} in this program, it wouldn't do anything. But when I put it at the method mouseDrag, it would draw. But it doesn't work if I want to make rectanges b/c it's just makes a the same rectangular shape.

    I don't know why it is. I could call paint() in mouseDrag and it'd work. but if I just want to use paint by itself my screen won't draw anything. It works if i make another program and uses it but not this program. =\

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Ellipse2D;
     
    import javax.swing.*;
     
     
     
     
    public class Etch_A_Sketch extends JFrame implements MouseListener, MouseMotionListener, ActionListener  // NOTE multiple interfaces
    {		
     
     
    	public void paintComponent(Graphics g)
    {  super.paintComponents(g);
    g.setColor(Color.blue);
    g.drawRect(10, 10, 80, 30);
    g.drawRoundRect(100, 10, 80, 30, 15, 15);
     
    int thickness = 4;
     
    for (int i = 0; i <= thickness; i++)
       g.draw3DRect(200 - i, 10 - i, 
          80 + 2 * i, 30 + 2 * i, true);
    for (int i = 0; i < thickness; i++)
       g.draw3DRect(200 - i, 50 - i, 
          80 + 2 * i, 30 + 2 * i, false);
     
    g.drawOval(10, 100, 80, 30);
    }
     
     
     
     
    	Point start, end;
    	boolean mouseUp = false;
    	JFrame window;
    	Container content;
    	int mouseX,mouseY,oldX,oldY;
    	JLabel coords;
    	JButton colorButton;
    	JComboBox shapes;
    	Color newColor;
    	JRadioButton button1, button2;
    	private boolean draw,oval, rectangle, line;
    	private boolean fill = false;
    	int x1,x2,y1,y2;
    	Graphics gg;
    	public Etch_A_Sketch()
    	{
    		JFrame window = new JFrame("Classic Etch a Sketch");
    		content = window.getContentPane();
    		content.setLayout( new FlowLayout() );
     
    		coords = new JLabel();
    		coords.setFont(new Font("TimesRoman", Font.ITALIC + Font.BOLD, 32));
     
    		JPanel dPanel = new JPanel();
     
    		//JCOLORCHOOSER
    		colorButton = new JButton("Choose a Color");
    	    colorButton.addActionListener(this);
    	    dPanel.add(colorButton);
     
    	    //JCOMBOBOX
    	    String[] shapesList = {"Default", "Line", "Rectange", "Oval" };
    	    shapes = new JComboBox(shapesList);
    	    dPanel.add(shapes);	    	
    	    shapes.addActionListener(this);
    	    shapes.setSelectedIndex(0);
     
    	    //JRADIO
    	     button1 = new JRadioButton("fill ");
    	     button2 = new JRadioButton("empty");
    	    ButtonGroup fillingsGroup = new ButtonGroup();
    	    fillingsGroup.add(button1);
    	    fillingsGroup.add(button2);
     
    	    button2.setSelected(true);
    		JPanel bPanel = new JPanel();
    		dPanel.add(button1);
    		dPanel.add(button2);
     
    		button1.addActionListener(this);
    		button2.addActionListener(this);
    		//LAYOUT
            content.add(bPanel, BorderLayout.SOUTH);
     
            content.add(dPanel, BorderLayout.SOUTH);
    		content.add( coords); 
    		content.addMouseListener(this);        // "this" is the class that impliments that listener
    		content.addMouseMotionListener(this);
    		// "this" is the class that impliments that listener
    		window.setSize(640,480);
     
    		window.setVisible(true);
    	}
     
     
    	// ..............................................................
    	// IMPLEMENTING MOUSELISTENER REQUIRES YOU TO WRITE (OVER-RIDE) THESE METHODS 
     
    	public void mouseClicked( MouseEvent me)
    	{
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse clicked at: " +
    			mouseX + "," + mouseY );
     
    	}
    	public void mousePressed( MouseEvent me)
    	{	
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse Pressed at: " +
    			mouseX + "," + mouseY );
    		//repaint();
     
    		x1= mouseX;
    		y1 =mouseY;
    		System.out.println("x1: " +x1 +"y1: " +y1);
    		}
     
    	public void mouseReleased( MouseEvent me)
    	{
     
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse released at: " +
    			mouseX + "," + mouseY );
    		//repaint();
    		x2 = mouseX;
    		y2 = mouseY;
    		System.out.println("x2: " +x2 +"y2: " +y2);
    	}
     
    	public void mouseExited( MouseEvent me)
    	{
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse exited at: " +
    			mouseX + "," + mouseY );
    		//repaint();
    	}
    	public void mouseEntered( MouseEvent me)
    	{
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse Entered at: " +
    			mouseX + "," + mouseY );
    		//repaint();
    	}
     
    	// ...............................................................
    	// IMPLEMENTING MOUSEMOTIONLISTENER REQUIRES YOU WRITE (OVER-RIDE) THESE METHODS 
     
    	public void mouseDragged( MouseEvent me)
    	{
     
     
    		mouseX = me.getX();
    		mouseY = me.getY();
     
     
     
    		if (oldX ==0 )
    		{
    			oldX=mouseX;
    			oldY=mouseY;
    			return;
    		}
    		gg = content.getGraphics();
    	    gg.setColor(Color.YELLOW);
     
     
    	    if(draw)
    		gg.drawLine( oldX,oldY, mouseX, mouseY );
     
    	    gg.drawRect(100,100,100,100);
     
    	    paint(gg);
    	    oldX = mouseX;
    		oldY = mouseY;
    		reportCoords("Mouse Dragged at: " +
    			mouseX + "," + mouseY );
    		//repaint();
     
     
     
     
     
     
    	}
     
    	  public void mouseMoved( MouseEvent me)
    	{
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse Moved at: " +
    			mouseX + "," + mouseY );
    		//repaint();
    	}
     
     
    public static int difference(int a, int b){
    	return Math.abs(a-b);
    }
    	// ..............................................................
     
     
    	public static void main( String[] args)
    	{
    		new Etch_A_Sketch();
     
     
    	}
    /////////////////////////////////////////////////////////////
    	  public void paint(Graphics g) {
     
    		    g.setColor(Color.RED);
     
     
    		    int width; int height;
     
    		    width = difference(x1,x2);
    		    height = difference(y1,y2);
     
     
    		    if(draw)
    			g.drawLine( oldX,oldY, mouseX, mouseY );
     
    			else if(oval){
     
    				g.drawOval(mouseX,mouseY, width,height);
    			if(fill)
    				g.fillOval(mouseX,mouseY, width,height);
    			}
    			else if(rectangle){
    				g.drawRect(mouseX,mouseY, width, height);
     
    			 if(fill)
    				g.fillRect(mouseX,mouseY, width,height);
     
    			}
    		  }
     
     
     
     
     
     
    	// a helper utility
    	private void reportCoords( String msg )
    	{
    		coords.setText( msg ); 
    	}
    	  public void actionPerformed(ActionEvent e) {
    		    // Args are parent component, title, initial color
     
    		     if(e.getSource()==colorButton){
     
    			  Color bgColor       = JColorChooser.showDialog(this,  "Choose a color to draw",    getBackground());
    		  		getBackground();
    		    if (bgColor != null)
    		      getContentPane().setBackground(bgColor);
     
     
     
    		    newColor = bgColor;
     
     
    		    System.out.println("bgColor:" +bgColor);
    		    System.out.println("newColor:" +newColor);    
     
    		  }
     
    		  int Selection;
    		  Selection = shapes.getSelectedIndex();
     
     
    		    if(Selection == 0){
    			  System.out.println("Default: at " + Selection); setFlagsFalse(); draw = true;
    		    }
    		    else    if(Selection == 1){
    				  System.out.println("Line: at " + Selection); setFlagsFalse(); draw = true; 
    			  }
    		    else if(Selection == 2){
    				  System.out.println("Rec: at " + Selection); setFlagsFalse(); rectangle = true; 
    			  }
    		    else if(Selection == 3){
    				  System.out.println("Oval: at " + Selection); setFlagsFalse(); oval = true; 
    			  }
     
     
     
    		    if(e.getSource() == button1){
    		    	System.out.println("button1" + fill);
    		    	fill = true;
    		    }
    		    else if(e.getSource() == button2){
    		    	System.out.println("button2" + fill);
    		    	fill = false;
     
    		    } 
     
     
     
     
     
    	  }
     
    	  void setFlagsFalse()
    	  {
    	  line = false;
    	  oval = false;
    	  rectangle = false;
    	  draw = false;
    	  }
     
    }//EOF
    the dragged
    public void mouseDragged( MouseEvent me)
    	{
     
     
    		mouseX = me.getX();
    		mouseY = me.getY();
     
     
     
    		if (oldX ==0 )
    		{
    			oldX=mouseX;
    			oldY=mouseY;
    			return;
    		}
    		gg = content.getGraphics();
    	    gg.setColor(Color.YELLOW);
     
     
    	    if(draw)
    		gg.drawLine( oldX,oldY, mouseX, mouseY );
     
    	    gg.drawRect(100,100,100,100);
     
    	    paint(gg);
    	    oldX = mouseX;
    		oldY = mouseY;
    		reportCoords("Mouse Dragged at: " +
    			mouseX + "," + mouseY );
    		//repaint();
     
     
     
     
     
     
    	}
    the paint()
      public void paint(Graphics g) {
     
    		    g.setColor(Color.RED);
     
     
    		    int width; int height;
     
    		    width = difference(x1,x2);
    		    height = difference(y1,y2);
     
     
    		    if(draw)
    			g.drawLine( oldX,oldY, mouseX, mouseY );
     
    			else if(oval){
     
    				g.drawOval(mouseX,mouseY, width,height);
    			if(fill)
    				g.fillOval(mouseX,mouseY, width,height);
    			}
    			else if(rectangle){
    				g.drawRect(mouseX,mouseY, width, height);
     
    			 if(fill)
    				g.fillRect(mouseX,mouseY, width,height);
     
    			}
    		  }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    You're not supposed to call the paint or paintComponent methods. You call the repaint() method and the JVM calls the paint method shortly after that and passes it a reference to a Graphics object.
    For normal use of drawing methods in paint/paintComponent your code does the computations for what you want drawn, puts the data about the drawings where the paint method can get to it and calls repaint().
    The JVM calls paint and the paint method gets the stored data and does the drawing.

  3. The Following User Says Thank You to Norm For This Useful Post:

    steel55677 (November 23rd, 2011)

  4. #3
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: how to use graphics g

    I see. I added repaint(); after mouseReleased and whenever I tried to draw a rectangle, it still won't show up . I'm really confused on how it is able to draw on the GUI when it's at mouseDragged without having to do repaint(); but when I used repaint(); at another method of mouseListener's actions it just won't work.
    public void mouseReleased( MouseEvent me)
    	{
     
    		mouseX = me.getX();
    		mouseY = me.getY();
    		reportCoords("Mouse released at: " +
    			mouseX + "," + mouseY );
    		x2 = mouseX;
    		y2 = mouseY;
    		System.out.println("x2: " +x2 +"y2: " +y2);
    		repaint();
    	}

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    Your code is confused on who does the painting. For example JFrame does not have a paintComponent() method to override.
    You should NOT override JFrame's paint method, but instead create a JPanel, add that to the JFrame and do your painting there.
    The code that builds the GUI is very confused also. The layout manager that's used and the constraints passed to the add() method are mixed. You add two components for the SOUTH area and another without any area.
    You should go through the design of the code and rewrite it.

  6. The Following User Says Thank You to Norm For This Useful Post:

    steel55677 (November 23rd, 2011)

  7. #5
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: how to use graphics g

    Yeah =\. I wished I did mine out of scratch but we're suppose to use our prof's pre-made program and then do the modifications there. I made a quick tester just like that and it worked when I used repaint(); but not at this program. Okay, I get what you're saying, that's the question I was thinking too when I couldn't find the panel that the g.draw uses. I just assumed it somehow makes an infinite loop of listener's on the screen. and the reason i made both "SOUTH" was b/c i wanted to see what the painted canvas was. I assumed that it'
    d go to the bottom but it's still on top ("NORTH").

    how do you make a paintedCanvas? do I just add it to JPanel paintedCanvas = new JPanel? and then paintedCanvas.add( paint object? );

  8. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    how do you make a paintedCanvas
    Create a class that extends JPanel and in that class override the paintComponent() method.
    Add an instance of that class to your GUI where you what to see it.

  9. The Following User Says Thank You to Norm For This Useful Post:

    steel55677 (November 23rd, 2011)

  10. #7
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: how to use graphics g

    got it, my first step. I added it as an inner class, is that okay? or do i need to make it outside of my etch a sketch class?
    public class paint extends JPanel{
     
    	}

  11. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    An inner class would be useful because it would allow the class to see the enclosing class's variables.
    paint is not a good name for your class. paint is a method name for some classes and class names should start with a Uppercase letter.

  12. #9
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: how to use graphics g

    Thanks, now I've changed it to:

    	  public class PaintHere extends Canvas{
     
    	  	}

    I'm hoping canvas would work because on the description it says: "A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. "

  13. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    Canvas is from the old awt classes. JPanel is part of Swing and has a lot more features that can be useful.

  14. #11
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: how to use graphics g

    thanks, i've gotten it to work correctly now.
    i got one last question, is there a way to store rectangle/oval or any shape so that when i make an eraser button, i can remove it?

  15. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,155
    Thanks
    65
    Thanked 2,722 Times in 2,672 Posts

    Default Re: how to use graphics g

    To be able to "erase" a shape, you will need to create a list of shapes for the paint method to draw.
    The erase step will remove the shape from the list.

Similar Threads

  1. Graphics class NullPointerException Initialize Graphics Class??
    By bglueck in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 13th, 2011, 11:13 PM
  2. OOP graphics program
    By conmanva in forum Object Oriented Programming
    Replies: 2
    Last Post: January 2nd, 2011, 04:20 PM
  3. JButton with 2D Graphics help
    By mystikaljester in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 13th, 2010, 09:33 PM
  4. Help about Graphics
    By mamech in forum What's Wrong With My Code?
    Replies: 13
    Last Post: September 9th, 2010, 03:20 PM
  5. graphics in job?
    By SweetyStacey in forum The Cafe
    Replies: 10
    Last Post: May 3rd, 2010, 03:29 PM