• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

How do I write a JFrame in which a dot/spot is created at the point clicked.

I am doing a Java course and have an assignment in which I have to write an application in which spots are drawn on a frame according to menu selections (size and colour). I have written the code for drawing the JFrame and inserting the menu elements, however I am stuck on how to draw the spots in the frame.

What I would like are some pointers or links on how to put spots or dots on the point clicked in a JFrame. Basically, I think I need pointers on how to use MouseAdapters. Code for a simple JFrame in which each click leaves a dot should be sufficient to get me on my way.

Thanks in advance
0
appretice
Asked:
appretice
  • 8
  • 6
1 Solution
 
objectsCommented:
0
 
appreticeAuthor Commented:
Sorry for the delay in feedback. Still getting my head wrapped round the solution provided!
0
 
appreticeAuthor Commented:
Hi again,

I have racked my brains but do not seem to be getting anywhere. Could someone please look my code over and suggest any ideas or pointers on what I should concentrate my efforts on.

This is the code for the program to draw spots at the point of the mouse click. It should also have provision to remove the last spots drawn if the undo button is pressed.

Any hints or pointers would be much appreciated.

Thanks
/*
 * Spotting.java
 *
 * Created on 13 July 2007, 14:07
 *
 */
 
package tma03q4;
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
 
/**
 *
 * @author M257
 */
public class Spotting extends JFrame
{
   // Insert declarations here
   private JRadioButton small;
   private JRadioButton medium;
   private JRadioButton large;
   
   private JRadioButton red;
   private JRadioButton green;
   private JRadioButton blue;
   
   private int[] xVals,yVals;
   private int numberOfClicks=0;
   
   private Clicker c1;
   
   // OU code starts below. Above code is mine
   private ArrayList<Spot> spots;
   
   private static int SMALL = 10;
   private static int MEDIUM = 20;
   private static int LARGE = 40;
   
   private int currentSize = SMALL;
   
   private Color currentColor = Color.RED;
   
   private JPanel canvas;
   
   public Spotting()
   {
      setSize(300, 300);
      setTitle("Spotting");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      canvas = new JPanel();
      canvas.setBackground(Color.WHITE);
      
      // Insert code here to construct the GUI
      //01.02.2008 @ 19:43 Starting work on the assignment:
      
      //Start with setting up the menu bar and menu items
      JMenuBar spottingMenuBar = new JMenuBar();
      
      //Trying to implement the menu items using radio buttons
      
      ButtonGroup size = new ButtonGroup();
      ButtonGroup colour = new ButtonGroup();
      
      JMenu spottingMenuSize = new JMenu("Size");
      JMenu spottingMenuColour = new JMenu("Colour");
      JMenu spottingMenuEdit = new JMenu("Edit");
            
      JRadioButtonMenuItem small = new JRadioButtonMenuItem("Small",true);
      JRadioButtonMenuItem medium = new JRadioButtonMenuItem("Medium",false);
      JRadioButtonMenuItem large = new JRadioButtonMenuItem("Large",false);
      
      small.addActionListener(new MenuSelection());
      medium.addActionListener(new MenuSelection());
      large.addActionListener(new MenuSelection());
      
      size.add(small);
      size.add(medium);
      size.add(large);
      
      JRadioButtonMenuItem red = new JRadioButtonMenuItem("Red",true);
      JRadioButtonMenuItem green = new JRadioButtonMenuItem("Green",false);
      JRadioButtonMenuItem blue = new JRadioButtonMenuItem("Blue",false);
      
      red.addActionListener(new MenuSelection());
      green.addActionListener(new MenuSelection());
      blue.addActionListener(new MenuSelection());
      
      spottingMenuSize.add(small);
      spottingMenuSize.add(medium);
      spottingMenuSize.add(large);
      
      spottingMenuColour.add(red);
      spottingMenuColour.add(green);
      spottingMenuColour.add(blue);
      
      JMenuItem undoItem = new JMenuItem("Undo");
      undoItem.setAccelerator(KeyStroke.getKeyStroke("control Z"));
      spottingMenuEdit.add(undoItem);
      
      c1 = new Clicker();
      addMouseListener(c1);
      
      spottingMenuBar.add(spottingMenuSize);
      spottingMenuBar.add(spottingMenuColour);
      spottingMenuBar.add(spottingMenuEdit);
      
      
      colour.add(red);
      colour.add(green);
      colour.add(blue);
     
      setJMenuBar(spottingMenuBar);
     
      
      getContentPane().add("Center", canvas);
   }
   
   public void paint(Graphics g)
   {
      super.paint(g);
      Graphics gr = canvas.getGraphics();
      
     // Insert drawing code here
      //02.02.2008, dabbling with drawing the spot
     for (int i=0;i<numberOfClicks;i++)
     {
      gr.setColor(currentColor);
      gr.fillOval(xVals[i],yVals[i], currentSize, currentSize);
     }
   }
   
  // Insert code here to define the listener classes
   public class MenuSelection implements ActionListener
   {
      public void actionPerformed (ActionEvent e)
      {
         if (e.getSource()=="small")
         {
            currentSize = SMALL;
         }
         
         if (e.getSource()=="medium")
         {
            currentSize = MEDIUM;
         }
         
         if (e.getSource()=="large")
         {
            currentSize = LARGE;
         }
         if (e.getSource()=="red")
         {
            currentColor = Color.RED;
         }
         
         if (e.getSource()=="green")
         {
            currentColor = Color.GREEN;
         }
         
         if (e.getSource()=="blue")
         {
            currentColor = Color.BLUE;
         }
         repaint();
      }
   }
      
   private class Clicker extends MouseAdapter
   {
      public void mouseClicked (MouseEvent m)
      {
         for (int i=0;i<numberOfClicks;i++)
         { 
            xVals[i] = m.getX();
            yVals[i] = m.getY();
            numberOfClicks++;
            repaint();
         }
      }
   }
   
   public void setColor(Color c)
   {
      currentColor = c;
   }
    
}

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Bart CremersJava ArchitectCommented:
It would be easier to work with the arraylist and the Spot class.

On each mouseclick, add a new Spot to the list and repaint the canvas. In the paint method simply iterate over the list and draw the spots one by one.

For the undo, when pressed you can simply remove the last element from the list and repaint.
0
 
Bart CremersJava ArchitectCommented:
Also, add the mouselistener on the canvas instead of on the frame. Spot position will be easier to resolve.
0
 
Bart CremersJava ArchitectCommented:
For the menu actionlistener:
You're declaring fields:

      // Insert declarations here
      private JRadioButton small;
      private JRadioButton medium;
      private JRadioButton large;
   
      private JRadioButton red;
      private JRadioButton green;
      private JRadioButton blue;
 
but yet you are redeclaring them as local variables:

      JRadioButtonMenuItem small = new JRadioButtonMenuItem("Small",true);
      JRadioButtonMenuItem medium = new JRadioButtonMenuItem("Medium",false);
      JRadioButtonMenuItem large = new JRadioButtonMenuItem("Large",false);

while in the action listener you're comparing the source (JRadioButtonMenuItem) to a String. It should be:

      if (e.getSource() == small) {
          currentSize = SMALL;
     }

You can then simply add one for the undo.
0
 
appreticeAuthor Commented:
Thanks for the tips Bart_Cr.

Am currently working on your input. Will post back as soon as I have 'digested' it.
0
 
appreticeAuthor Commented:
Seeing as the Spot class doesn't have a paint method, hence a spot object cannot draw itself, how do I draw a spot using the spot class?
0
 
Bart CremersJava ArchitectCommented:
In the paint method you can write:

    gr.setColor(spot.getColor());
    gr.fillOval(spot.getX(), spot.getY(), spot.getSize(), spot.getSize());

This of course works with my Spot class as you didn't provide me with yours:
class Spot {
    private int x;
    private int y;
    private Color color;
    private int size;
 
    public Spot(int x, int y, Color color, int size) {
        this.x = x - (size / 2);
        this.y = y - (size / 2);
        this.color = color;
        this.size = size;
    }
 
    public int getX() {
        return x;
    }
 
    public int getY() {
        return y;
    }
 
    public Color getColor() {
        return color;
    }
 
    public int getSize() {
        return size;
    }
}

Open in new window

0
 
appreticeAuthor Commented:
Interesting! Back to the drawing board for me. Thanks, will post back as soon as I have played with the code some more.
0
 
appreticeAuthor Commented:
I'm almost there. Just need some assistance on the last few legs. Tried finding the solutions myself but I'm so tired now I think I need another 'shot' of direction. Please show me where I'm going wrong. I 've tried changing a few things and experimenting a little but have still failed to get the menu to work right or to get the 'undo' item working.
/*
 * Spotting.java
 *
 * Created on 13 July 2007, 14:07
 *
 */
 
package tma03q4;
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
 
/**
 *
 * @author M257
 */
public class Spotting extends JFrame
{
   // Insert declarations here
   private JRadioButton small;
   private JRadioButton medium;
   private JRadioButton large;
   
   private JRadioButton red;
   private JRadioButton green;
   private JRadioButton blue;
   
   private JMenuItem undoItem;
   
   private int xVal,yVal;
   private int numberOfClicks=0;
   
   // OU code starts below. Above code is mine
   private ArrayList<Spot> spots;
   
   private static int SMALL = 10;
   private static int MEDIUM = 20;
   private static int LARGE = 40;
   
   private int currentSize = SMALL;
   
   private Color currentColor = Color.RED;
   
   private JPanel canvas;
   
   public Spotting()
   {
      setSize(300, 300);
      setTitle("Spotting");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      canvas = new JPanel();
      canvas.setBackground(Color.WHITE);
      canvas.addMouseListener(new MouseWatcher());
      
      // Insert code here to construct the GUI
      //01.02.2008 @ 19:43 Starting work on the assignment:
      
      //Start with setting up the menu bar and menu items
      JMenuBar spottingMenuBar = new JMenuBar();
      
      //Trying to implement the menu items using radio buttons
      
      ButtonGroup size = new ButtonGroup();
      ButtonGroup colour = new ButtonGroup();
      
      JMenu spottingMenuSize = new JMenu("Size");
      JMenu spottingMenuColour = new JMenu("Colour");
      JMenu spottingMenuEdit = new JMenu("Edit");
            
      JRadioButtonMenuItem small = new JRadioButtonMenuItem("Small",true);
      JRadioButtonMenuItem medium = new JRadioButtonMenuItem("Medium",false);
      JRadioButtonMenuItem large = new JRadioButtonMenuItem("Large",false);
      
      small.addActionListener (new MenuSelection());
      medium.addActionListener(new MenuSelection());
      large.addActionListener(new MenuSelection());
      
      size.add(small);
      size.add(medium);
      size.add(large);
      
      JRadioButtonMenuItem red = new JRadioButtonMenuItem("Red",true);
      JRadioButtonMenuItem green = new JRadioButtonMenuItem("Green",false);
      JRadioButtonMenuItem blue = new JRadioButtonMenuItem("Blue",false);
      
      red.addActionListener(new MenuSelection());
      green.addActionListener(new MenuSelection());
      blue.addActionListener(new MenuSelection());
      
      spottingMenuSize.add(small);
      spottingMenuSize.add(medium);
      spottingMenuSize.add(large);
      
      spottingMenuColour.add(red);
      spottingMenuColour.add(green);
      spottingMenuColour.add(blue);
      
      undoItem = new JMenuItem("Undo");
      undoItem.setAccelerator(KeyStroke.getKeyStroke("control Z"));
      spottingMenuEdit.add(undoItem);
      
      spottingMenuBar.add(spottingMenuSize);
      spottingMenuBar.add(spottingMenuColour);
      spottingMenuBar.add(spottingMenuEdit);
      
      
      colour.add(red);
      colour.add(green);
      colour.add(blue);
     
      setJMenuBar(spottingMenuBar);
     
      spots = new ArrayList();
      
      getContentPane().add("Center", canvas);
   }
   
   public void paint(Graphics g)
   {
      super.paint(g);
      Graphics gr = canvas.getGraphics();
      
     // Insert drawing code here
      //02.02.2008, dabbling with drawing the spot
      for (int i=0;i<numberOfClicks;i++)
      {
         gr.setColor(currentColor);
         gr.fillOval(spots.get(i).getX(),
               spots.get(i).getY(),
               spots.get(i).getRadius(),
               spots.get(i).getRadius());
      }
   }
  // Insert code here to define the listener classes
     public class MenuSelection implements ActionListener
   {
      public void actionPerformed (ActionEvent e)
      {
         if (e.getSource()==small)
         {
            currentSize = SMALL;
         }
         
         if (e.getSource()==medium)
         {
            currentSize = MEDIUM;
         }
         
         if (e.getSource()==large)
         {
            currentSize = LARGE;
         }
         if (e.getSource()==red)
         {
            currentColor = Color.RED;
         }
         
         if (e.getSource()==green)
         {
            currentColor = Color.GREEN;
         }
         
         if (e.getSource()==blue)
         {
            currentColor = Color.BLUE;
         }
         if (e.getSource()==undoItem)
         {
            if (spots.get(numberOfClicks-1)!=null)
            {
               spots.remove(numberOfClicks-1);
            }
         }
        
         repaint();
      }
   }
 
      
   private class MouseWatcher implements MouseListener
   {
      public void mouseClicked (MouseEvent m)
      {
         xVal = m.getX();
         yVal = m.getY();
         spots.add(new Spot(currentColor, xVal, yVal, currentSize));
         numberOfClicks++;
         repaint();
      }
      public void mouseEntered (MouseEvent m)
      {
         
      }
      public void mouseReleased (MouseEvent m)
      {
         
      }
      public void mousePressed (MouseEvent m)
      {
         
      }
      public void mouseExited (MouseEvent m)
      {
         
      }
   }
   
   public void setColor(Color c)
   {
      currentColor = c;
   }
    
}

Open in new window

0
 
Bart CremersJava ArchitectCommented:
For the menu actionlistener:
You're declaring fields:

      // Insert declarations here
      private JRadioButton small;
      private JRadioButton medium;
      private JRadioButton large;
   
      private JRadioButton red;
      private JRadioButton green;
      private JRadioButton blue;
 
but yet you are redeclaring them as local variables:

      JRadioButtonMenuItem small = new JRadioButtonMenuItem("Small",true);
      JRadioButtonMenuItem medium = new JRadioButtonMenuItem("Medium",false);
      JRadioButtonMenuItem large = new JRadioButtonMenuItem("Large",false);
0
 
Bart CremersJava ArchitectCommented:
The construction of the items should be :

      small = new JRadioButtonMenuItem("Small",true);
      medium = new JRadioButtonMenuItem("Medium",false);
      large = new JRadioButtonMenuItem("Large",false);
0
 
appreticeAuthor Commented:
Surprising how some things are so easily overlooked. Thanks very much for all your assistance Bart_Cr. I have learnt quite a lot just from doing this assignment. Will work on the 'undo' function and neatening up of the code after a few hours sleep! Once again, thanks for everything. Your help has been invaluable especially to a newbie.
0
 
appreticeAuthor Commented:
As a newbie working on an assignment, I was guided to finding the correct solution and have learnt quite a lot through the Experts guidance. Thank you!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now