Rotating Rectangle with mouse isn't consistant - java

The following example draws 2 Rectangles.
Within the paintComponent() method, the first Rectangle is draw normally and the second Rectangle is rotated.
Rotation is based on the mouse movement. If the mouse is clicked on the rectangle and then moved
in a circular fashion, the 2nd Rectangle rotations as expected, but as the mouse rotations around, the rotation of the Rectangle isn't always in sync with the mouse.
I suspect this is all related to the angle calculation. Any suggestions on how to get the rotation of the Rectangle to be in sync with the mouse movement?
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class SimpleTest extends JComponent
{
static int x = 200,y = 200 , width = 100 , height = 30;
static Vector objectsToDraw = new Vector();
static int mouseClickX, mouseClickY, mouseX, mouseY = 0;
static double angle;
public static void main(String[] args)
{
//Create Frame
JFrame window = new JFrame();
//Attach Mouse Listeners.
window.addMouseMotionListener(new MouseMotionListener()
{
#Override
public void mouseMoved(MouseEvent e) { }
#Override
public void mouseDragged(MouseEvent e)
{
// System.out.println("Dragged");
System.out.println("Dragged at X :" + e.getX() + " Y : " + e.getY());
calculateAngle(e.getX(), e.getY());
mouseX = e.getX();
mouseY = e.getY();
window.repaint();
}
});
window.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 e)
{
System.out.println("Pressed at X :" + e.getX() + " Y : " + e.getY());
mouseClickX = e.getX();
mouseClickY = e.getY();
}
#Override
public void mouseReleased(MouseEvent arg0)
{
System.out.println("Released");
mouseClickX = 0;
mouseClickY = 0;
window.repaint();
}
});
//show Window
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 800, 800);
window.getContentPane().add(new SimpleTest());
window.setVisible(true);
}
public static void calculateAngle (int x, int y)
{
int deltaX = x - 250;//Rectangle Center X
int deltaY = y - 200;//Rectangle Center Y
angle = Math.toDegrees(Math.atan2(deltaY, deltaX));
System.out.println("Angle = " + angle);
}
#Override //Works
public void paintComponent(Graphics g)
{
System.out.println("paintComponent() - using angle : " + angle);
Graphics2D g2d = (Graphics2D)g;
AffineTransform old = g2d.getTransform();
g.drawRect(x, y, width, height);
g2d.rotate(Math.toRadians(angle), 250, 215);
Rectangle rect2 = new Rectangle(200, 200, 100, 30);
g.drawRect(x, y, width, height);
g2d.setTransform(old);
}
}

For one, you're adding the MouseListener to the wrong component. Don't add it to the window but rather to the JComponent that does the drawing. Otherwise, your mouse positioning will be off by however large the menu bar is, or any other components that changes the position of the drawing component (the component that uses the mouse positions) relative to the JFrame (your component that currently gets the mouse positions).
e.g.,
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleTest2 extends JPanel {
// avoiding "magic" numbers
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
public static final int RECT_X = 200;
public static final int RECT_Y = RECT_X;
public static final int RECT_WIDTH = 100;
public static final int RECT_HEIGHT = 30;
private double angle;
private static void createAndShowGui() {
SimpleTest2 mainPanel = new SimpleTest2();
JFrame frame = new JFrame("Simple Test 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack(); // let the GUI size itself
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
public SimpleTest2() {
// using an adapter is a nice clean way of avoiding empty method bodies
MouseAdapter myMouse = new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
calculateAngle(e.getX(), e.getY());
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
calculateAngle(e.getX(), e.getY());
repaint();
}
};
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
public void calculateAngle(int x, int y) {
// get rid of "magic" numbers
int deltaX = x - (RECT_X + RECT_WIDTH / 2);// Rectangle Center X
int deltaY = y - (RECT_Y + RECT_HEIGHT / 2);// Rectangle Center Y
angle = Math.toDegrees(Math.atan2(deltaY, deltaX));
}
#Override
public Dimension getPreferredSize() {
// better way to size the drawing component
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // ***don't forget this guy***
Graphics2D g2d = (Graphics2D) g;
// for smoother rendering
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform old = g2d.getTransform();
g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT);
g2d.rotate(Math.toRadians(angle), 250, 215);
// Rectangle rect2 = new Rectangle(200, 200, 100, 30);
g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT);
g2d.setTransform(old);
}
}

Related

Drawing multiple rectangles on a panel in Swing

I'm trying to draw multiple rectangles on a panel. I created an ArrayList<Shape> and initialized in my constructor. In my paintComponent method, I draw a rectangle and then add it to the ArrayList. But when I do that, the drawing outcome on my panel turns out weird. As I drag to draw my first rectangle, I get this:
Here's part of my code:
public class MyMouseListener extends MouseAdapter {
#Override
public void mousePressed(final MouseEvent theEvent) {
myStartPoint = theEvent.getPoint();
repaint();
}
#Override
public void mouseReleased(final MouseEvent theEvent) {
myEndPoint = theEvent.getPoint();
repaint();
}
}
public class MyMouseMotionHandler extends MouseMotionAdapter {
#Override
public void mouseDragged(final MouseEvent theEvent) {
myEndPoint = theEvent.getPoint();
repaint();
}
}
/**
* Paints some rectangles.
*
* #param theGraphics The graphics context to use for painting.
*/
#Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
// for better graphics display
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(51, 0, 111));
g2d.setStroke(new BasicStroke(3));
final double x = myStartPoint.getX();
final double y = myStartPoint.getY();
final double xEnd = myEndPoint.getX();
final double yEnd = myEndPoint.getY();
if (xEnd> x && yEnd > y) {
final Shape rectangle = new Rectangle2D.
Double(x, y, xEnd - x, yEnd - y);
g2d.draw(rectangle);
myDrawings.add(rectangle);
}
for (Shape s : myDrawings) {
g2d.draw(s);
}
}
Don't do any code logic within paintComponent -- that method is for drawing and drawing only, and that is the source of your bug. Add the rectangle to the ArrayList in the mouse listener, on mouse release.
When I have done a similar project, I usually have one Rectangle field that I use to draw with the mouse listener on mouse drag, and which is draw within paintComponent. Then on mouse release I place that rectangle into the ArrayList, and set the class field as null.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class RectangleDraw extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Color TEMP_RECT_COLOR = Color.LIGHT_GRAY;
private static final Color SHAPE_COLOR = Color.RED;
private Rectangle tempRect = null;
private List<Shape> shapes = new ArrayList<>();
public RectangleDraw() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// draw the temporary rectangle if not null
if (tempRect != null) {
g2.setColor(TEMP_RECT_COLOR);
g2.draw(tempRect);
}
// draw all the rectangles in the list
g2.setColor(SHAPE_COLOR);
for (Shape shape : shapes) {
g2.draw(shape);
}
}
// size the GUI to my specification
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// My mouse listener and mouse motion listener
private class MyMouse extends MouseAdapter {
private Point p1; // start point
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
// create temporary rectangle
tempRect = createRectangle(e);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
tempRect = null; // null temp rectangle and
// add rectangle to List
shapes.add(createRectangle(e));
repaint();
}
// create a rectangle from start point and current point
private Rectangle createRectangle(MouseEvent e) {
Point p2 = e.getPoint();
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
Rectangle rect = new Rectangle(x, y, w, h);
return rect;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Rectangle Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RectangleDraw());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Draw ring with given thickness, position, and radius. (Java2D)

I need to draw a ring, with given thickness, that looks something like this:
The center must be transparent, so that it doesn't cover previously drawn shapes. (or other rings) I've tried something like this:
//g is a Graphics2D object
g.setColor(Color.RED);
g.drawOval(x,y,width,height);
g.setColor(Color.WHITE);
g.drawOval(x+thickness,y+thickness,width-2*thickness,height-2*thickness);
which draws a satisfactory ring, but it covers other shapes; the interior is white, not transparent. How can I modify/rewrite my code so that it doesn't do that?
You can create an Area from an Ellipse2D that describes the outer circle, and subtract the ellipse that describes the inner circle. This way, you will obtain an actual Shape that can either be drawn or filled (and this will only refer to the area that is actually covered by the ring!).
The advantage is that you really have the geometry of the ring available. This allows you, for example, to check whether the ring shape contains a certain point, or to fill it with a Paint that is more than a single color:
Here is an example, the relevant part is the createRingShape method:
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class RingPaintTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RingPaintTestPanel p = new RingPaintTestPanel();
f.getContentPane().add(p);
f.setSize(800,800);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class RingPaintTestPanel extends JPanel
{
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.RED);
g.drawString("Text", 100, 100);
g.drawString("Text", 300, 100);
Shape ring = createRingShape(100, 100, 80, 20);
g.setColor(Color.CYAN);
g.fill(ring);
g.setColor(Color.BLACK);
g.draw(ring);
Shape otherRing = createRingShape(300, 100, 80, 20);
g.setPaint(new GradientPaint(
new Point(250, 40), Color.RED,
new Point(350, 200), Color.GREEN));
g.fill(otherRing);
g.setColor(Color.BLACK);
g.draw(otherRing);
}
private static Shape createRingShape(
double centerX, double centerY, double outerRadius, double thickness)
{
Ellipse2D outer = new Ellipse2D.Double(
centerX - outerRadius,
centerY - outerRadius,
outerRadius + outerRadius,
outerRadius + outerRadius);
Ellipse2D inner = new Ellipse2D.Double(
centerX - outerRadius + thickness,
centerY - outerRadius + thickness,
outerRadius + outerRadius - thickness - thickness,
outerRadius + outerRadius - thickness - thickness);
Area area = new Area(outer);
area.subtract(new Area(inner));
return area;
}
}
You can use the Shape and Area classes to create interesting effects:
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.net.*;
public class Subtract extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int size = 100;
int thickness = 10;
int innerSize = size - (2 * thickness);
Shape outer = new Ellipse2D.Double(0, 0, size, size);
Shape inner = new Ellipse2D.Double(thickness, thickness, innerSize, innerSize);
Area circle = new Area( outer );
circle.subtract( new Area(inner) );
int x = (getSize().width - size) / 2;
int y = (getSize().height - size) / 2;
g2d.translate(x, y);
g2d.setColor(Color.CYAN);
g2d.fill(circle);
g2d.setColor(Color.BLACK);
g2d.draw(circle);
g2d.dispose();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Subtract");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Subtract());
frame.setLocationByPlatform( true );
frame.setSize(200, 200);
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Using an Area you can also add multiple Shapes together or get the intersection of multiple Shapes.
You could use graphics.setStroke(...) for this. This way the center will be fully transparent and therefore won't cover previously drawn shapes. In my example I had to do some additional calculations because of this method though, to make sure the displayed x and y coordinates are actually the same as the ones of the Ring instance:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example {
public Example() {
ArrayList<Ring> rings = new ArrayList<Ring>();
rings.add(new Ring(10, 10, 100, 20, Color.CYAN));
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gg = (Graphics2D) g.create();
gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Ring ring : rings) {
// Previously drawn
gg.setColor(Color.BLACK);
String str = "Hello!";
gg.drawString(str, ring.getX() + (ring.getWidth() - gg.getFontMetrics().stringWidth(str)) / 2,
ring.getY() + ring.getHeight() / 2 + gg.getFontMetrics().getAscent());
// The actual ring
ring.draw(gg);
}
gg.dispose();
}
};
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
class Ring {
private int x, y, width, height, thickness;
private Color color;
public Ring(int x, int y, int width, int height, int thickness, Color color) {
setX(x);
setY(y);
setWidth(width);
setHeight(height);
setThickness(thickness);
setColor(color);
}
public Ring(int x, int y, int radius, int thickness, Color color) {
this(x, y, radius * 2, radius * 2, thickness, color);
}
public void draw(Graphics2D gg) {
Stroke oldStroke = gg.getStroke();
Color oldColor = gg.getColor();
gg.setColor(Color.BLACK);
gg.setStroke(new BasicStroke(getThickness()));
gg.drawOval(getX() + getThickness() / 2, getY() + getThickness() / 2, getWidth() - getThickness(),
getHeight() - getThickness());
gg.setColor(getColor());
gg.setStroke(new BasicStroke(getThickness() - 2));
gg.drawOval(getX() + getThickness() / 2, getY() + getThickness() / 2, getWidth() - getThickness(),
getHeight() - getThickness());
gg.setStroke(oldStroke);
gg.setColor(oldColor);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getThickness() {
return thickness;
}
public void setThickness(int thickness) {
this.thickness = thickness;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}

Preventing Dotted Lines When Mouse is Moved Fast

Does anyone know how to draw solid lines when the mouse is rapidly moved?
When I move the mouse slowly the line is drawn solid, but when the mouse is moved quickly the line is drawn like a dotted line, as shown here.
The code to draw the lines is currently this:
private final class MouseL extends MouseAdapter implements MouseMotionListener
{
#Override
public void mouseClicked(MouseEvent e)
{
Point p = e.getPoint();
int half = brushDiameter / 1200;
Graphics2D g = getImage().createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setPaint(getColor());
g.fillOval(p.x - half, p.y - half, brushDiameter, brushDiameter);
g.dispose();
repaint(p.x - half, p.y - half, brushDiameter, brushDiameter);
}
#Override
public void mouseDragged(MouseEvent e)
{
mouseClicked(e);
}
But i would like to change it so that the line appears solid. Any help to achieve this is greatly appreciated thanks.
Simple: If you want to draw curves, don't draw individual points or ovals. Instead connect adjacent points with a line using g.drawLine(...). If you want a thicker curve, change the Graphics2D's Stroke width.
For example:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class DrawCurve extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color CURRENT_PTS_COLOR = Color.BLUE.brighter().brighter();
public static final Color IMG_COLOR = Color.RED;
public static final Stroke IMG_STROKE = new BasicStroke(4f);
private static final Color FILL_COLOR = Color.WHITE;
private BufferedImage img = null;
private List<Point> currentPts = new ArrayList<>();
public DrawCurve() {
img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setBackground(FILL_COLOR);
g2.clearRect(0, 0, PREF_W, PREF_H);
g2.dispose();
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, null);
}
Graphics2D g2 = (Graphics2D) g;
g2.setColor(CURRENT_PTS_COLOR);
for (int i = 1; i < currentPts.size(); i++) {
int x1 = currentPts.get(i - 1).x;
int y1 = currentPts.get(i - 1).y;
int x2 = currentPts.get(i).x;
int y2 = currentPts.get(i).y;
g2.drawLine(x1, y1, x2, y2);
}
}
private class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
currentPts = new ArrayList<>();
currentPts.add(e.getPoint());
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
currentPts.add(e.getPoint());
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
currentPts.add(e.getPoint());
Graphics2D g2 = img.createGraphics();
g2.setColor(IMG_COLOR);
g2.setStroke(IMG_STROKE);
for (int i = 1; i < currentPts.size(); i++) {
int x1 = currentPts.get(i - 1).x;
int y1 = currentPts.get(i - 1).y;
int x2 = currentPts.get(i).x;
int y2 = currentPts.get(i).y;
g2.drawLine(x1, y1, x2, y2);
}
g2.dispose();
currentPts.clear();
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawCurve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawCurve());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

JLabel goes out of alignment (aka funky) when overlaying a rectangle on it

I have a GUI I am making for the popular software ImageMagick in Java SWING.
Now, I am implementing the Crop feature into it and was trying to implement a drawable box to denote the region to be cropped.
The issue is that although I have gotten the rectangle to draw on the JLabel, the JLabel itself starts to move around once I finish painting the graphics on it.
As an example, here is a screenshot of the app before and after the selection is made.
Here is the code for the MouseReleased() event listener
private void input_showerMouseReleased(java.awt.event.MouseEvent evt) {
end_x = evt.getX();
end_y = evt.getY();
paint(input_shower.getGraphics());
input_shower.revalidate();
}
Here is the code for the paint() method
public void paint(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(5));
Rectangle2D.Double rectangle = new Rectangle2D.Double(start_x, start_y, (end_x - start_x), (end_y - start_y));
g2.draw(rectangle);
}
Are there any ideas as to why this is happening and any possible solutions?
This is dangerous code:
private void input_showerMouseReleased(java.awt.event.MouseEvent evt) {
end_x = evt.getX();
end_y = evt.getY();
paint(input_shower.getGraphics());
input_shower.revalidate();
}
since you're painting directly to a component with a Graphics object that was not given to you by the JVM. Just don't do this, and instead paint passively.
Instead use end_x and end_y in your listened to jcomponent's paintComponent method and draw with that.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class PaintComponentCorrect extends JPanel {
public static final String BULL_FIGHT = "https://duke.kenai.com/misc/Bullfight.jpg";
private static final Color RECT_COLOR = new Color(150, 150, 255);
private int startX;
private int startY;
private int endX;
private int endY;
private BufferedImage img;
public PaintComponentCorrect() throws IOException {
URL url = new URL(BULL_FIGHT);
img = ImageIO.read(url);
MyMouseAdapt myMouseAdapt = new MyMouseAdapt();
addMouseListener(myMouseAdapt);
addMouseMotionListener(myMouseAdapt);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, null);
}
g.setColor(RECT_COLOR);
int x = Math.min(startX, endX);
int y = Math.min(startY, endY);
int width = Math.abs(startX - endX);
int height = Math.abs(startY - endY);
g.drawRect(x, y, width, height);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || img == null) {
return super.getPreferredSize();
}
return new Dimension(img.getWidth(), img.getHeight());
}
private class MyMouseAdapt extends MouseAdapter {
private BufferedImage subImg;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
startX = e.getX();
startY = e.getY();
endX = startX;
endY = startY;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
endX = e.getX();
endY = e.getY();
repaint();
int x = Math.min(startX, endX);
int y = Math.min(startY, endY);
int w = Math.abs(startX - endX);
int h = Math.abs(startY - endY);
subImg = img.getSubimage(x, y, w, h);
ImageIcon icon = new ImageIcon(subImg);
JOptionPane.showMessageDialog(PaintComponentCorrect.this, icon);
}
#Override
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
repaint();
}
}
private static void createAndShowGui() {
PaintComponentCorrect mainPanel = null;
try {
mainPanel = new PaintComponentCorrect();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("PaintComponent Correct");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
public void paint(Graphics g) {
super.paintComponents(g);
Custom painting is done by overriding the paintComponent() method.
You then invoke super.paintComponent(), not "paintComponents" with an "s"
For example check out Custom Painting Approaches. The code isn't designed to do what you want, but it does show how to draw a Rectangle on a component using the above suggestion.

Using listeners and mouse pointer location to check if pointer is inside of a circle

I'm trying to make it so a line of text is drawn on the point of the cursor that states if the cursor is inside or outside of the drawn circle. I'm not entirely sure how to do that and I don't think that the global X and Y coordinates I've made are working properly.
Does anyone know of a way to some how trigger the string to be drawn when the cursor is in or out of the circle? I'm still sort of new to Java.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseCircleLocation extends JPanel {
boolean insideCircleStatus;
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
public MouseCircleLocation() {
//the listener that checks if the mouse if moving.
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
//gets the location of the mouse.
int x = e.getX();
int y = e.getY();
//simple check to see if the mouse location is inside the circle area.
if ( (Math.pow((x - 100), 2)) + (Math.pow((y - 60), 2)) < (Math.pow((50), 2))){
insideCircleStatus = true;
}
else{
insideCircleStatus = false;
}
}
});
}
//basic frame setup.
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Location");
frame.add(new MouseCircleLocation());
frame.setSize(210, 190);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//draws the circle.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (insideCircleStatus = true){
g.drawString("Point is inside the circle", x, y);
System.out.println("Point is inside the circle");
}
if (insideCircleStatus = false){
g.drawString("Point is outside the circle", x, y);
System.out.println("Point is outside the circle");
}
g.setColor(Color.BLACK);
g.drawOval(100 - 50, 60 - 50, 50 *2, 50 * 2);
}
}
One thing you're forgetting to do is call repaint(). Just because the value of insideCircleStatus changes, doesn't make it automatically repaint(), so you'll want to call repaint() inside the MouseListener
Also, you could use the Shape interface and the method contains for example
Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 200, 200);
...
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
if (circle.contains(e.getPoint())) {
System.out.println("Click within Circle");
}
}
});
See full example using MouseMotionListener and the API - Also See Ellips2D
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestShapeContains extends JPanel {
private static final int D_W = 500;
private static final int D_H = 500;
Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 300, 300);
Point p = new Point();
private boolean insideCircle = false;
public TestShapeContains() {
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent e) {
if (circle.contains(e.getPoint())) {
insideCircle = true;
} else {
insideCircle = false;
}
p = e.getPoint();
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(circle);
if (insideCircle) {
g.drawString("Mouse in Circle at point " + (int)p.getX() + ", " + (int)p.getY(),
(int)p.getX(), (int)p.getY());
} else {
g.drawString("Mouse outside Circle at point " + (int)p.getX() + ", " + (int)p.getY(),
(int)p.getX(), (int)p.getY());
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new TestShapeContains());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Categories

Resources