Drawing in a Paint Method - Java - java

I am only posting the relevant code. I am fairly new to java and right now I am building a program that will allow the user to use a draw method. However, when I click the button for drawing in the interface, it automatically generates a random line anywhere on the page and does not allow user interaction. I think the error is occurring in my mouseListener method, but I am not sure as this is my first time doing anything like this. Any help would be greatly appreciated. Thank you!
Also, the error that prints out is: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
public class SimplePaint extends JFrame {
JButton drawing = new JButton();
Line2D draw = new Line2D.Float();
Point start = null;
Point end = null;
public SimplePaint() {
JPanel panel = new JPanel() {
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
start = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
start = e.getPoint();
//start = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
end = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
end = e.getPoint();
repaint();
}
});
}
};
drawing.setText("Draw");
panel.add(drawing);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == drawing) {
draw = new Line2D.Float(start.x, start.y, end.x, end.y);
}
repaint();
}
};
drawing.addActionListener(actionListener);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(0, 250, 2000, 300);
g2.draw(draw);
}
}

Related

drag object using mouse Listener

I'm trying to create a program that able the user to drag and drop the oval around in the space. I was able to drag and drop but after I tried do it again on the second run, the oval jump all over the places. I was wondering if anyone know why this happen? Am i missing something? Thank you
public class MoveOval extends JFrame {
private Ellipse2D node = new Ellipse2D.Float(200,200,80,120);
private Point offset;
private int preX,preY;
private Image dbImage;
private Graphics dbg;
Adapter ma = new Adapter();
public static void main(String args[]){
JFrame frame = new MoveOval();
frame.setSize(600,600);
frame.setVisible(true);
}
public MoveOval(){
super("Move Oval");
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(ma);
addMouseMotionListener(ma);
}
private class Adapter extends MouseAdapter{
public void mousePressed(MouseEvent e){
if(node.contains(e.getPoint())){
preX = node.getBounds().x-e.getX();
preY = node.getBounds().y-e.getX();
offset = new Point(preX, preY);
}
}
public void mouseDragged(MouseEvent e){
if(node.contains(e.getPoint())){
updateLocation(e);
}
}
public void mouseReleased(MouseEvent e) {
offset=null;
}
}
public void updateLocation(MouseEvent e){
Point to = e.getPoint();
to.x += offset.x;
to.y += offset.y;
Rectangle bounds = node.getBounds();
bounds.setLocation(to);
node.setFrame(bounds);
repaint();
}
public void paint(Graphics g){
dbImage=createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g){
Graphics2D gd = (Graphics2D)g.create();
gd.setColor(Color.blue);
gd.fill(node);
}
}
Actually a very simple mistake and easy to fix.
public void mousePressed(MouseEvent e){
if(node.contains(e.getPoint())){
preX = node.getBounds().x-e.getX();
preY = node.getBounds().y-e.getX(); // <- That's the bad guy.
offset = new Point(preX, preY);
}
}
It has to be -e.getY() not -e.getX().

Java panel interface

Im trying to make a pline drawing program. when I try to repaint all of the lines(after creating a new one) only the last one is draw out.The problem might be in repainting.
Can someone see what I am doing wrong?
Code is here:
public class Kimp extends JFrame {
private ArrayList<Point[]> pointsArray = new ArrayList<>();
private Point points[] = new Point[10000];
private int pointCounter = 0;
public Kimp () {
panel paintArea = new panel();
add(paintArea, BorderLayout.CENTER);
}
private class panel extends JPanel {
public panel () {
HandlerClass handler = new HandlerClass();
this.addMouseListener(handler);
this.addMouseMotionListener(handler);
}
#Override
void paintComponent(Graphics g) {
super.paintComponent(g);
try {
for (Point[] p : pointsArray) {
for(int i = 0; i < p.length; i++) {
if (p[i].x == 0) {
continue;
} else {
if (p[i + 1].x == 0) {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i].x, p[i].y);
} else {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
}
}
}
}
points = preFill(points);
} catch (NullPointerException e) {
}
}
}
private class HandlerClass implements MouseListener , MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
points[pointCounter++] = e.getPoint();
}
#Override
public void mousePressed(MouseEvent e) {
points[pointCounter] = e.getPoint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public static Point[] preFill (Point[] points) {
for (int i = 0; i < points.length; i++) {
points[i] = new Point(-999,-999);
}
return points;
}
}
I quickly rewrote your code to simplify it as much as possible. You may be able to better understand the concepts behind it.
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Color;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Kimp {
public static void main(String[] args) {
JFrame frame = new JFrame("Kimp!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.add(new CanvasPanel());
frame.setVisible(true);
}
}
class CanvasPanel extends JPanel {
private final List<List<Point>> lines = new LinkedList<List<Point>>();
private List<Point> points = new LinkedList<Point>();
public CanvasPanel() {
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
for (List<Point> line : lines)
drawLine(line, g);
drawLine(points, g);
}
private void drawLine(List<Point> points, Graphics g) {
if (points.size() < 2) return;
Point p1 = points.get(0);
for (int i=1, n=points.size(); i<n; i++) {
Point p2 = points.get(i);
g.setColor(Color.BLUE);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
private MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (points.size() > 1) {
lines.add(points);
points = new LinkedList<Point>();
}
}
};
}
private ArrayList<Point[]> pointsArray = new ArrayList<>();
This is a list of Point[]. Here only one private Point points[] = new Point[10000]; is allocated. Which means that each time you add points into pointArray, you are adding the same instance of points.
When you change the elements of points, all the existing Point[] in pointArray is updated. Since all the elements are referring to the same points.
Allocate new Point[] when drawing a new line.
You are resetting your points array every time you painted it (preFillPoints() is called in paint()). Your pointsArray (which should be called pointsList for gods sake) is completely meaninless, you add the same points[] array each time the mouse is released.
The code makes no sense. You only need the list or the array. Not both. Declare a List<Point> (not Point[]) and just add a new Point every time the mouse moves.

Java Challenge on Permitting the User to Draw A Line

My question has been alluded to in java draw line as the mouse is moved, however, I have not advanced far enough into this book to have covered JPanels, JFrames and Points as stated by the prior programmer who asked this question.
Answering this question definitely would help most beginner programmers better understand the graphics class and drawing, an often intricate process, especially for beginners.
According to the text I am using (as I am learning Java on my own), this was the example of how to draw a line using Java:
/*
* LineTest
* Demonstrates drawing lines
*/
import java.awt.*;
public class LineTest extends Canvas {
public LineTest() {
super();
setSize(300, 200);
setBackground(Color.white);
}
public static void main(String args[]) {
LineTest lt = new LineTest();
GUIFrame frame = new GUIFrame("Line Test");
frame.add(lt);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g) {
g.drawLine(10, 10, 50, 100);
g.setColor(Color.blue);
g.drawLine(60, 110, 275, 50);
g.setColor(Color.red);
g.drawLine(50, 50, 300, 200);
}
}
The specification is:
Create an application that allows you to draw lines by clicking the initial
point and dragging the mouse to the second point. The application should
be repainted so that you can see the line changing size and position as you
are dragging the mouse. When the mouse button is released, the line is
drawn.
As you will recognize, running this program does not create any drawing by the user. I believe this error is encountered due to line 21: g.drawLine(x, y, x2, y2); being incorrect since this is the statement defining the drawing of the line.
Any help is greatly appreciated. Thank you in advance for all your time and cooperation regarding this matter.
My code to answer the question is:
import java.awt.*;
import java.awt.event.*;
public class LineDrawer extends Canvas
implements MouseListener, MouseMotionListener {
int x, y, x2, y2;
public LineDrawer() {
super();
setSize(300, 200);
setBackground(Color.white);
}
public void mouseClicked(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int x2 = me.getX();
int y2 = me.getY();
}
public void paint(Graphics g) {
g.drawLine(x, y, x2, y2);
g.setColor(Color.blue);
}
public void mousePressed(MouseEvent me) {
repaint();
}
public void mouseDragged(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
}
public static void main(String args[]) {
LineDrawer ld = new LineDrawer();
GUIFrame frame = new GUIFrame("Line Drawer");
frame.add(ld);
frame.pack();
frame.setVisible(true);
}
}
P.S.: I have been hesitant to ask for help since I am concerned that other programmers would answer with methods that I have not yet learned.
int x1, y1, x2, y2;
public void mousePressed(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
}
public void mouseDragged(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
// Now Paint the line
repaint();
}
Hope it helps.
Let's start with
public void mouseClicked(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int x2 = me.getX();
int y2 = me.getY();
}
You have previous declared x, y, x2 and y2, but in this method, you have overridden those decelerations with new ones, meaning that the previous declared variables will not be used and the event parameters will be ignored.
mouseClicked is fired AFTER a mousePressed and mouseReleased event, meaning that this is actually when the user has released the mouse button.
Extreme Coder has pointed out that MouseClicked is only fired when the mouse button is pressed and released at the same point, i.e. no dragging is involved - it's still not the right method to use, but the clarification is nice
What you should do is...
On mousePressed store the x, y position of the click and on mouseReleased store the x2, y2 position.
On the mouseDragged event, you should update the x2, y2 values and call repaint
public void mousePressed(MouseEvent me) {
// Mouse is down, but hasn't yet being released...
x = me.getX();
y = me.getY();
// We need to "override" any previous values...
x2 = x;
y2 = y;
repaint();
}
public void mouseDragged(MouseEvent me) {
x2 = me.getX();
y2 = me.getY();
repaint();
}
public void mouseReleased(MouseEvent me) {
// Here I would store the points so I could re-draw each new line...
}
Instead of using x, y, x2 and y2, it might be better to use two arrays, ie
private int[] startPoint;
private int[] endPoint;
Then you could do something like...
public void mousePressed(MouseEvent me) {
// Mouse is down, but hasn't yet being released...
startPoint = new int[2];
startPoint[0] = me.getX();
startPoint[1] = me.getY();
endPoint = startPoint;
repaint();
}
public void mouseDragged(MouseEvent me) {
endPoint = new int[2];
endPoint[0] = me.getX();
endPoint[1] = me.getY();
repaint();
}
Now I prefer paintComponent from JComponent, but I'll stick to you example for now..
public void paint(Graphics g) {
super.paint(g); // This is super important...
if (startPoint != null && endPoint != null && startPoint.length == 2 && endPoint.length == 2) {
g.drawLine(startPoint[0], startPoint[1], endPoint[0], endPoint[1]);
}
}
Additional
This is of some concern...
public void paint(Graphics g) {
g.drawLine(x, y, x2, y2);
g.setColor(Color.blue);
}
The order of operation is VERY important. Setting the color AFTER you've painted the line with have no effect on you paint operations (but may effect paint operations that occur after you).
Also, you MUST call super.paint(g) - this is super important...
Examples
A "basic" example, using int[] arrays for point storage...
public class BasicLineDraw {
public static void main(String[] args) {
new BasicLineDraw();
}
public BasicLineDraw() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawLinePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawLinePane extends JPanel {
private int[] startPoint;
private int[] endPoint;
private List<int[][]> lines;
public DrawLinePane() {
lines = new ArrayList<int[][]>(25);
MouseAdapter handler = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
startPoint = new int[]{e.getX(), e.getY()};
endPoint = startPoint;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
endPoint = new int[]{e.getX(), e.getY()};
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (startPoint != null && endPoint != null && startPoint.length == 2 && endPoint.length == 2) {
lines.add(new int[][]{startPoint, endPoint});
}
startPoint = null;
endPoint = null;
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (startPoint != null && endPoint != null && startPoint.length == 2 && endPoint.length == 2) {
g2d.setColor(Color.RED);
g2d.drawLine(startPoint[0], startPoint[1], endPoint[0], endPoint[1]);
}
g2d.setColor(Color.BLUE);
for (int[][] line : lines) {
g2d.drawLine(line[0][0], line[0][1], line[1][0], line[1][1]);
}
g2d.dispose();
}
}
}
And a more advanced example, using Point and Java's 2D Graphics API
public class LineDrawer {
public static void main(String[] args) {
new LineDrawer();
}
public LineDrawer() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawLinePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawLinePane extends JPanel {
private Point anchor;
private Point lead;
private List<Line2D> lines;
public DrawLinePane() {
lines = new ArrayList<Line2D>(25);
MouseAdapter handler = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
lead = null;
anchor = e.getPoint();
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
lead = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (lead != null && anchor != null && !anchor.equals(lead)) {
lines.add(new Line2D.Float(anchor, lead));
}
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
if (lead != null && anchor != null) {
Composite composite = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25f));
g2d.draw(new Line2D.Float(anchor, lead));
g2d.setComposite(composite);
}
for (Line2D line : lines) {
g2d.draw(line);
}
g2d.dispose();
}
}
}

Why doesn't the circle appear when I click?

I have to use the Console class in HoltSoft's Ready to Program. I'm not supposed to use swing, so if I can't do it without swing, kindly ignore this.
//imports
import java.awt.*;
import java.awt.event.*;
import hsa.*;
public class DrawLines extends Panel implements MouseListener, MouseMotionListener
{
Console c;
int startX, startY, prevX, prevY; //mouse coordinates
private boolean dragging; //whether or not the mouse is being dragged
MouseEvent e;
public DrawLines ()
{
c = new Console (); //creates console window
addMouseListener (this); //detects press/release
addMouseMotionListener (this);//detects dragging
}
public void mousePressed (MouseEvent e)
{
while (!dragging)
{
try
{
startX = e.getX ();//get the
startY = e.getY ();//original co-ordinates
dragging = true;
}
catch (NullPointerException q) //because I kept getting this error
{
}
}
}
public void mouseDragged (MouseEvent e)
{
while (dragging)
{
try
{
int x = e.getX (); //gets and
int y = e.getY (); //updates
prevX = x; //the mouse
prevY = y; //coordinates
}
catch (NullPointerException q)//because I kept getting this error
{
}
}
}
public void mouseReleased (MouseEvent e)
{
dragging = false; //stopped dragging
}
public void drawTheLine ()
{
mousePressed (e);
mouseDragged (e);
c.setColor (Color.black);
c.fillOval (prevX, prevY, 50, 50); //draws a circle where the mouse is
mouseReleased (e);
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseExited (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public static void main (String[] args)
{
DrawLines a = new DrawLines ();
a.drawTheLine ();
}
}
I've been trying to use MouseListener and MouseMotionListener in Console. At first, the program kept giving me errors, so I added the try/catch structures. Now it doesn't crash, but nothing appears on the screen. Why? Help?
If I shouldn't use try/catch to just ignore it, what should I do?
I'm not allowed to use anything other than Console() for this program. It's a course assignment.
Look at this:
public void drawTheLine ()
{
while (true)
{
mousePressed (e);
mouseDragged (e);
c.setColor (Color.black);
c.fillOval (prevX, prevY, 50, 50); //draws a circle where the mouse is
mouseReleased (e);
}
}
The parameter "e" you're passing is null. It is declared here:
public class DrawLines extends Panel
implements MouseListener, MouseMotionListener
{
MouseEvent e; // IT IS NEVER SET TO ANYTHING! IT IS NULL!!!
Somewhere in your constructor you should do this so it's no longer null:
e = (something);
Swing is an event driven system and is a single threaded system.
This means that your application "waits" for events to occur (which is taken care for you by the Event Dispatching Thread) and that anyone that blocks the EDT, like, loops, long running processes or blocking IO, will prevent you application from receiving notification of those events, making impossible for you application to run.
So, if we have a look at this...
while (true)
{
mousePressed (e);
mouseDragged (e);
c.setColor (Color.black);
c.fillOval (prevX, prevY, 50, 50);
mouseReleased (e);
}
}
It suggest that...one, you don't understand how events are generated in Swing and two, how the EDT actually works.
Unlike some UI frameworks, you are not required to implement a event loop, this is taken care of you by Swing. Blocking the EDT like this, will prevent it for processing events
Instead, remove the drawLineMethod as it is doing absolute nothing for you and replace you main method with something like...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawLines());
// I prefer pack, but you've not specified a preferred size for your panel...
//frame.pack();
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Now. I have no idea what the Console class is or does, but in your mouse event methods, you will need to update it so that it can update it's output...
Updated with example
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawPane extends JPanel {
private Point center;
private int radius;
public DrawPane() {
MouseAdapter handler = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
center = e.getPoint();
radius = 0;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
int width = Math.max(e.getX(), center.x) - Math.min(e.getX(), center.x);
int height = Math.max(e.getY(), center.y) - Math.min(e.getY(), center.y);
radius = Math.max(width, height);
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (center != null) {
g.setColor(Color.RED);
g.fillOval(center.x - 2, center.y - 2, 4, 4);
g.drawOval(center.x - (radius / 2), center.y - (radius / 2), radius, radius);
}
}
}
}
I would suggest that you take the time to have a read through...
Creating a GUI with Swing to get an understanding of the overall basics of Swing
Performing Custom Painting to get an understanding of how custom painting is actually performed in Swing
Painting in AWT and Swing as all developers wishing to perform custom painting in Swing need to understand how this works...
Update with a pure AWT version
As it was pointed out to me that the OP was using AWT instead of Swing, why, cause they seem to be able to ...
public class DrawCircleAWT {
public static void main(String[] args) {
new DrawCircleAWT();
}
public DrawCircleAWT() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame frame = new Frame("Testing");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setLayout(new BorderLayout());
frame.add(new DrawPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawPane extends Panel {
private Point center;
private int radius;
public DrawPane() {
MouseAdapter handler = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
center = e.getPoint();
radius = 0;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
int width = Math.max(e.getX(), center.x) - Math.min(e.getX(), center.x);
int height = Math.max(e.getY(), center.y) - Math.min(e.getY(), center.y);
radius = Math.max(width, height);
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (center != null) {
g.setColor(Color.RED);
g.fillOval(center.x - 2, center.y - 2, 4, 4);
g.drawOval(center.x - (radius / 2), center.y - (radius / 2), radius, radius);
}
}
}
}

Why are only the co-ordinates of the mouse displayed?

when the Thread thread is running, (after clicking record) it only displays the position the mouse was in when the thread started? how can i make it constantly update, displaying where the mouse is even if i move it around the frame?
#Override public void actionPerformed(ActionEvent e)
{
thread = new Thread(this);
if(e.getSource() == record)
{
thread.start();
System.out.println("record");
}
if(e.getSource() == stopRecording)
{
setVisible(false);
System.out.println("stop recording");
}
}
#Override public void run()
{
setTitle("979");
setSize(screen.width, screen.height);
addMouseListener(this);
setLocationRelativeTo(null);
setLayout(transFlo);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(stopRecording);
setOpacity(0.50f);
setVisible(true);
while(true)
{
repaint();
}
}
#Override public void paint(Graphics g)
{
g.drawString(mousePOS + x + space + y, 250, 250);
}
Okay, just to reiterate; PLEASE read The Event Dispatching Thread,
then read Concurrency in Swing
and finally have a read of How to Write a Mouse Listener
ADDINTIONAL
If you want to monitor the global mouse events (all mouse events that pass through the system), then you will want to take a look at Toolkit.addAWTEventListener
This will allow you to monitor all the mouse events without the need to attach mouse listeners to all the components
SIMPLE MOUSE EXAMPLE
Here is a simple example of a panel that monitors the mouse :P
public class CrayPanel extends javax.swing.JPanel implements MouseMotionListener, MouseListener {
private List<Point> lstPoints;
/**
* Creates new form CrayPanel
*/
public CrayPanel() {
lstPoints = new ArrayList<Point>(25);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (lstPoints.size() > 1) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
Point startPoint = lstPoints.get(0);
for (int index = 1; index < lstPoints.size(); index++) {
Point toPoint = lstPoints.get(index);
g2d.drawLine(startPoint.x, startPoint.y, toPoint.x, toPoint.y);
startPoint = toPoint;
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
lstPoints.add(e.getPoint());
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
lstPoints.clear();
lstPoints.add(e.getPoint());
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
lstPoints.add(e.getPoint());
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
lstPoints.add(e.getPoint());
repaint();
}
}
I put together another example. This is essentially a mouse monitor, it shows that, if done correctly, you don't need the Thread
public class MouseFrame extends javax.swing.JFrame implements AWTEventListener, ActionListener {
private boolean monitor = false;
private Point mousePoint;
/**
* Creates new form MouseFrame
*/
public MouseFrame() {
setLayout(new GridBagLayout());
JButton btnToggle = new JButton("Start");
add(btnToggler);
btnToggle.addActionListener(this);
setSize(400, 400);
}
public void actionPerformed(java.awt.event.ActionEvent evt) {
monitor = !monitor;
if (monitor) {
btnTrigger.setText("Stop");
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_MOTION_EVENT_MASK);
} else {
btnTrigger.setText("Start");
Toolkit.getDefaultToolkit().removeAWTEventListener(this);
}
}
#Override
public void paint(Graphics grphcs) {
super.paint(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
if (monitor) {
g2d.setColor(Color.RED);
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString(mousePoint.x + "x" + mousePoint.y, 25, fm.getHeight() + 25);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MouseFrame().setVisible(true);
}
});
}
#Override
public void eventDispatched(AWTEvent evt) {
if (evt instanceof MouseEvent) {
MouseEvent me = (MouseEvent) evt;
mousePoint = SwingUtilities.convertPoint(me.getComponent(), me.getPoint(), this);
repaint();
}
}
}

Categories