I'm trying to get the red dot to move straight down the y-axis. Please help. Right now it is not moving. I need it to move down at x = 235, y = 0 Until x = 235, y = 235 to create the illusion of motion. Here is the code (it is messy because I changed the ball movement from left right, but can't get it to got downward).
import java.awt.Color;
import java.awt.Graphics;
public class Animation {
public static void main(String [] args) {
DrawingPanel panel = new DrawingPanel(350, 350);
Graphics g = panel.getGraphics();
background(g);
ballroll(panel, g);
}
public static void ballroll(DrawingPanel panel, Graphics g) {
//draw and roll the ball now
g.setColor(Color.RED);
int x = 245, y = 0, direction=1;
while(y<245){
g.fillOval(235, 0, 20, 20);
//if (x==0){
y+=60;
direction *= -1;
}
//else if (x < 115){
//direction *= -1;
//y+=60;
//}
y+=direction*15;
System.out.println(x);
panel.sleep(80);
}
panel.sleep(350);
//}
}
You counting the y value up but you didn't use it.
I think it should be g.fillOval(235, y, 20, 20);
Related
Please help me how to make this eye move or to make it blink using repaint, thread and implements runnable. I don't know where to place the right codes to make it work. Please help me guys! Thank you!
Here is the code:
import java.awt.*;
import java.applet.*;
public class Pucca extends Applet {
public Pucca(){
setSize(700, 700); }
//paint method
public void paint(Graphics g){
Color white = new Color(255,255,255);
g.setColor(white);
g.fillOval(600, 100, 125, 125); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(600, 100, 125, 125); // left big black line eye
g.setColor(white);
g.fillOval(700, 100, 125, 125); //right white fill eye
g.setColor(Color.BLACK);
g.drawOval(700, 100, 125, 125); //right big black line eye
Color blue = new Color(0, 160, 198);
g.setColor(blue);
g.fillOval(635, 130, 51, 51); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(635, 130, 50, 50); // left black small line eye
g.setColor(blue);
g.fillOval(735, 130, 51, 51); // right blue fill eye
g.setColor(Color.BLACK);
g.drawOval(735, 130, 50, 50); // right black small line eye
g.setColor(Color.BLACK);
g.fillOval(650, 145, 20, 20); // left black iris
g.setColor(Color.BLACK);
g.fillOval(750, 145, 20, 20); // right black iris
}
}
When it comes to animation, everything becomes variable. You also have a lot of repeated code (seriously, if you can paint one eye, you can paint lots).
The first thing you need to is make all the values of the eye as variable as possible.
The follow makes the eye size and position variable and the iris and pupil a scaled value of the eye size, which makes the whole process simpler to animate.
Next, you need an updated loop, which can update the state of the values you want to change. To keep it simple, I've set it up so that the pupil has a variable offset, which is changed over time.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
public class Pucca extends Applet {
public Pucca() {
setSize(700, 700);
Thread t = new Thread(new Runnable() {
private int xDelta = -1;
private int yDelta = 0;
private int blinkCount = 0;
#Override
public void run() {
while (true) {
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
xOffset += xDelta;
double irisSize = eyeSize.width * irisScale;
double range = ((eyeSize.width - irisSize) / 2);
if (xOffset <= -range) {
xOffset = -(int) range;
xDelta *= -1;
} else if (xOffset >= range) {
xOffset = (int) range;
xDelta *= -1;
}
blinkCount++;
if (blink && blinkCount > 10) {
blink = false;
blinkCount = 0;
} else if (blinkCount > 25) {
blink = true;
blinkCount = 0;
}
repaint();
}
}
});
t.setDaemon(true);
t.start();
}
private boolean blink = false;
private int xOffset, yOffset = 0;
private Dimension eyeSize = new Dimension(125, 125);
private Point left = new Point(20, 20);
private Point right = new Point(left.x + 100, left.y);
private double irisScale = 0.4;
private double pupilScale = 0.16;
//paint method
#Override
public void paint(Graphics g) {
super.paint(g);
paintEye(g, new Rectangle(left, eyeSize));
paintEye(g, new Rectangle(right, eyeSize));
}
protected void paintEye(Graphics g, Rectangle bounds) {
Color white = new Color(255, 255, 255);
if (blink) {
g.setColor(Color.YELLOW);
} else {
g.setColor(white);
}
g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(bounds.x, bounds.y, bounds.width, bounds.height); // left big black line eye
if (!blink) {
Color blue = new Color(0, 160, 198);
paintEyePartAt(g, bounds, irisScale, blue);
paintEyePartAt(g, bounds, pupilScale, Color.BLACK);
}
}
private void paintEyePartAt(Graphics g, Rectangle bounds, double delta, Color color) {
int width = (int) (bounds.width * delta);
int height = (int) (bounds.height * delta);
g.setColor(color);
g.fillOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width, height); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width,
height); // left blue fill eye
}
}
This complicates things, as painting can occur for any number of reasons, many of which you don't have control over or will be notified about, so you should be very careful about where and when you change values.
You should also have a look at Java Plugin support deprecated and Moving to a Plugin-Free Web and Why CS teachers should stop teaching Java applets.
Applets are simply a dead technology and given the inherent complexities involved in using them, you should instead focus you should probably attention towards window based programs.
Personally, I'd start with having a look at Painting in AWT and Swing and Performing Custom Painting
I'm currently working on a program which enables user to draw various geometric shapes. However, I got some issues on calculating and placing the angle objects onto my Canvas panel accurately. The angle object is basically an extension of the Arc2D object, which provides a additional method called computeStartAndExtent(). Inside my Angle class, this method computes and finds the necessary starting and extension angle values:
private void computeStartAndExtent()
{
double ang1 = Math.toDegrees(Math.atan2(b1.getY2() - b1.getY1(), b1.getX2() - b1.getX1()));
double ang2 = Math.toDegrees(Math.atan2(b2.getY2() - b2.getY1(), b2.getX2() - b2.getX1()));
if(ang2 < ang1)
{
start = Math.abs(180 - ang2);
extent = ang1 - ang2;
}
else
{
start = Math.abs(180 - ang1);
extent = ang2 - ang1;
}
start -= extent;
}
It is a bit buggy code that only works when I connect two lines to each other, however, when I connect a third one to make a triangle, the result is like the following,
As you see the ADB angle is the only one that is placed correctly. I couldn't figure how to overcome this. If you need some additional info/code please let me know.
EDIT: b1 and b2 are Line2D objects in computeStartAndExtent() method.
Thank you.
There are some of things that can be made to simplify the calculation:
Keep the vertices ordered, so that it is always clear how to calculate the vertex angles pointing away from the corner
Furthermore, always draw the polygon to the same direction; then you can always draw the angles to the same direction. The example below assumes the polygon is drawn clockwise. The same angle calculation would result in the arcs drawn outside given a polygon drawn counterclockwise.
Example code; is not quite the same as yours as I don't have your code, but has similar functionality:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Arc2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Polygon extends JPanel {
private static final int RADIUS = 20;
private final int[] xpoints = {
10, 150, 80, 60
};
private final int[] ypoints = {
10, 10, 150, 60
};
final Arc2D[] arcs;
Polygon() {
arcs = new Arc2D[xpoints.length];
for (int i = 0; i < arcs.length; i++) {
// Indices of previous and next corners
int prev = (i + arcs.length - 1) % arcs.length;
int next = (i + arcs.length + 1) % arcs.length;
// angles of sides, pointing outwards from the corner
double ang1 = Math.toDegrees(Math.atan2(-(ypoints[prev] - ypoints[i]), xpoints[prev] - xpoints[i]));
double ang2 = Math.toDegrees(Math.atan2(-(ypoints[next] - ypoints[i]), xpoints[next] - xpoints[i]));
int start = (int) ang1;
int extent = (int) (ang2 - ang1);
// always draw to positive direction, limit the angle <= 360
extent = (extent + 360) % 360;
arcs[i] = new Arc2D.Float(xpoints[i] - RADIUS, ypoints[i] - RADIUS, 2 * RADIUS, 2 * RADIUS, start, extent, Arc2D.OPEN);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(160, 160);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawPolygon(xpoints, ypoints, xpoints.length);
Graphics2D g2d = (Graphics2D) g;
for (Shape s : arcs) {
g2d.draw(s);
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Polygon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Polygon());
frame.pack();
frame.setVisible(true);
}
});
}
}
Results in:
Essentially, in this program bugs move around the screen eating food.
The issue that I am having is that graphics "circle" repaints fine and moves around the frame, but none of the bugs are repainted (However they are drawn initially).
I've tested it with console outputs and the x and y coordinates of the bugs do update, but the graphic in the frame does not.
So my question is, why is it the x/y of the circle is updated and repainted, but the bugs are not?
(As far as I can see, I'm approaching the task of changing the bugs x/y in the same way as with the circle)
(I've removed some of the things like the world getters and setters, and cut the code down a bit. The actual program has a movebug() method which handles the moving of the bugs in a correct fashion with hit detection.)
public class Run extends JPanel implements ActionListener{
double x, y, velX, velY, newx, newy;
public Timer t;
private static AWorld world1;
ArrayList<Ellipse2D> graphicBugArrayList = new ArrayList<Ellipse2D>();
public Run(){
x = 150;
y = 150;
velX = 2;
velY = 2;
t = new Timer(5, this);
setWorld1(new AWorld());
getWorld1().populatemap();
AWorld.direction directionchecker;
repaint();
t.start();
}
public void paintComponent(Graphics g){
//Creating circle that move
g.setColor(Color.BLACK);
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x, y, 10, 10);
//creating and drawing the bugs
for(int i=0; i<world1.getNumberofbugs(); i++)
{
Ellipse2D obscircle = new Ellipse2D.Double(getWorld1().bugArrayList.get(i).getHPosition(), getWorld1().bugArrayList.get(i).getVPosition(), 14, 15);
graphicBugArrayList.add(obscircle);
g2.setPaint(Color.RED);
g2.fill(graphicBugArrayList.get(i));
g2.draw(graphicBugArrayList.get(i));
}
//Drawing the circle that moves
g2.setPaint(Color.BLACK);
g2.draw(circle);
}
public void actionPerformed(ActionEvent arg0) {
//Moving the circle
if(x<0 || x > 500)
{
velX = -velX;
}
if(y<0 || y > 500)
{
velY = -velY;
}
x += velX;
y -= velY;
//Test moving the bugs
getWorld1().bugArrayList.get(i).setHPosition(getWorld1().bugArrayList.get(i).getHPosition()+1);
repaint();
}
}
You never clear your graphicBugArrayList, but only draw the first few elements over and over. Try this in your loop:
for(int i=0; i<world1.getNumberofbugs(); i++)
{
Ellipse2D obscircle = new Ellipse2D.Double(getWorld1().bugArrayList.get(i).getHPosition(), getWorld1().bugArrayList.get(i).getVPosition(), 14, 15);
graphicBugArrayList.add(i, obscircle);
g2.setPaint(Color.RED);
g2.fill(graphicBugArrayList.get(i));
g2.draw(graphicBugArrayList.get(i));
}
Hello I am fairly new to java and have been stuck on this problem for awhile so hopefully someone will be able to save me. Basically I am creating a program that can graph an equation and right now I'm testing out x^2 between -10 and 10. I can get the points to graph in the right spots but I can't figure out how to fill in the spots in between the points so it looks like a real graph.
Here's my code:
import java.util.Scanner;
import javax.swing.JFrame;
import java.awt.*;
class PlotGraph extends JFrame{
public void paint(Graphics l){
l.drawLine(50, 300, 550, 300); //x axis
l.drawLine(300, 550, 300, 50); //y axis
//Orignin x = 300 y = 300
int xmin, xmax, y, tmin, tmax;
xmin =(-10);
xmax = 10;
int x_bet, y_bet;
while(xmin<=xmax){
y = 300-(xmin*xmin);
l.drawLine(xmin+300, y, xmin+300, y);
//while(x_bet>xmin){
//l.drawLine(, , , );
//}
xmin++;
}
}
public static void main(String [] args) {
PlotGraph graph = new PlotGraph();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(600, 600);
graph.setVisible(true);
graph.setTitle("PlotGraph");
}
}
Another way to do it is to create a GeneralPath, like this.
import javax.swing.JFrame;
import java.awt.*;
import java.awt.geom.*;
class PlotGraph extends JFrame{
public void paint(Graphics l){
l.drawLine(50, 300, 550, 300); //x axis
l.drawLine(300, 550, 300, 50); //y axis
int xmin, xmax, y, tmin, tmax;
xmin =(-10);
xmax = 10;
int x_bet, y_bet;
GeneralPath gp = new GeneralPath();
y = 300-(xmin*xmin);
gp.moveTo((double)xmin+300, (double)y);
while(xmin<=xmax){
y = 300-(xmin*xmin);
gp.lineTo((double)xmin+300, (double)y);
xmin++;
}
Graphics2D g2 = (Graphics2D)l;
g2.setColor(Color.RED);
g2.draw(gp);
}
public static void main(String [] args) {
PlotGraph graph = new PlotGraph();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(600, 600);
graph.setVisible(true);
graph.setTitle("PlotGraph");
}
}
This source still has problems though:
GUI updates should be done on the EDT.
Custom painting is either best done in a JPanel/JComponent or a BufferedImage displayed in a JLabel.
The 'graph component' should declare a preferred size, rather than setting a size for the frame..
Maybe try this:
int x = xmin;
int last_y = 300-(x*x);
for (x = xmin+1; x<=xmax; x++);
y = 300-(x*x);
l.drawLine(x-1, last_y, x, y);
last_y = y;
}
You want the line to be drawn between previous x and y coordinates and the current ones. That's what last_y is for.
There are several ways to do this. If this is an assignment then I'm guessing that your professor is looking to see what methods you come up with. At the most basic level you just draw a line from the last point to the current point. How else could you accomplish this? Maybe a polyline in a different color? Maybe use a little math to draw larger circles a then run a line through them?
Here is one simple way to address the specific problem. I wouldn't recommend turning this in (if it's an assignment) but it shows you the basic principle.
import java.util.Scanner;
import javax.swing.JFrame;
import java.awt.*;
class PlotGraph extends JFrame{
public void paint(Graphics l){
l.drawLine(50, 300, 550, 300); //x axis
l.drawLine(300, 550, 300, 50); //y axis
int xmin, xmax, y, tmin, tmax;
int z = 0;
xmin =(-10);
xmax = 10;
int x_bet, y_bet;
while(xmin<=xmax){
y = 300-(xmin*xmin);
l.drawLine(xmin+300, y, xmin+300, y);
if(z!=0)
l.drawLine(xmin+300, y, xmin+300, z);
z=y;
xmin++;
}
}
public static void main(String [] args) {
PlotGraph graph = new PlotGraph();
graph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
graph.setSize(600, 600);
graph.setVisible(true);
graph.setTitle("PlotGraph");
}
}
import javax.swing.*;
import java.awt.*;
public class JFrameAnimationTest extends JFrame {
public static void main(String[] args) throws Exception{
AnimationPanel animation = new AnimationPanel();
JFrameAnimationTest frame = new JFrameAnimationTest();
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(animation);
frame.setVisible(true);
for(int i = 0; i < 100; i++) {
animation.incX(1);
//animation.incY(1);
animation.repaint();
Thread.sleep(10);
}
}
}
class AnimationPanel extends JPanel {
int x = 10;
int y = 10;
public AnimationPanel() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawRect(x, y, 20, 20);
g.fillRect(x, y, 20, 20);
}
protected void incX(int X) {
x += X;
}
protected void incY(int Y) {
y += Y;
}
}
So anyways theres my code. It probably looks a bit jumbled as I am not used to stackoverflow just yet so I apologize.
Here's my question: This program makes this small rectangle slowly move to the right; how can I add rotation to the rectangles movement during that time period?
Note: I haven't actually compiled this code, but you get the gist.
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D g2d = (Graphics2D) g;
// The 20x20 rectangle that you want to draw
Rectangle2D rect = new Rectangle2D.Double( 0, 0, 20, 20 );
// This transform is used to modify the rectangle (an affine
// transform is a way to do operations like translations, rotations,
// scalings, etc...)
AffineTransform transform = new AffineTransform();
// 3rd operation performed: translate the rectangle to the desired
// x and y position
transform.translate( x + 10, y + 10 );
// 2nd operation performed: rotate the rectangle around the origin
transform.rotate( rotation );
// 1st operation performed: translate the rectangle such that it is
// centered on the origin
transform.translate( -10, -10 );
// Apply the affine transform
Shape s = transform.createTransformedShape( rect );
// Fill the shape with the current paint
g2d.fill( s );
// Stroke the edge of the shape with the current paint
g2d.draw( s );
}
Also note that you should really be using something like a javax.swing.Timer when you modify x, y, and rotation and when you call repaint(). That way all of it happens on the event dispatch thread.