Linking a button click to a mouse event?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 11 of 11

Thread: Linking a button click to a mouse event?

Hybrid View

  1. #1
    Join Date
    Nov 2005
    Posts
    44

    Linking a button click to a mouse event?

    Hi,

    I'm pretty new to Java, and as such still struggle from basic problems.

    My problem is how to do I link an action event from a button to a mouse event. This is being used in a program to allow users to draw a square, oval etc on a canvas by clicking their mouse button. They choose which shape to draw from the corresponding button. My problem is that the button is not reflecting the mouse click and vice-versa.

    My code so far is as follows,

    From the DrawToolCanvas class:

    import java.awt.*;
    import java.awt.event.*;

    public class DrawToolCanvas extends Canvas implements MouseListener, ActionListener
    {


    public void paint(Graphics g)
    {
    }

    public void actionPerformed(ActionEvent event)
    { if (event.getActionCommand().equals("square"))
    square();
    else if (event.getActionCommand().equals("circle"))
    circle();
    }

    public void square()
    { Graphics g = getGraphics();
    int x=e.getX(), y=e.getY();
    g.setColor(Color.red);
    g.fillRect( x, y, x = 40, y = 40 );
    g.setColor(Color.black);
    }

    public void circle()
    { Graphics g = getGraphics();
    int x=getX(), y=getY();
    g.setColor(Color.blue);
    g.fillOval( x, y, x = 40, y = 40 );
    g.setColor(Color.black);

    }

    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}

    }


    Any help would be gratefully appreciated!

    Many thanks

  2. #2
    Join Date
    Oct 2004
    Location
    Chicago
    Posts
    108
    You don't hava a button which you can link the event with.

    You are basically drawing shapes on the canvas. I dont' think it is possible to do it like that, I might be wrong.


    Code:
    JButton square = new JButton("Square");
    		
    		square.addMouseListener(new MouseListener()
    		{
    		
    				public void actionPerformed(MouseListener I)
    				{
    					System.out.print("Clicked on Square");
    				}
    		});

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Drawing in the sand.

    You can implement it like this:
    Code:
    /**
     * DrawTool Canvas (awt)
     */
    
    import java.awt.*;
    import java.awt.event.*;
    
    public class DrawToolAWT extends Canvas
        implements MouseListener, ActionListener {
    
      String drawType="square";
      Point lastClickPoint=null;
    
      public void paint(Graphics g) {
        update(g);
      }
      public void update(Graphics g) {
        System.out.println("update");
        Color c=g.getColor();
        coverBackground(g);
        if (lastClickPoint==null) {
          g.setColor(Color.black);
          g.drawString("Click canvas first",20,20);
        } else {
          if (drawType.equals("square")) {
            drawSquare(g);
          }
          else if (drawType.equals("circle")) {
            drawCircle(g);
          }
        }
        g.setColor(c);
      }
    
      private void coverBackground(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0,0,getWidth(),getHeight());
      }
    
      public void actionPerformed(ActionEvent event) {
        System.out.println("actionPerformed: "+event.getActionCommand());
        if (event.getActionCommand().equals("square"))
          drawType="square";
        else if (event.getActionCommand().equals("circle"))
          drawType="circle";
        repaint();
      }
      public void mouseReleased(MouseEvent e) {
        lastClickPoint=e.getPoint();
        repaint();
      }
      public void drawSquare(Graphics g) {
        g.setColor(Color.red);
        g.fillRect(lastClickPoint.x, lastClickPoint.y, 40, 40);
    
      }
    
      public void drawCircle(Graphics g) {
        g.setColor(Color.blue);
        g.fillOval(lastClickPoint.x, lastClickPoint.y, 40, 40);
    
    
      }
      public static void main(String[] args) {
        Frame f=new Frame("DrawTool");
        f.setLayout(new BorderLayout());
        DrawToolSwing dts=new DrawToolSwing();
        Button btn1=new Button("circle");
        Button btn2=new Button("square");
        btn1.addActionListener(dts);
        btn2.addActionListener(dts);
        dts.addMouseListener(dts);
    
        dts.add(btn1);
        dts.add(btn2);
        Panel btnPan=new Panel();
        btnPan.add(btn1);
        btnPan.add(btn2);
    
        f.add(dts,BorderLayout.CENTER);
        f.add(btnPan,BorderLayout.SOUTH);
    
        f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
        f.setBounds(20,20,500,400);
        f.setVisible(true);
      }
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseClicked(MouseEvent e) {}
    
    }
    The problem is that these drawings are stored nowhere else but in the display
    graphical context, so if you minimize/restore the app window, or cover it
    partially the drawing will disappear. You will either have to store the drawing
    shapes in a list and/or use double buffering for the graphics.
    Last edited by sjalle; 11-06-2005 at 08:01 AM. Reason: I mixed swing & awt real bad
    eschew obfuscation

  4. #4
    Join Date
    Nov 2005
    Posts
    44

    Re: Linking a button to a mouse event?

    Hi,

    Thanks for the reply. The buttons are specified in a seperate class, called DrawToolFrame. Here is the code for both classes,

    1. DrawToolFrame class:

    import java.awt.*;
    import java.awt.event.*;

    public class DrawToolFrame extends Frame
    implements WindowListener
    {
    DrawToolCanvas myCanvas;

    public DrawToolFrame()
    {
    setTitle("Draw Tool Frame");
    addWindowListener(this);
    Button square, circle;
    Panel myPanel = new Panel();
    square = new Button("square"); square.setActionCommand("square");
    circle = new Button("circle"); circle.setActionCommand("circle");
    myPanel.add(square); myPanel.add(circle);
    add("South", myPanel);
    DrawToolCanvas myCanvas = new DrawToolCanvas();
    add("Center", myCanvas);
    square.addMouseListener(myCanvas);
    circle.addMouseListener(myCanvas);
    }


    public void windowClosing(WindowEvent event) { System.exit(0); }
    public void windowOpened(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowClosed(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}

    }


    2. DrawToolCanvas class:

    import java.awt.*;
    import java.awt.event.*;

    public class DrawToolCanvas extends Canvas implements MouseListener, ActionListener
    {
    MouseEvent e;


    public void paint(Graphics g)
    {
    }

    public void actionPerformed(ActionEvent event)
    { if (event.getActionCommand().equals("square"))
    square();
    else if (event.getActionCommand().equals("circle"))
    circle();
    }

    public void square()
    { Graphics g = getGraphics();
    int x=e.getX(), y=e.getY();
    g.setColor(Color.black);
    g.fillRect( x, y, x = 40, y = 40 );
    g.setColor(Color.black);

    }

    public void circle()
    { Graphics g = getGraphics();
    int x=e.getX(), y=e.getY();
    g.setColor(Color.blue);
    g.fillOval( x, y, x = 40, y = 40 );
    g.setColor(Color.black);

    }

    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseClicked(MouseEvent e)
    {
    }

    }


    I'm getting really lost with this at the moment. Any help?

  5. #5
    Join Date
    Nov 2005
    Posts
    44
    sjalle, thank you for your reply.

    I have tried implementing the DrawToolCanvas class as recommended, but the program still doesn't display any image when the user clicks on the canvas.

    Maybe my implementation of DrawToolFrame is incorrect. I'm really getting frustrated with this. Java does not seem to be my type of language.

    Anyway, the code for the DrawToolFrame class is as follows:

    import java.awt.*;
    import java.awt.event.*;

    public class DrawToolFrame extends Frame
    implements WindowListener
    {
    DrawToolCanvas myCanvas;

    public DrawToolFrame()
    {
    setTitle("Draw Tool Frame");
    addWindowListener(this);
    Button square, circle;
    Panel myPanel = new Panel();
    square = new Button("square"); square.setActionCommand("square");
    circle = new Button("circle"); circle.setActionCommand("circle");
    myPanel.add(square); myPanel.add(circle);
    add("South", myPanel);
    DrawToolCanvas myCanvas = new DrawToolCanvas();
    add("Center", myCanvas);
    square.addMouseListener(myCanvas);
    circle.addMouseListener(myCanvas);
    }


    public void windowClosing(WindowEvent event) { System.exit(0); }
    public void windowOpened(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowClosed(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}

    }


    Again, any help would be really appreciated.

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    My fault...

    My first post here was wrong, I have edited it, sorry about that.

    But, I have a swing version also here. Notice that I when I use this I am
    able to add components (buttons) to the drawingArea.

    Also, check out the oddities w. the AWT version. Among other things,
    the println in the actionPerformed method is not happening, at least not on
    my machine, although the method obviously is invoked.

    So, I'd say; trash the Canvas and forget it. Use JPanel, not only does is
    "work" better, it looks better too.

    Code:
    /**
     * DrawTool JPanel (swing)
     */
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DrawToolSwing extends JPanel
        implements MouseListener, ActionListener {
    
      String drawType="square";
      Point lastClickPoint=null;
    
      public void paintComponent(Graphics g) {
        Color c=g.getColor();
        coverBackground(g);
        if (lastClickPoint==null) {
          g.setColor(Color.black);
          g.drawString("Click canvas first",20,20);
        } else {
          if (drawType.equals("square")) {
            drawSquare(g);
          }
          else if (drawType.equals("circle")) {
            drawCircle(g);
          }
        }
        g.setColor(c);
      }
    
      private void coverBackground(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0,0,getWidth(),getHeight());
      }
    
      public void actionPerformed(ActionEvent event) {
        System.out.println("actionPerformed: "+event.getActionCommand());
        if (event.getActionCommand().equals("square"))
          drawType="square";
        else if (event.getActionCommand().equals("circle"))
          drawType="circle";
        repaint();
      }
      public void mouseReleased(MouseEvent e) {
        lastClickPoint=e.getPoint();
      }
      public void drawSquare(Graphics g) {
        g.setColor(Color.red);
        g.fillRect(lastClickPoint.x, lastClickPoint.y, 40, 40);
        g.setColor(Color.black);
      }
    
      public void drawCircle(Graphics g) {
        g.setColor(Color.blue);
        g.fillOval(lastClickPoint.x, lastClickPoint.y, 40, 40);
        g.setColor(Color.black);
    
      }
      public static void main(String[] args) {
        JFrame f=new JFrame("DrawTool");
        f.getContentPane().setLayout(new GridLayout());
        DrawToolSwing dts=new DrawToolSwing();
        JButton btn1=new JButton("circle");
        JButton btn2=new JButton("square");
        btn1.addActionListener(dts);
        btn2.addActionListener(dts);
        dts.addMouseListener(dts);
        dts.add(btn1);
        dts.add(btn2);
        f.getContentPane().add(dts,null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setBounds(20,20,500,400);
        f.setVisible(true);
      }
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseClicked(MouseEvent e) {}
    
    }
    Last edited by sjalle; 11-06-2005 at 08:10 AM.
    eschew obfuscation

  7. #7
    Join Date
    Nov 2005
    Posts
    44

    Smile Any idea how to keep images on the canvas?

    Hi sjalle,

    Thank you so much for your help with this problem. One last question though.

    Any idea how I can keep the shapes on the screen after each time a user clicks the canvas. At the moment, they are simply being replaced with a new shape.

    Many thanks

Similar Threads

  1. Replies: 3
    Last Post: 11-26-2002, 03:40 PM
  2. Simulating button click event
    By Rich Golem in forum .NET
    Replies: 2
    Last Post: 04-14-2002, 10:07 PM
  3. Replies: 0
    Last Post: 08-07-2000, 10:29 PM
  4. Replies: 0
    Last Post: 08-07-2000, 10:29 PM
  5. Re: List Boxes? and the Click event
    By Ray Wimsett in forum VB Classic
    Replies: 0
    Last Post: 07-20-2000, 04:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center