Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 252
  • Last Modified:

How do I add a label

How do I add a label to a canvas and move the label with the mouse on every mouseDragged event.
0
amba2004
Asked:
amba2004
  • 3
1 Solution
 
CEHJCommented:
label.setPosition(me.getX(), me.getY()); // 'me' is the MouseEvent
0
 
objectsCommented:
Use a null layout, and set the label location in your mouseDragged.

label.setLocation(event.getX(), event.getY());
0
 
gnoonCommented:
>How do I add a label to a canvas
You *cannot* add Label to a Canvas since Canvas is not a Container.
0
 
gnoonCommented:
In you need Canvas anyway, this example can tells you how to do work around.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Frm extends JFrame {

    public Frm() {
        super("");
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        setSize(400,400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        MyCanvas cv = new MyCanvas();
        c.add(cv);
    }

    public static void main(String[] args) {
        Frm f1 = new Frm();
        f1.show();
    }
}

class MyCanvas extends Canvas implements MouseMotionListener {
    int x = 0;
    int y = 10;
    public MyCanvas() {
        addMouseMotionListener(this);
    }
    public void paint(Graphics g) {
        g.setColor(Color.black);
        g.drawString("Label",x,y);
    }
    public void setXY(int x,int y) {
        this.x = x;
        this.y = y;
        repaint();
    }
    public void mouseDragged(MouseEvent e){
        setXY(e.getX(),e.getY());
    }
    public void mouseMoved(MouseEvent e) {}
}
0
 
gnoonCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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