3 Simple Ways to
Share What You Make

With Instructables you can share what you make with the world — and tap into an ever-growing community of creative experts.

PhotosPhotos

Share one or more photos of a project, recipe, or whatever you've made, quickly and easily.

Step by StepStep-By-Step

Share your step-by-step photos with text instructions of what you made so others can do it too!

VideoVideo

Share your how-to video. You'll need your embed code from a video site such as YouTube.

Using Java to Rotate an Object to Face the Mouse

Using Java to Rotate an Object to Face the Mouse
If you have ever used Java's 2D API you probably have wanted to know how to make a character face your mouse. So you got on google and looked it up and guess what? THERE ARE NO RELEVANT RESULTS! Ah. So I spent an hour figuring out how to use trig to do just this in Java.
 
Remove these adsRemove these ads by Signing Up
 

Step 1Build a Simple Game

Ok simply use Java to make a JFrame called mainFrame. I made it its own class but you dont have to. Next make a Paint class. It should read-

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

public class Paint extends JPanel {
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, this.getSize().width, this.getSize().height);
g2.drawImage(getBaseImage(), 235, 200,null);
g2.setColor(Color.black);
g2.drawLine(250, 215,(int)mainFrame.littleX+250, (int)mainFrame.littleY+215);
}
public BufferedImage getBaseImage(){
BufferedImage Img = null;
try {
Img = ImageIO.read(new File("/*PICTURE FILE-NAME*/"));
} catch (IOException e) {
System.err.println(e);
}
return Img;
}
//this method is optional and just adds a pic to the file
}

Create a global variable that reads-
public static javax.swing.JPanel jPanel1;

Next, on the mainFrame add the JPanel and make it the same size as the JFrame.
Set it equal to new Paint();
ie... jPanel1=new Paint();

(this code won't work quite yet so don't panic if you get a ton of errors)
« Previous StepDownload PDFView All StepsNext Step »

Pro

Get More Out of Instructables

Already have an Account?

close

All Steps Viewing
View all steps of an Instructable on the same page when you're a Pro Member.

Upgrade to Pro today!
1
Followers
2
Author:ghostbust555