Results 1 to 13 of 13
  1. #1
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Drawing shapes on the JPanel, not working properly

    I am for the first time working with JPanel and drawing basic shapes on the JPanel.

    I have write a code for the shape like this:

    Java Code:
    public class Shape extends JPanel{
    
    int x,y;
    
    public Shape(int x, int y){
        this.x = x;
        this.y = y;
    }
    
    public void paint(Graphics g){
        super.paint(g);
        g.setColor(Color.black);
        g.drawRect(x, y, 20, 20);
        }
    }
    I have another class where I will be using this shape. It extends JFrame and implements MouseListener. On this JFrame I have put the JPanel it is called simply "panel".

    The "panel" is defined as an attribute of a class, and initilaized, in a constructor.

    I have the method, which reads the mouse position, and draws the shape on the "panel".

    Java Code:
    public void mouseClicked(MouseEvent e){
        Shape shape = new Shape(e.getX(),e.getY());
        panel.add(shape);
        panel.revalidate();
        panel.repaint();
    }
    The problem is that it doesn't draw the shape on the coordinate where my mouse is. It just draws on panel at the upper-side and the rectangle is gray, instead of black.

    Thank you for your help.

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

    Default Re: Drawing shapes on the JPanel, not working properly

    Much depends on the layout of the container that you're adding this JPanel to. Consider creating and posting a small compilable and runnable program that we can run and modify and that shows us your problem, an SSCCE.

  3. #3
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    Sure, I can post the code, no problem.

    This is the whole second class:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DrawingExample extends JFrame implements ActionListener, MouseListener {
    	JPanel panel;
    	Container content;
    	
    	public DrawingExample(String name){
    		super(name);
    		content = getContentPane();
    		content.setLayout(null);
    
    		panel = new JPanel();
    		panel.addMouseListener(this);
    		
    		panel.setBackground(Color.white);
    		panel.setBounds(130,10, 500, 450);
    		
    		content.add(panel);
    		
    		
    	}
    	
    	public void mouseClicked(MouseEvent e){
    		Shape shape = new Shape(e.getX(),e.getY());
    		shape.setBounds(e.getY(),e.getX(), 10, 10);
    		panel.add(shape);
    		panel.revalidate();
    		panel.repaint();
    	}
    	
    	public void mouseEntered(MouseEvent e){		
    	}
    	
    	public void mouseExited(MouseEvent e){
    		
    	}
    	public void mousePressed(MouseEvent e){
    		
    	}
    	
    	public void mouseReleased(MouseEvent e){
    		
    	}
    	
    	public static void main(String args[]){
    		DrawingExample frame = new DrawingExample("Drawing");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(750, 550);
    		frame.setVisible(true);
    	}
    	
    }
    Can you see what is the problem? Thanks for answering.

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

    Default Re: Drawing shapes on the JPanel, not working properly

    You're forgetting that the panel JPanel uses FlowLayout. If this were my code, I would
    1. Not use null layout for anything
    2. Add my Shape JPanel to the JFrame's contentPane using contentPane's default BorderLayout, and in the CENTER position.
    3. I'd give the MouseListener to the Shape JPanel,
    4. I'd have my MouseListener set the Shape JPanel's x position and y position via a setter method and call repaint on it.
    5. I'd change the name of my position fields from x and y since I know that I'd risk big trouble if I ever accidentally override a JPanel's setX, setY, or getX and getY methods.

  5. #5
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    I need the MouseListener at the "panel". Because I will add buttons, where you can change the shape for drawing on the "panel".

    If I dont' use the method setLayout(null), the position of the "panel" on the frame doesn't work.


    Can you help me with changing the code, so I can see what did you mean. I don't have much time for doing this.

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

    Default Re: Drawing shapes on the JPanel, not working properly

    Quote Originally Posted by Nforce View Post
    I need the MouseListener at the "panel". Because I will add buttons, where you can change the shape for drawing on the "panel".
    I'm sorry, but I don't understand this statement. Can you please elaborate?

    If I dont' use the method setLayout(null), the position of the "panel" on the frame doesn't work.
    Yes it will if you understand and use the layout managers correctly. Use of null layout will cause you no end of grief if you ever have to maintain or update the GUI.

    Can you help me with changing the code, so I can see what did you mean.
    I can't do your project for you of course. Please clarify your concerns and I will try to help as best I can.

    I don't have much time for doing this.
    This is more your concern than ours.

  7. #7
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    Quote Originally Posted by Fubarable View Post
    I'd give the MouseListener to the Shape JPanel,
    I'd have my MouseListener set the Shape JPanel's x position and y position via a setter method and call repaint on it.
    If I understand you correctly, if I add the MouseListener to the Shape Class, I can't use it in my main class. Can you please modify the code, so that I can see what did you mean.

    You will help me by this but not completely. I have to add a lot of stuff in the program, and I will do it myself.

    The problem is that I can't find anything on the internet or in my books, for this task.

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

    Default Re: Drawing shapes on the JPanel, not working properly

    Quote Originally Posted by Nforce View Post
    If I understand you correctly, if I add the MouseListener to the Shape Class, I can't use it in my main class.
    No, that's not true at all. You can use it as the main panel that is added to the JFrame. Your Shape class extends JPanel and can be used anywhere and in any way that you would use a JPanel.

    Can you please modify the code, so that I can see what did you mean.
    My preference is that you give the rec a try and to work with what you come up with. I'm simply recommending that you use the Shape object in place of JPanel for your panel variable, again that you add an MouseListener to it, and that you have that MouseListener set the fields of the Shape object and not create a new Shape object. Please give it a go, as I bet you'll be successful if you do!

  9. #9
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    Yes it extends but, the whole program must contain extra buttons, and a comboBox, so I don't think, moving a MouseListener to the Shape class, is a good idea.

    Your answer is good, but it has destroyed my logic, so I don't know what to do now...

    I was just doing by the book, and some examples. I don't know how to start now?

  10. #10
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    Sorry, again for a double post. But if I use the flowlayout, the buttons and the "panel" are all align on the left.

    This is something i don't want to happen, so I use method setlayout(null) so I can position the elements where are I want to.

    I was experementing with this, and I also set for the "panel", setLayout(null), so the rectangles wouldn't be align on the panel.

    Java Code:
    content = getContentPane();
    content.setLayout(null);
     
    panel = new JPanel();
    panel.setLayout(null);
    panel.addMouseListener(this);
    And now it doesn't work at all.

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

    Default Re: Drawing shapes on the JPanel, not working properly

    You want an example, here's an example of doing graphics directly in a JPanel and adding components to it. The example doesn't do exactly what you're trying to do, but shows you what can be done for similar problems:

    Java Code:
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Stroke;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class DrawExample extends JPanel {
       private static final int PREF_W = 900;
       private static final int PREF_H = 500;
       private static final Color DRAW_COLOR = Color.blue.darker();
       private static final Color DRAWING_COLOR = new Color(190, 190, 255);
       private static final Stroke RECT_STROKE = new BasicStroke(3f);
       private Rectangle drawingRect = null;
       private List<Rectangle> rectList = new ArrayList<Rectangle>();
    
       public DrawExample() {
          MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
          addMouseListener(myMouseAdapter);
          addMouseMotionListener(myMouseAdapter);
          int eb = 15;
          setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
       }
       
       public void clearRects() {
          rectList.clear();
          repaint();
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          if (drawingRect != null) {
             g2.setColor(DRAWING_COLOR);
             g2.draw(drawingRect);
          }
          g2.setColor(DRAW_COLOR);
          g2.setStroke(RECT_STROKE);
          for (Rectangle rect : rectList) {
             g2.draw(rect);
          }
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private class MyMouseAdapter extends MouseAdapter {
          private Point pt1;
    
          @Override
          public void mousePressed(MouseEvent mEvt) {
             pt1 = mEvt.getPoint();
             drawingRect = new Rectangle(pt1.x, pt1.y, 0, 0);
          }
          
          @Override
          public void mouseReleased(MouseEvent mEvt) {
             Point pt2 = mEvt.getPoint();
             
             drawingRect.x = Math.min(pt1.x, pt2.x);
             drawingRect.y = Math.min(pt1.y, pt2.y);
             drawingRect.width = Math.abs(pt1.x - pt2.x);
             drawingRect.height = Math.abs(pt1.y - pt2.y);
             
             rectList.add(drawingRect);
             drawingRect = null;
             repaint();
          }
          
          @Override
          public void mouseDragged(MouseEvent mEvt) {
             Point pt2 = mEvt.getPoint();
             
             drawingRect.x = Math.min(pt1.x, pt2.x);
             drawingRect.y = Math.min(pt1.y, pt2.y);
             drawingRect.width = Math.abs(pt1.x - pt2.x);
             drawingRect.height = Math.abs(pt1.y - pt2.y);
             repaint();
          }
       }
    
       private static void createAndShowGui() {
          final DrawExample mainPanel = new DrawExample();
          
          mainPanel.setLayout(new BorderLayout());
          
          JPanel btnPanel = new JPanel(new GridLayout(1, 0, 15, 0));
          btnPanel.setOpaque(false);
          String[] btnNames = {"To", "Show", "Can", "Add", "GUI", "Elements"};
          for (String btnName : btnNames) {
             btnPanel.add(new JButton(new AbstractAction(btnName) {
                
                @Override
                public void actionPerformed(ActionEvent arg0) {
                   mainPanel.clearRects();
                }
             }));
          }
          
          mainPanel.add(btnPanel, BorderLayout.SOUTH);
    
          JFrame frame = new JFrame("DrawExample");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }

  12. #12
    Nforce is offline Member
    Join Date
    Dec 2012
    Posts
    7
    Rep Power
    0

    Default Re: Drawing shapes on the JPanel, not working properly

    Thanks a lot, but you shouldn't post the whole code. I would be much happier if you could add the missing parts to my code.


    I see a class Rectangle, is that build into JComponent Framework? Is there a class for a circle?

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

    Default Re: Drawing shapes on the JPanel, not working properly

    Quote Originally Posted by Nforce View Post
    Thanks a lot, but you shouldn't post the whole code. I would be much happier if you could add the missing parts to my code.
    Again, this isn't an adaption of your code.

    I see a class Rectangle, is that build into JComponent Framework? Is there a class for a circle?
    You should rename your Shape class to something else, and then look at the Shape interface in the Java API. There are several classes that implement this interface that you could possibly use including an Ellipse2D.

Similar Threads

  1. Drawing Shapes on to a Jpanel
    By pepsi in forum AWT / Swing
    Replies: 7
    Last Post: 03-09-2012, 06:39 PM
  2. Having issues drawing Shapes into Jpanel
    By Greedychris in forum AWT / Swing
    Replies: 2
    Last Post: 03-06-2012, 06:32 AM
  3. Drawing different shapes with stars.
    By Amazineous in forum New To Java
    Replies: 23
    Last Post: 11-14-2011, 04:55 PM
  4. Drawing shapes with for loops using characters
    By Strawlion in forum New To Java
    Replies: 3
    Last Post: 02-16-2011, 09:32 PM
  5. drawing shapes in java help
    By alphajoseph in forum Java 2D
    Replies: 2
    Last Post: 09-29-2009, 07:35 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
  •