Draw trail of circles with mouseDragged - java

I am trying to write a program that draws a line of circles with mouseDragged, like MS paint does. I have successfully gotten my program to draw a circle when I click. I have also been successful in getting my program to draw a circle when I drag the mouse; however, this doesn't leave a line of circles behind wherever I dragged. It simply drags the same circle around. I am trying to get my program to leave a trail of circles behind where I am dragging but I am pretty confused on why my program wont do so.
package assignment_11;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Canvas extends JComponent implements MouseListener, MouseMotionListener{
private int x, x1;
private int y, y1;
public Canvas() {
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
//creates new JFrame, sets Exit On Close, sets visible
JFrame window = new JFrame();
window.add(new Canvas());
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(640,480);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println(arg0);
x = arg0.getX();
y = arg0.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println(arg0);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 10, 10);
g.fillOval(x1, y1, 10, 10);
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0);
x1 = arg0.getX();
y1 = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
System.out.println(arg0);
}
}
Any help is appreciated!

Painting is destructive. That is, every time paintComponent is called, you are expected to repaint the entire state of the component.
This raises the issue - you need some way to store the state you want to paint every time paintComponent is called.
For this, a simple ArrayList would do the job nicely. It would allow you to store all the points you're interested and allow you to repaint them each time paintComponent is called, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Canvas extends JComponent implements MouseListener, MouseMotionListener {
private List<Point> points;
public Canvas() {
points = new ArrayList<>(25);
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
EventQueue.invokeLater((new Runnable() {
#Override
public void run() {
JFrame window = new JFrame();
window.add(new Canvas());
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}));
}
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println(arg0);
points.add(arg0.getPoint());
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println(arg0);
}
public void paintComponent(Graphics g) {
for (Point p : points) {
g.fillOval(p.x, p.y, 10, 10);
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0);
points.add(arg0.getPoint());
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
System.out.println(arg0);
}
}
Now, as the complexity of your problem grows, you could instead store "shapes" in the List which have some kind of notion of how to paint themselves, allowing to add in more complex shapes
You should also have a look at Painting in AWT and Swing to gain a better understand of how painting in Swing actually works

Related

Problems with repaint()

Im having some trouble using repaint.The code is supposed to draw a line behind your cursor.
package javaapplication6;
import java.awt.*;
import javax.swing.JFrame;
import java.awt.event.*;
class Test extends Canvas implements MouseListener, MouseMotionListener {
int x[]=new int[1024];
int y[]=new int[1024];
int size=0;
public void MouseDemo(){
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint (Graphics g){
g.setColor(Color.red);
for (int i=1;i<size;i++) g.drawLine(x[i],y[i],x[i-1],y[i-1]);
}
public void mousePressed(MouseEvent e){
x[size]=e.getX();
y[size]=e.getY();
size++;
}
public void mouseDragged(MouseEvent e){
y[size]=e.getY();
x[size]=e.getX();
size++;
repaint();
}
public void mouseEntered(MouseEvent e){
size=0;
y[size]=e.getY();
x[size]=e.getX();
repaint();
}
public void mouseExited (MouseEvent e){
size=0;
repaint();
}
public void mouseReleased (MouseEvent e){}
public void mouseClicked (MouseEvent e){
}
public void mouseMoved (MouseEvent e){}
}
public class JavaApplication6 {
public static void main(String[] args) {
JFrame win= new JFrame ("Target");
win.setSize(600,500);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.add(new Test());
win.setVisible(true);
}}
This same code worked at the school computer but when I got home and tried to do another example and it didn't really work so I decided to test this one and it doesn't work either.I would really appreciate some help and an explanation as to why repaint doesn't trigger.
Your primary problem is here...
public void MouseDemo() {
addMouseListener(this);
addMouseMotionListener(this);
}
This is a method, not a constructor, so it will never register your listeners. Instead, change it to...
public MouseDemo() {
addMouseListener(this);
addMouseMotionListener(this);
}
Or, based on you actually example code...
public Test() {
addMouseListener(this);
addMouseMotionListener(this);
}
java.awt.Canvas is a heavy weight component, AWT components don't always play nice with Swing, as they have no concept of z-ordering in the way that Swing implements it.
You'd be better off starting with a JPanel.
By convention, you should then override the paintComponent method and perform your custom painting within it, remembering to call super.paintComponent first
Because frame borders are inserted into the visible area of the frame, you "useable" area will be less then that specified by setSize, instead, you should override the getPreferredSize method of the JPanel and specify the "usable" area you prefer. From there, you can pack the frame around it.
To avoid any possible issues with threads, you should use EventQueue.invokeLater to start you UI in
For example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test extends JPanel implements MouseListener, MouseMotionListener {
int x[] = new int[1024];
int y[] = new int[1024];
int size = 0;
public Test() {
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 500);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
for (int i = 1; i < size; i++) {
g.drawLine(x[i], y[i], x[i - 1], y[i - 1]);
}
}
#Override
public void mousePressed(MouseEvent e) {
x[size] = e.getX();
y[size] = e.getY();
size++;
}
public void mouseDragged(MouseEvent e) {
y[size] = e.getY();
x[size] = e.getX();
size++;
repaint();
}
public void mouseEntered(MouseEvent e) {
System.out.println("Entered");
size = 0;
y[size] = e.getY();
x[size] = e.getX();
repaint();
}
public void mouseExited(MouseEvent e) {
size = 0;
repaint();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Test());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Position JTextField via moving Coordinates?

(The above image is taken from AutoCAD)
My application draws a line on a JPanel using two Point class variables: "startPoint" and "finishPoint".
"startPoint" is set from the first mouse click. Once a starting point has been established the finishPoint variable is set on the position of the cursor. Therefore the line moves/grows dynamically with the mouse movement until the "finishPoint" is finalised by a second mouse click.
During the period where a startPoint has been established and the line dynamically changes I would like to position a JTextField on the line midpoint (well... slightly off-center so it's not obscuring the line) if possible?
I know I'll get shouted at if I try and position a component without the use of a layout manager, but I can't see how a layout manager can help. I would like to position the JTextField using Coordinates. The only way I can think of doing that is to somehow add the textfield into a shape. Beyond that I'm at a loss.
Can someone put me in the right direction?
My code should anybody want to see it:
package Drawing;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* An extension to P2PLines. A line from point A to point B but with an animation.
*/
public class LineAnimation extends JPanel implements MouseListener, MouseMotionListener
{
private Graphics g;
private Point lineStart = new Point(0, 0);
private Point lineFinish = new Point(0, 0);
private boolean drawing;
int globalX = 0, globalY;
ArrayList<Line2D> edges = new ArrayList<>();
public LineAnimation()
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
drawing = false;
}
#Override public void mouseClicked(MouseEvent me) {}
#Override public void mousePressed(MouseEvent me)
{
if (drawing)
{
g = getGraphics(); // Get Graphics content
g.setColor(Color.black);
lineFinish.move(me.getX(), me.getY());
g.drawLine(lineStart.x, lineStart.y, me.getX(), me.getY());
edges.add(new Line2D.Float(lineStart.x, lineStart.y, lineFinish.x, lineFinish.y));
drawing = false;
g.dispose();
}
else
{
lineStart.move(me.getX(), me.getY());
drawing = true;
}
}
#Override public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawPreviousLine((Graphics2D)g);
if (drawing)
{g.drawLine(lineStart.x, lineStart.y, globalX, globalY);}
}
private void drawPreviousLine(Graphics2D g)
{
for(Line2D lines: edges)
{g.draw(lines);}
}
#Override
public void mouseMoved(MouseEvent me)
{
repaint();
globalX = me.getX();
globalY = me.getY();
}
#Override public void mouseReleased(MouseEvent me) {}
#Override public void mouseEntered(MouseEvent me) {}
#Override public void mouseExited(MouseEvent me) {}
#Override public void mouseDragged(MouseEvent me) {}
public static void main(String[] args)
{
JFrame frame = new JFrame("Drawing Frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
LineAnimation drawingFrame = new LineAnimation();
frame.add(drawingFrame);
frame.setVisible(true);
drawingFrame.addMouseListener(drawingFrame);
drawingFrame.addMouseMotionListener(drawingFrame);
}
}

how can I give the action to "MouseListener" to draw a shape in java?

this is my code
I want to draw the rectangle at the position that I clicked but it is not drawing any thing :( , I don't know how I giving the action to "MouseListener"
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Transparenttxom extends JPanel implements MouseListener {
Graphics g=null;
public void init(){
Transparenttxom panel=new Transparenttxom();
panel.addMouseListener(this);
}//end init
//********************************************************************
public void paint(Graphics g){
}
//********************************************************************
public void mouseClicked(MouseEvent e){
int mousex=e.getX();
int mousey=e.getY();
g.drawRect(20,20,mousex,mousey);
}//end mouseclicked method
//********************************************************************
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) {
Transparenttxom panel=new Transparenttxom();
JFrame frame = new JFrame("java lover");
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
thanks for helping.
I would start with the fact the Graphics g=null; and since you've never assigned it anything, it's likely to remain null.
Then I'd move onto the point where init is never called, but your init method scares me...
public void init(){
Transparenttxom panel=new Transparenttxom();
panel.addMouseListener(this);
}//end init
Why are you creating a new instance of Transparenttxom? Simple call addMouseListener(this)...
But even then, this...
public void paint(Graphics g){
}
Means nothing will ever get painting...
Start by taking a look at Performing Custom Painting for more details
Instead overriding paint, you should override paintComponent, making sure you call super.paintComponent before you do any painting of your own.
In your mouseClicked event you should define what you want painted and simply call repaint which will trigger a paint event which will, eventually, call your paintComponent where in which you paint stuff.
Updated with a basic example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Transparenttxom extends JPanel implements MouseListener {
private Point mousePoint;
public Transparenttxom() {
addMouseListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mousePoint != null) {
g.drawRect(20, 20, mousePoint.x - 20, mousePoint.y - 20);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void mouseClicked(MouseEvent e) {
mousePoint = e.getPoint();
repaint();
}//end mouseclicked method
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) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Transparenttxom());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Add listener like this:
public Transparenttxom() {
// TODO Auto-generated constructor stub
super();
this.addMouseListener(this);
}
Your init method never gets called.
and g is null!
and try this:
public void mouseClicked(MouseEvent e){
int mousex=e.getX();
int mousey=e.getY();
Graphics g = this.getGraphics();
g.drawRect(20,20,mousex,mousey);
}//end mouseclicked method
The whole code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Transparenttxom extends JPanel implements MouseListener {
Graphics g=null;
public Transparenttxom() {
// TODO Auto-generated constructor stub
super();
this.addMouseListener(this);
}
public void init(){
Transparenttxom panel=new Transparenttxom();
System.out.println("no");
panel.addMouseListener(this);
}//end init
//********************************************************************
public void paint(Graphics g){
}
//********************************************************************
public void mouseClicked(MouseEvent e){
int mousex=e.getX();
int mousey=e.getY();
Graphics g = this.getGraphics();
g.drawRect(20,20,mousex,mousey);
}//end mouseclicked method
//********************************************************************
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) {
Transparenttxom panel=new Transparenttxom();
JFrame frame = new JFrame("java lover");
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Check out Custom Painting Approaches for two common methods to do custom painting:
Keep an ArrayList of objects to paint
Paint onto a BufferedImage
In both examples the mouseReleased code actually saves the object to be painted. In your case you want to add the Rectangle on mousePressed.

How do I zoom on Swing components using AffineTransform?

I am trying to create a panel where I will have the possibility to zoom on custom made JComponent objects.
I have tried to call the scale() method in the AffineTransform class with different values, but I have not succeeded. My objects just disappear.
Below is my component that is used in the main frame class. Everything works except the zooming. Could some of you explain the concepts of AffineTransform. I donĀ“t think the JavaDoc explenation is enough for me.
Here is an executable SSCCE:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class JavaApplication1 extends JFrame {
public static void main(String[] args) {
new JavaApplication1();
}
private MyComponent myComponent = new MyComponent();
public JavaApplication1() throws HeadlessException {
this.setSize(400,400);
this.setVisible(true);
this.add(myComponent);
}
class MyComponent extends JComponent {
private int x, y;
private double scale=1;
private MouseAdapter mouseAdapter = new MouseAdapter();
private AffineTransform transform = new AffineTransform();
public MyComponent() {
this.addMouseListener(mouseAdapter);
this.addMouseWheelListener(mouseAdapter);
this.addMouseMotionListener(mouseAdapter);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.DARK_GRAY);
g2.fillRect(0, 0, 400, 400);
g2.setColor(Color.RED);
g2.setTransform(transform);
transform.scale(scale, scale);
g2.drawString("My String!", x, y);
}
private class MouseAdapter implements MouseWheelListener, MouseListener, MouseMotionListener {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
if(e.getWheelRotation() == 1) {
scale+=0.1;
}else {
scale-=0.1;
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
}
}
transform.scale accepts two double parameters, one for the x axis and the other for the y axis, being 1 the neutral value (no change in scale), and the two parameters the multipliers.
Ex: transform.scale(2,2) will show the component twice as big, while transform.scale(0.5,0.5) will show it twice as small.
http://docs.oracle.com/javase/6/docs/api/java/awt/geom/AffineTransform.html#scale(double, double)

JLabel mouse events for Drag and Drop

I want to enable the drag and drop feature over a JLabel by overriding mouse events over it , but when I define the drag and drop in mousePressed event ,the mouseReleased does not take effect on that JLabel. Am I doing something wrong ?
Thumbnails[I_Loop].setText("1");
Thumbnails[I_Loop].setTransferHandler(new TransferHandler("text"));
Thumbnails[I_Loop].addMouseListener( new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
System.out.println("here mouse released");
}
public void mousePressed(MouseEvent me) {
System.out.println("here mouse pressed");
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
});
*Thumbnails is array of JLabel
When running the program , the drag and drop works but the statement "here mouse released" does not get printed. However, When I remove the code responsible for DND from the mousePressed() method, "here mouse released" is printed.
What is the wrong in this code?
#Thomas is correct, but two alternatives are worth noting:
This example shows how to drag a component using JLayeredPane; this variation expands on the concept; this more recent example uses a similar approach.
The code below shows how to use a MouseMotionListener; this more complex example uses the same principle.
Code:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/5312702/230513 */
public class MouseDragTest extends JPanel {
private static final String TITLE = "Drag me!";
private static final int W = 640;
private static final int H = 480;
private Point textPt = new Point(W / 2, H / 2);
private Point mousePt;
public MouseDragTest() {
this.setFont(new Font("Serif", Font.ITALIC + Font.BOLD, 32));
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mousePt = e.getPoint();
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
textPt.setLocation(textPt.x + dx, textPt.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w2 = g.getFontMetrics().stringWidth(TITLE) / 2;
g.drawString(TITLE, textPt.x - w2, textPt.y);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new MouseDragTest());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
Well, if I remember correctly, the drag and drop machinery catches all mouse events and processes them itself. Thus, the normal MouseEvents are not thrown anymore. You'd need to register a DropTargetListener on the JLabel's DropTarget.
Does it have to be a JLabel? I made a class with a string that might get you started..
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class mainProgram extends JPanel implements Runnable
{
private static final long serialVersionUID = 1L;
public static boolean MOUSE_DOWN = false;
public static String str;
public mainProgram()
{
JFrame win = new JFrame("Window");
win.add(this);
win.setSize(700,500);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
str = "Drag me!";
new Thread(this).start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(MOUSE_DOWN)
{
g.drawString(str, MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y);
}
}
#Override
public void run()
{
Thread t = Thread.currentThread();
this.addMouseListener(new MouseListener()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
}
#Override
public void mouseEntered(MouseEvent arg0)
{
}
#Override
public void mouseExited(MouseEvent arg0)
{
}
#Override
public void mousePressed(MouseEvent arg0)
{
MOUSE_DOWN = true;
}
#Override
public void mouseReleased(MouseEvent arg0)
{
MOUSE_DOWN = false;
}
});
while(t==Thread.currentThread())
{
if(MOUSE_DOWN)
repaint();
try {Thread.sleep(10);}
catch (InterruptedException e) {e.printStackTrace();}
}
}
}

Categories