Java Graphics2D mouse pattern drawing - java

I have a GUI with a panel where I draw. Whatever mouse pattern I do is repeated in every sector which is divided by two lines. However, I am able to do this because my paintComponen method does not invoke super.paintComponent. If I actually do invoke the method I get only a single point whenever i drag my mouse. How should i go about it?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import javax.swing.JPanel;
public final class DisplayPanel extends JPanel
{
private boolean dragging;
private Point draw;
private Line2D sectorLine;
private int sectors;
public void init()
{
DisplayListener listener = new DisplayListener();
addMouseListener(listener);
addMouseMotionListener(listener);
setOpaque(true);
setBackground(Color.BLACK);
setSize(900,900);
setVisible(true);
}
//performs the drawing on the display panel
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
sectorLine = new Line2D.Double(getWidth()/2, 0, getWidth()/2, getHeight());
sectors = 12;
//draws the sectors on the screen
for(int i=0; i<sectors; i++)
{
g2d.draw(sectorLine);
g2d.rotate(Math.toRadians(30),getWidth()/2,getHeight()/2);
}
//draws the doilie
if(dragging)
{
for(int i=0; i<sectors; i++)
{
g2d.fillOval((int) draw.getX(), (int) draw.getY(),20, 20);
g2d.rotate(Math.toRadians(30), getWidth()/2, getHeight()/2);
}
}
}
private class DisplayListener extends MouseAdapter
{
public void mouseDragged(MouseEvent event)
{
dragging = true;
draw = event.getPoint();
repaint();
}
public void mouseReleased(MouseEvent event)
{
dragging = false;
}
}
}

super.paintComponent() erases/clears the area before drawing, so you only see the point you current draw.
If you want to draw the line the mouse dragged, you would have to store each drawn coordinate in a List, and then in paintComponent(), draw all the points again. Please be aware that this list could get very big, and thus eat a lot of memory, so you should probably think about limiting it somehow.

Related

Keylistener works but is not executing the intended operation. Why?

This is the MainApplication which creates a Frame and holds the class which implements Graphics.
MainApplication.java
import java.awt.*;
public class MainApplication
{
public MainApplication()
{
Frame frame= new Frame("Test App");
frame.add(new KeyTest());
frame.setBackground(Color.RED);
frame.setLayout(null);
frame.setSize(700,750);
frame.setVisible(true);
}
public static void main(String args[])
{
new MainApplication();
}
}
This class creates all the Graphical shapes and implements the KeyListener too.
KeyTest.java
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.RoundRectangle2D;
public class KeyTest extends Canvas {
/**
*
*/
private static final long serialVersionUID = 3L;
Graphics2D graphics2D;
Color color = Color.BLACK;
private static float borderThickness = 5;
Shape firstShape = new RoundRectangle2D.Double(20,40,300,50,10,10);
Shape secondShape = new RoundRectangle2D.Double(20,150,300,50,10,10);
public KeyTest()
{
setBackground(Color.RED);
setSize(700,750);
}
public void paint(Graphics graphics)
{
graphics2D = (Graphics2D)graphics; //TypeCasting to 2D
System.out.println("I am inside paint");
// Smoothening the corners
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Apple border color
Stroke oldStroke = graphics2D.getStroke();
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Apple
graphics2D.draw(firstShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(firstShape);
// Setting the font inside the shape
Font firstFont = new Font("Serif", Font.BOLD,35);
graphics2D.setFont(firstFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Apple",30,80);
// Pineapple border color
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Pineapple
graphics2D.draw(secondShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(secondShape);
// Setting the font inside the shape
Font secondFont = new Font("Serif", Font.BOLD,35);
graphics2D.setFont(secondFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Pineapple",30,190);
addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
System.out.println(KeyEvent.VK_UP);
if(keyCode==KeyEvent.VK_UP){
System.out.println("Going to move up");
move(firstShape);
}
if(keyCode==KeyEvent.VK_DOWN){
System.out.println("Going to move down");
move(secondShape);
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}});
}
public void move(Shape s){
System.out.println("Check:"+s.getBounds2D());
graphics2D.setColor(Color.GREEN);
graphics2D.fill(s);
System.out.println("moving out");
}
}
My console output clearly shows that my Key Listener works but its not executing the task which I intend it to do.
Console Output
I am inside paint Going to move up
Check:java.awt.geom.Rectangle2D$Double[x=20.0,y=40.0,w=300.0,h=50.0]
moving out Going to move down
Check:java.awt.geom.Rectangle2D$Double[x=20.0,y=150.0,w=300.0,h=50.0]
moving out
OUTPUT:
The Output which am getting now.. (IMAGE 1)
The output I expect when I press DOWN ARROW Button (IMAGE 2)
The Output I expect when I press UP ARROW Button (IMAGE 3)
First, you shouldn't add a KeyListener from inside the paint method, since it will register an additional one each time paint is called.
Then, don't rely on storing a Graphics object of a Componentand painting things on it, because many things can happen to it that are outside of your control (for instance it may get cleared by other occuring AWT UI operations).
The only relevant Graphics object is the instance you receive in paint, and only in the scope of the paint method.
So in the following code :
addKeyListener has been moved outside of paint .
The key listener
calls move with the index of the Shape to move.
The move method
now only registers the Shape to highlight depending on the index received, and calls repaint.
The
Graphics2D object is set as a local variable to paint, since it
isn't relevant outside.
paintHighlightedShape is responsible for painting the highlighted Shape, on a Graphics2D object received as a parameter
The paint method now calls paintHighlightedShape with its Graphics2D object passed as a parameter.
Note that a main method has been added to KeyTest for testing purpose, its content should go in your main class.
Also if you plan on having more Shapes to highlight, you may use an array of Shape, and the index passed to move could be the array index of the Shape to highlight.
Finally, to optimize things, we shouldn't draw the regular shape if it is a highlighted one, since it will be hidden by the green shape anyway.
Consider creating a drawShape(Graphics2D, Shape) method that will draw the regular shape or the green shape, depending on the shape being highlighted or not.
You would call this method from the paint method, looping on all shapes.
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.RoundRectangle2D;
public class KeyTest extends Canvas {
/**
*
*/
private static final long serialVersionUID = 3L;
Color color = Color.BLACK;
private static float borderThickness = 5;
Shape firstShape = new RoundRectangle2D.Double(20, 40, 300, 50, 10, 10);
Shape secondShape = new RoundRectangle2D.Double(20, 150, 300, 50, 10, 10);
Shape highlightedShape;
public KeyTest() {
setBackground(Color.RED);
setSize(700, 750);
}
public static void main(final String[] args) {
Frame frame = new Frame("Test App");
final KeyTest keyTest = new KeyTest();
keyTest.addKeyListener(new KeyListener() {
#Override
public void keyTyped(final KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(final KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
System.out.println(KeyEvent.VK_UP);
if (keyCode == KeyEvent.VK_UP) {
System.out.println("Going to move up");
keyTest.move(1);
}
if (keyCode == KeyEvent.VK_DOWN) {
System.out.println("Going to move down");
keyTest.move(2);
}
}
#Override
public void keyReleased(final KeyEvent e) {
// TODO Auto-generated method stub
}
});
frame.add(keyTest);
frame.setBackground(Color.RED);
frame.setLayout(null);
frame.setSize(700, 750);
frame.setVisible(true);
}
public void paint(final Graphics graphics) {
Graphics2D graphics2D = (Graphics2D) graphics; //TypeCasting to 2D
System.out.println("I am inside paint");
// Smoothening the corners
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Apple border color
Stroke oldStroke = graphics2D.getStroke();
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Apple
graphics2D.draw(firstShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(firstShape);
// Setting the font inside the shape
Font firstFont = new Font("Serif", Font.BOLD, 35);
graphics2D.setFont(firstFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Apple", 30, 80);
// Pineapple border color
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Pineapple
graphics2D.draw(secondShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(secondShape);
// Setting the font inside the shape
Font secondFont = new Font("Serif", Font.BOLD, 35);
graphics2D.setFont(secondFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Pineapple", 30, 190);
paintHighlightedShape(graphics2D);
}
private void paintHighlightedShape(final Graphics2D graphics2D) {
if (highlightedShape != null) {
graphics2D.setColor(Color.GREEN);
graphics2D.fill(highlightedShape);
}
}
public void move(final int shapeNumber) {
switch (shapeNumber) {
case 1:
highlightedShape = firstShape;
break;
case 2:
highlightedShape = secondShape;
break;
default:
}
System.out.println("Check:" + highlightedShape.getBounds2D());
System.out.println("Moving shape : " + highlightedShape);
repaint();
System.out.println("moving out");
}
}

JPanel - Graphics stop while mouse is being moved?

I'm working on a little java project wherein I need to draw a small handful of shapes to the screen. I also need to capture mouse events for utility functions. Right now, I have a program that captures a click, and sends out a little ripple from that position. Whenever the mouse is moved, however, the paintComponent(Graphics g) method just stops entirely. I thought it was a buffering issue, so I implemented one, and it just slowed even more at normal rendering. Another strange thing: When the mouse is being held down, the paintComponent method doesn't care about the mouse movement anymore. It resumes as normal.
EDIT: I should also mention that the mouse events are triggered by a class that implements MouseListener. They are calling correctly. To get the mouse position, I use this:
public Point getMouse() {
Point mousePos = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(mousePos, screen);
return mousePos;
}
package com.noneofyebidmness;
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.RenderingHints;
import java.util.ArrayList;
import javax.swing.JPanel;
import com.noneofyebidmness.Organism;
#SuppressWarnings("serial")
public class Screen extends JPanel {
private int diameter = 10;
private ArrayList<Point> ripplePositions;
private ArrayList<Point> rippleDiameters;
public Screen() {
ripplePositions = new ArrayList<Point>();
rippleDiameters = new ArrayList<Point>();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(Reference.SCREEN_WIDTH_DEFAULT, Reference.SCREEN_HEIGHT_DEFAULT);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Painting");
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Organism o : Wrapper.getInstance().getOrganisms()) {
o.draw(g2d);
}
Point mouse = Wrapper.getInstance().getMouse();
Utility.background(Utility.color(0, 150, 250), g2d, this);
g2d.setColor(Utility.color(255));
g2d.fillOval((int)mouse.getX() - diameter / 2, (int)mouse.getY() - diameter / 2, diameter, diameter);
g2d.setColor(Color.BLACK);
g2d.drawString(Wrapper.FPS_PERIODIC + "", 10, 20);
for(int i = 0; i < ripplePositions.size(); i++) {
int w = rippleDiameters.get(i).x;
g2d.setColor(Utility.color(255, Math.min(220-w, 255)));
g2d.setStroke(new BasicStroke(10));
g2d.drawOval(ripplePositions.get(i).x - w / 2, ripplePositions.get(i).y - w / 2, rippleDiameters.get(i).x, rippleDiameters.get(i).x);
if(w < 255) {
rippleDiameters.get(i).x += rippleDiameters.get(i).y;
if(rippleDiameters.get(i).y > 0)
rippleDiameters.get(i).y -= 0.01;
}
if(220-w == 0) {
ripplePositions.remove(i);
rippleDiameters.remove(i);
}
}
g2d.dispose();
}
public void addRipple() {
ripplePositions.add(Wrapper.getInstance().getMouse());
rippleDiameters.add(new Point(diameter, 20));
}
}
TL;DR:
When the mouse is moved over my JPanel, it stops calling paintComponent().
If the mouse is held down and moved, things operate as normal.
Any help is appreciated,
Carl Litchman

Resizing a Path2D shape when user clicks and drags

So, I have a program that adds a square to a JPanel and lets the user drag the shape around the panel. What I want to do is be able to click on the bottom-right corner of the shape and resize it as the user drags it. I'm kind of stuck on how to do this. I know that as the user drags it will need to recalculate the rectangle's length and width to make the bottom right corner match where the mouse is. But how can I detect a click on the bottom right edge of the rectangle? Thanks for any help.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Shapes shapeList = new Shapes();
Panel panel;
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
panel = new Panel();
}
public void addMenus() {
getContentPane().add(shapeList);
setTitle("UML Editior");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
shapeList.addSquare(100, 100);
}
public void loadFile() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r = chooser.showOpenDialog(this);
if (r == JFileChooser.APPROVE_OPTION) {
}
}
}
// Shapes class, used to draw the shapes on the panel
// as well as implements the MouseListener for dragging
class Shapes extends JPanel {
private static final long serialVersionUID = 1L;
private List<Path2D> shapes = new ArrayList<Path2D>();
int currentIndex;
public Shapes() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
public void addSquare(int width, int height) {
Path2D rect2 = new Path2D.Double();
rect2.append(new Rectangle(getWidth() / 2 - width / 2, getHeight() / 2
- height / 2, width, height), true);
shapes.add(rect2);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2));
for (Path2D shape : shapes) {
g2.draw(shape);
}
}
class MyMouseAdapter extends MouseAdapter {
private boolean pressed = false;
private Point point;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
for (int i = 0; i < shapes.size(); i++) {
if (shapes.get(i) != null
&& shapes.get(i).contains(e.getPoint())) {
currentIndex = i;
pressed = true;
this.point = e.getPoint();
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (pressed) {
int deltaX = e.getX() - point.x;
int deltaY = e.getY() - point.y;
shapes.get(currentIndex).transform(
AffineTransform.getTranslateInstance(deltaX, deltaY));
point = e.getPoint();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
pressed = false;
}
}
}
I wrote a couple of things back in the day that might be helpful to you
To start, AreaManager (http://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/shape/) This is kind of what you want, in that it's dealing with Shapes (Area's, actually). There's a dragger class which uses mouse drag, and a resizer class that uses the mouse wheel. But this isn't exactly the user interface you've described.
That user interface for doing changing the cursor and resizing based on the type of cursor and the mouse drag is in Draggable in http://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/drag/. Draggable works with Components that are contained in Containers with the layoutmanager turned off. But it should be not so complicated to adapt to your purposes

Simple Java Paint Program: How to change the color without changing the previous painted

I am writing simple Paint program, where you paint whatever you want by dragging the mouse. You can change the color and the size of the brush, but in this version, when I change the color or the size of the brush, everything painted before is changed too when I start to draw again by dragging the mouse. I have tried with getGraphics method in the paintComponent method, but I probably did it wrong way because it did not help me.. Any ideas how to deal with this issue? Thank you.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;
public class PaintPanel extends JPanel{
private int pointCount = 0;
private Point points[] = new Point[10000];
private Color currentColor;
private int pointSize;
public PaintPanel(){
setBackground(Color.WHITE);
setDefaultColor();
setDefaultPointSize();
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged(MouseEvent event){
if(pointCount < points.length){
points[pointCount] = event.getPoint();
pointCount++;
repaint();
}
}
}
);
}
public void setColor(Color newColor){
currentColor = newColor;
}
public void setDefaultColor(){
currentColor = Color.BLACK;
}
public void setPointSize(int size){
pointSize = size;
}
public void setDefaultPointSize(){
pointSize = 6;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(currentColor);
for(int i = 0; i < pointCount; i++)
g.fillOval(points[i].x,points[i].y,pointSize,pointSize);
}
}
Any option to do it without Collections?
Everything is colored currentColor You need two levels of storage. First of all, use an ArrayList to store your points. Then use an array list of array lists to store your "curves." Each "curve" should know its color.

How to use paintComponent in Java to paint multiple things, but rotate one?

I'm making a program in Java for my CS class. My teacher has little experience with graphics programing in Java so I've turned to you. I'm currently using the paintComponent method of my main panel to draw two things, one, a rectangle (my cannon, possibly replaced with a image later), and two, a .png file of a cannon ball. I use the Graphics g (which I convert to Graphics2D) to paint the cannon and Ball on to the screen. I then rotate, but, the cannon and ball rotate, not just the cannon. Any tips, suggestions, or helpful tutorials are greatly appreciated.
Here is my code (the commented out links are where I got certain code, ignore them):
package Cannon;
import java.awt.geom.Point2D;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class NewMain{
public static void main(String[] args) {
FraMainWindow frame = new FraMainWindow();
}
}
class FraMainWindow extends JFrame {
DrawCannon pnlCannon = new DrawCannon();
ButtonPannel pnlButtons = new ButtonPannel();
public FraMainWindow() {
this.setDefaultCloseOperation(JFrame.EXI…
this.setTitle("Super Mario Cannon Bro's");
this.setSize(900, 550);
this.setLayout(new BorderLayout());
this.add(pnlCannon, BorderLayout.CENTER);
this.add(pnlButtons, BorderLayout.SOUTH);
MouseMovement mouseMove = new MouseMovement();
MouseAction mouseClick = new MouseAction();
pnlCannon.addMouseMotionListener(mouseMo…
pnlCannon.addMouseListener(mouseClick);
FireButton actnFire = new FireButton();
pnlButtons.btnFire.addActionListener(act…
this.setVisible(true);
}
public class DrawCannon extends JPanel{
Rectangle.Float rectCannon = new Rectangle.Float(30, 450, 50, 10);
Image imgBall=new ImageIcon("ball.png").getImage();
double dAngle = 0;
boolean isFired = false;
public void addCannonBall(){
isFired=true;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_RENDER_QUALITY);//A… Aliasing from http://www.java2s.com/Code/Java/2D-Graph…
g2d.rotate(0 - dAngle, rectCannon.getX(), rectCannon.getY() + 5);
g2d.fill(rectCannon);
if(isFired){
g2d.drawImage(imgBall, 0, 0, null);
}
//Dimension size = getSize();
}
}
public class ButtonPannel extends JPanel {
JButton btnFire = new JButton("Fire!");
ButtonPannel() {
this.add(btnFire);
}
}
public class FireButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
pnlCannon.addCannonBall();
System.out.println("Fire ZE MISSILES");
}
}
public class MouseMovement implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}//http://download.oracle.com/javase/tutori…
public void mouseMoved(MouseEvent e) {
}
}
public class MouseAction implements MouseListener {
public void mousePressed(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
} // From http://www.rgagnon
Try moving this bit:
if(isFired){
g2d.drawImage(imgBall, 0, 0, null);
}
before this line:
g2d.rotate(0 - dAngle, rectCannon.getX(), rectCannon.getY() + 5);
Any transformations you apply to your Graphics2D will affect anything from that point, so you have to either be careful to apply transforms when you need them, or to "un-apply" them before you don't need them.
You have to unrotate after drawing the cannon and before drawing the ball :)
You could try to save the transform before you do a rotate and then set it back again. This example is from setTransform in the Java Docs:
// Get the current transform
AffineTransform saveAT = g2.getTransform();
// Perform transformation
g2d.transform(...);
// Render
g2d.draw(...);
// Restore original transform
g2d.setTransform(saveAT);

Categories