Java animation about reframing an image - java

Hi I am currently making a program that will show a spring that moves with the values that I enter and uses the formulas of physics. The problem is that, when I create a spring and make the animation start, the old image stays there and overrides without deleting the one before here's the code of the problem :
bouton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
/*anime.animer();
anime.repaint();*/
for (int t = 0; t < 500; t += 5) {
for (int i = 105; i < 175; i += 5) {
Ellipse2D elp1 = new Ellipse2D.Double(i, 100, 15, 30);
((Graphics2D) dessinPanel.getGraphics()).draw(elp1);
}
for (int i = 105; i < 175; i += 5) {
Ellipse2D elp1 = new Ellipse2D.Double(i, 100, 15 + osi.simuler(t), 30);
((Graphics2D) dessinPanel.getGraphics()).draw(elp1);
dessinPanel.repaint();
Rectangle2D rect = new Rectangle2D.Double(186 + osi.simuler(t), 90, 50, 50);
((Graphics2D) dessinPanel.getGraphics()).draw(rect);
dessinPanel.repaint();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Here`s also some pictures to show the problem:
before
after

You need to decouple your painting from your value adjustments.
Your painting operation should start by clearing the background, then paint the spring and box using the current input values.
When an input value changes, simply update the variable and invalidate() the display area.
For better performance, clearing the background can also be done by drawing the spring and box at their current positions in the background color. This also makes the updating of the input values more difficult.
One more technique you might use would be to widen the brush and draw first in the background color, then shrink the brush and draw the actual spring and rectangle in their correct form. This would be equivalent to erasing the background as long as you control the amount either can move in a single frame.

Related

Platforms in a class not moving when called in

For a university course I'm making a game with a friend. The general idea is that we have some platforms moving from right to left and each time one goes offscreen it is generated at a random x and y position on the right (within some limits). There will be a little sprite that jumps from platform to platform.
We have reached a problem we're not sure how to solve. We have all the right code and everything but the platforms just won't move. They should move to the left at a constant speed of -4 pixels per frame (rectVelocity).
We cannot get them to move, though; they are static on the screen at the position each one is initially called in at.
This is the code as condensed as I can make it:
Platforms [] mainPlats;
void setup() {
size(750, 400);
mainPlats = new Platforms[3];
}
void draw() {
level();
}
void level() {
//This is the code for the first platform
mainPlats[0] = new Platforms(200, 200, 100, 15); //These values need to be set inside the class so that
//they aren't constantly overwriting the movement variables in the class
mainPlats[0].displayPlat();
mainPlats[0].platTransition();
//This is the code for the second platform
mainPlats[1] = new Platforms(420, 300, 100, 15);
mainPlats[1].displayPlat();
mainPlats[1].platTransition();
//This is the code for the third platform
mainPlats[2] = new Platforms(570, 350, 100, 15);
mainPlats[2].displayPlat();
mainPlats[2].platTransition();
}
class Platforms {
PImage platform;
int rectX, rectY, rectWidth, rectHeight;
int rectVelocity = 4;
Platforms(int x, int y, int w, int h) {
rectX = x;
rectY = y;
// rectX = (int(random(600, 800))); //Tried to randomise start position, failed hilariously
//rectY = (int(random(150, 350)));
rectWidth = w;
rectHeight = h;
}
void displayPlat() {
platform = loadImage ("images/tiles.png");
//imageMode(CENTER);
image(platform, rectX, rectY, 100, 15); //rectangle platforms replaced with images
}
void platMove() {
rectX -= rectVelocity;
}
void platTransition() {
if (rectX < -200) {
rectX = (int(random(700, 1000)));
rectY = (int(random(150, 350)));
}
}
}
From the draw() function, you call your level() function, which initializes your Platform array every single frame.
This means that you create new Platforms at their starting positions every frame. You never see the platforms move, because as soon as you do move them, you replace them with new platforms at the starting positions again.
So step one is to move their initialization out of the level() function and only call them once, at the beginning of your sketch- the setup() function would be one place you could put them.
Your other problem is that you never actually call the platMove() function. So step two is to make sure you call that function.
A solution might look something like this:
Platforms [] mainPlats;
void setup() {
size(750, 400);
mainPlats = new Platforms[3];
mainPlats[0] = new Platforms(200, 200, 100, 15);
mainPlats[1] = new Platforms(420, 300, 100, 15);
mainPlats[2] = new Platforms(570, 350, 100, 15);
}
void draw() {
level();
}
void level() {
mainPlats[0].displayPlat();
mainPlats[0].platMove();
mainPlats[0].platTransition();
mainPlats[1].displayPlat();
mainPlats[1].platMove();
mainPlats[1].platTransition();
mainPlats[2].displayPlat();
mainPlats[2].platMove();
mainPlats[2].platTransition();
}
Also note that you shouldn't load the image every single frame, either. You should only load it once, at startup. You also might want to use a for loop to iterate over your Platforms instead of referring to every single index. But these don't really affect your problem.
You've got rectX as positive values (>0) when you construct the platforms, but you are checking for rectX < -200 when you call platTransition, which is why it never does anything.

Repainting a BufferedImage in Java does not change contents of panel

Long story short I am drawing the Mandelbrot using a BufferedImage that I put in a custom JPanel. I have already done the zooming in the set but have problems with repainting when unzooming. When unzooming I change the value of the image to that of the previous state of the image(I keep every state in a Stack) and repaint the panel. Problem is that the last image in the stack gets popped off but it is not drawn.
These are my instance variables
private BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
private Stack<BufferedImage> zooms = new Stack<BufferedImage>();
private boolean unzoom = false;
This is how I zoom and push the image that I want to save on a stack
public void mouseReleased(MouseEvent e)
{
zooms.push(image);
<some code for zooming that works>
repaint();
}
Now I want to unzoom by scrolling
class WheelZoomListener implements MouseWheelListener
{
public void mouseWheelMoved(MouseWheelEvent e)
{
unzoom = true;
//this is how I assign the current image to be the one before the last zoom
image = zooms.pop();
repaint();
}
}
Finally this is my paint method
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d= (Graphics2D) g;
//if it is not unzooming draw the mandelbrot set normally by
//dealing with every pixel of the Buffered Image separately
if (!unzoom)
{
for(int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
int iterations = getIterations(cnSet[i][j]);
if (iterations == noIterations)
{
color = Color.BLACK;
}
else
{
color = cols[iterations%noIterations];
}
image.setRGB(i, j, color.getRGB());
}
}
}
//zooming or unzooming always draw the image in its current state
g2d.drawImage(image, 0, 0, this);
unzoom = false;
}
FIX: It turned out that I don't need to keep the last image and create temporary images every time. Instead now I only keep the coordinates of the complex plane in a stack. That is all I need to repaint the old image again.
This:
private BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Instantiates a new BufferedImage and stores a reference to that object in image.
This:
zooms.push(image);
Pushes the reference to that single BufferedImage you created onto the stack.
As long as you keep using the same BufferedImage, all you are doing is pushing multiple references to the same object onto the stack; so changes to the object's data are reflected in every reference you've placed on the stack, because every item in the stack points to the same object.
The high-level effect is you are changing every previous state to the current one every time you render.
You'll want to create a whole new BufferedImage for each state; so that each reference you stick on the stack points to a unique object.
Take a look at this nice little article about how references work in Java.

Opacity in images with Processing

Very simple thing I'm trying to do here. I would like to have 2 images on top of one another. When i use my mouse event dragged and clicked on the top image, the area of the top level image selected will fade and make the lower image visible.
The way I see it, there are 2 ways I can do this:
I can make the top image Transparent over time (within the selected area)
or
I can delete the pixels individually in a spray can style fashion. Think the spray can tool from MS paint back in the day.
Heres some very basic code that i started which just lays the images on top of eachother
PImage sand;
PImage fossil;
void setup()
{
size(400,400);
background(255,255,0);
frameRate(30);
fossil = loadImage("foss.jpg");
sand = loadImage("sand.jpeg");
}
void draw()
{
image(fossil, 0, 0, width,height);
image(sand, 0, 0, width,height);
smooth();
if (mousePressed) {
fill(0);
tint(255,127); //the opacity function
} else {
fill(255);
}
}
So has anyone any comments on these 2 ways of creating opacity or perhaps there an easier way I've overlooked?
Perhaps I wasn't clear in my Spec as the 2 comments below are asking for clarification.
In its simplest terms, I have 2 images on top of each other. I would like to be able to make some modification to the top level image which would make the bottom image visible. However I need to make this modification to only part of the top level image.
I would like to know which is the better option. To make part of the top image become transparent using tint() or to delete the pixels from the top layer.
Then I will proceed with that approach. Any indication as to how to do it is also appreciated.
I hope this clears up any confusion.
If you simply want to crossfade between images, it can be with tint() as you code suggest. You were in fact quite close:
PImage sand;
PImage fossil;
void setup()
{
size(400, 400);
fossil = loadImage("CellNoise.jpg");
sand = loadImage("CellVoronoi.jpg");
}
void draw()
{
//tint from 255 to 0 for the top image
tint(255,map(mouseX,0,width,255,0));
image(fossil, 0, 0, width, height);
//tint from 0 to 255 for the bottom image - 'cross fade'
tint(255,map(mouseX,0,width,0,255));
image(sand, 0, 0, width, height);
}
For the "spray can style " erosion you can simply copy pixels from a source image into the destination image. It's up to you how you loop through pixels (how many, what order, etc.) to get the "spray" like effect you want, but here's a basic example of how to use the copy() function:
PImage sand,fossil;
int side = 40;//size of square 'brush'
void setup()
{
size(400, 400);
fossil = loadImage("CellNoise.jpg");
sand = loadImage("CellVoronoi.jpg");
}
void draw()
{
image(fossil, 0, 0, 400, 400);
if(mousePressed) {
for(int y = 0 ; y < side ; y++){
for(int x = 0; x < side; x++){
//copy pixel from 'bottom' image to the top one
//map sketch dimensions to sand/fossil an dimensions to copy from/to right coords
int srcX = (int)map(mouseX+x,0,width+side,0,sand.width);
int srcY = (int)map(mouseY+y,0,height+side,0,sand.height);
int dstX = (int)map(mouseX+x,0,width+side,0,fossil.width);
int dstY = (int)map(mouseY+y,0,height+side,0,fossil.height);
fossil.set(dstX, dstY, sand.get(srcX,srcY));
}
}
}
}
Note what I am simply looping to copy a square (40x40 in my case), but you can find other fun ways to loop and get different effects.
Have fun!

java applet: is there a simple way to draw and erase in a two-layered 2D scene?

I have an applet which displays some data using circles and lines. As the data continually changes, the display is updated, which means that sometimes the circles and lines must be erased, so I just draw them in white (my background color) to erase them. (There are a lot of them, so erasing everything and then recomputing and redrawing everything except the erased item would be a horribly slow way to erase a single item.)
The logic of the situation is that there are two layers that need to be displayed, and I need to be able to erase an object in one layer without affecting the other layer. I suppose the upper layer would need to have a background color of "transparent", but then how would I erase an object, since drawing in a transparent color has no effect.
What distinguishes this situation from all the transparency-related help on the web is that I want to be able to erase lines and circles one-by-one from the transparent layer, overwriting their pixels with the "fully transparent" color.
Currently my applet draws (using just a single layer) by doing this in start():
screenBuffer = createImage(640, 480);
screenBufferGraphics = screenBuffer.getGraphics();
and this in paint():
g.drawImage(screenBuffer, 0, 0, this);
and objects are rendered (or "erased" by drawing in white) by commands like:
screenBufferGraphics.drawLine(x1,y1,x2,y2);
Is it easy to somehow make a second screen buffer with a transparent background and then be able to draw and erase objects in that buffer and render it over the first buffer?
This seems fairly quick, so long as the rendered image area remains around 640x480, the code can achieve from 125-165 FPS. The code tracks 2000 semi-transparent lines of width 4px, and moves them around in an area 8 times the size of the rendered image.
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
class LineAnimator {
public static void main(String[] args) {
final int w = 640;
final int h = 480;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
hints.put(
RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY
);
final BufferedImage bi = new BufferedImage(w,h, BufferedImage.TYPE_INT_RGB);
final JLabel l = new JLabel(new ImageIcon(bi));
final BouncingLine[] lines = new BouncingLine[20000];
for (int ii=0; ii<lines.length; ii++) {
lines[ii] = new BouncingLine(w*8,h*8);
}
final Font font = new Font("Arial", Font.BOLD, 30);
ActionListener al = new ActionListener() {
int count = 0;
long lastTime;
String fps = "";
public void actionPerformed(ActionEvent ae) {
count++;
Graphics2D g = bi.createGraphics();
g.setRenderingHints(hints);
g.clearRect(0,0,w,h);
for (int ii=0; ii<lines.length; ii++) {
lines[ii].move();
lines[ii].paint(g);
}
if ( System.currentTimeMillis()-lastTime>1000 ) {
lastTime = System.currentTimeMillis();
fps = count + " FPS";
count = 0;
}
g.setColor(Color.YELLOW);
g.setFont(font);
g.drawString(fps,10,30);
l.repaint();
g.dispose();
}
};
Timer timer = new Timer(1,al);
timer.start();
JOptionPane.showMessageDialog(null, l);
System.exit(0);
}
}
class BouncingLine {
private final Color color;
private static final BasicStroke stroke = new BasicStroke(4);
private static final Random random = new Random();
Line2D line;
int w;
int h;
int x1;
int y1;
int x2;
int y2;
BouncingLine(int w, int h) {
line = new Line2D.Double(random.nextInt(w),random.nextInt(h),random.nextInt(w),random.nextInt(h));
this.w = w;
this.h = h;
this.color = new Color(
128+random.nextInt(127),
128+random.nextInt(127),
128+random.nextInt(127),
85
);
x1 = (random.nextBoolean() ? 1 : -1);
y1 = (random.nextBoolean() ? 1 : -1);
x2 = -x1;
y2 = -y1;
}
public void move() {
int tx1 = 0;
if (line.getX1()+x1>0 && line.getX1()+x1<w) {
tx1 = (int)line.getX1()+x1;
} else {
x1 = -x1;
tx1 = (int)line.getX1()+x1;
}
int ty1 = 0;
if (line.getY1()+y1>0 && line.getY1()+y1<h) {
ty1 = (int)line.getY1()+y1;
} else {
y1 = -y1;
ty1 = (int)line.getY1()+y1;
}
int tx2 = 0;
if (line.getX2()+x2>0 && line.getX2()+x2<w) {
tx2 = (int)line.getX2()+x2;
} else {
x2 = -x2;
tx2 = (int)line.getX2()+x2;
}
int ty2 = 0;
if (line.getY2()+y2>0 && line.getY2()+y2<h) {
ty2 = (int)line.getY2()+y2;
} else {
y2 = -y2;
ty2 = (int)line.getY2()+y2;
}
line.setLine(tx1,ty1,tx2,ty2);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
g2.setStroke(stroke);
//line.set
g2.draw(line);
}
}
Update 1
When I posted that code, I thought you said 100s to 1000s, rather than 1000s to 100,000s! At 20,000 lines the rate drops to around 16-18 FPS.
Update 2
..is this optimized approach, using layers, possible in Java?
Sure. I use that technique in DukeBox - which shows a funky plot of the sound it is playing. It keeps a number of buffered images.
Background. A solid color in a non-transparent image.
Old Traces. The older sound traces as stretched or faded from the original positions. Has transparency, to allow the BG to show.
Latest Trace. Drawn on top of the other two. Has transparency.
After a day of no proposed solutions, I started to think that Java Graphics cannot erase individual items back to a transparent color. But it turns out that the improved Graphics2D, together with BufferedImage and AlphaComposite, provide pretty much exactly the functionality I was looking for, allowing me to both draw shapes and erase shapes (back to full transparency) in various layers.
Now I do the following in start():
screenBuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
screenBufferGraphics = screenBuffer.createGraphics();
overlayBuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
overlayBufferGraphics = overlayBuffer.createGraphics();
I have to use new BufferedImage() instead of createImage() because I need to ask for alpha. (Even for screenBuffer, although it is the background -- go figure!) I use createGraphics() instead of getGraphics() just because my variable screenBufferGraphics is now a Graphics2D object instead of just a Graphics object. (Although casting back and forth works fine too.)
The code in paint() is barely different:
g.drawImage(screenBuffer, 0, 0, null);
g.drawImage(overlayBuffer, 0, 0, null);
And objects are rendered (or erased) like this:
// render to background
screenBufferGraphics.setColor(Color.red);
screenBufferGraphics.fillOval(80,80, 40,40);
// render to overlay
overlayBufferGraphics.setComposite(AlphaComposite.SrcOver);
overlayBufferGraphics.setColor(Color.green);
overlayBufferGraphics.fillOval(90,70, 20,60);
// render invisibility onto overlay
overlayBufferGraphics.setComposite(AlphaComposite.DstOut);
overlayBufferGraphics.setColor(Color.blue);
overlayBufferGraphics.fillOval(70,90, 30,20);
// and flush just this locally changed region
repaint(60,60, 80,80);
The final Color.blue yields transparency, not blueness -- it can be any color that has no transparency.
As a final note, if you are rendering in a different thread from the AWT-EventQueue thread (which you probably are if you spend a lot of time rendering but also need to have a responsive interface), then you will want to synchronize the above code in paint() with your rendering routine; otherwise the display can wind up in a half-drawn state.
If you are rendering in more than one thread, you will need to synchronize the rendering routine anyway so that the Graphics2D state changes do not interfere with each other. (Or maybe each thread could have its own Graphics2D object drawing onto the same BufferedImage -- I didn't try that.)
It looks so simple, it's hard to believe how long it took to figure out how to do this!

User-selected marker in time series data in Java

My code plots 5000 points of time series data in a panel that is 581 pixels wide by default, but this width changes when the user resizes the window. My code also plots several rectangular markers that each identify a local maximum/peak in this same space.
I need to enable the user to right click on any of the rectangular-peak-markers so that the user can manually delete any false peak. The problem is that my code is reporting different x-coordinates than expected when the user right-clicks on a peak-marker. I suspect that the reason may have to do with rounding error in converting from 581 x-pixels back to 5000 data indices. But I am not certain of the reason.
Can anyone suggest a solution that enables my users to manually select one of the above-described peak markers by right-clicking on it?
I am enclosing relevant sections of the code below. My actual code is very, very long, and too complicated to post. But the relevant portions below should be enough for someone to see the logic of my approach, and to then suggest a more effective approach.
The code that declares the class in question is:
class SineDraw extends JPanel implements MouseMotionListener, MouseListener {
// lots of code, including the two segments excerpted below
}
This segment of code overloads the paintComponent of the JPanel so that my data is plotted:
// declare some variables
ArrayList<Double> PeakList = new ArrayList<Double>() // this ArrayList is populated by an extraneous process
visiblePoints = 5000
hstep = getWidth()/visiblePoints //=581/5000 by default, but will change when user resizes window
int numPeaks = PeakList.size();
// scale (y-coordinate) data relative to height of panel
pts = new double[visiblePoints]
for (int i = 0; i < pts.length-1; i++){pts[i]=//data vertical scaled to fill panel;}
// plot the 5000 time-series-data-points within the 581 pixels in x-axis
for (int i = 1; i < visiblePoints; i++) {
int x1 = (int) ((i - 1) * hstep);
int x2 = (int) (i * hstep);
int y1 = (int)pts[i - 1];
int y2 = (int)pts[i];
g2.drawLine(x1, y1, x2, y2);
}
// plot a rectangle for each of the local peaks
for(int m=0;m<=(numPeaks-1);m++){
if(i==(int)(PeakList.get(m)){
int currentVal = (int)pts[(int)(PeakList.get(m)];
g2.drawRect((int)(PeakList.get(m), currentVal, 6, 6);
}
}
This section of code is for handling the right-clicking of the mouse:
public void mousePressed(MouseEvent e){
// check to see if right mouse button was clicked
boolean jones = (e.getModifiers()&InputEvent.BUTTON3_MASK)==InputEvent.BUTTON3_MASK;
if(jones==true){
// test the value returned as x-coordinate when user right-clicks (code always underestimates x-coordinate of local peaks by this test)
double ReverseHstep = visiblePoints/getWidth();
int getX_ConvertedTo_i = (int) (e.getX()*ReverseHstep);
System.out.println("getX_ConvertedTo_i is: "+getX_ConvertedTo_i );
// check to see if peaklist contains a value within the x-coordinates of the user-selected-rectangle
if(PeakList.contains((double)(e.getX()-3))
||PeakList.contains((double)(e.getX()-2))
||PeakList.contains((double)(e.getX()-1))
||PeakList.contains((double)(e.getX()))
||PeakList.contains((double)(e.getX()+1))
||PeakList.contains((double)(e.getX()+2))
||PeakList.contains((double)(e.getX()+3))
){
// handling code will go here, but for now it is a print test that never succeeds because x-coordinate is always underestimated
System.out.println("You just selected a peak!");
}
}
repaint();
}
I suggest you create objects (in this case Rectangles) for each thing you want to be clickable. Here is an over-simplified example of how you can make something you draw clickable. The key thing to take away from this is the mouseClicked method which will display a dialog only if the mouse clicked within the rectangle.
One tricky point is that I wasn't able to figure out how to make the rectangle filled in with color without drawing another rectangle over it. I'll leave that one for you ;-)
public class Canvas extends JPanel implements MouseListener{
private Rectangle rect = new Rectangle(100,100);
public Canvas(){
this.addMouseListener(this);
rect.setSize(100, 100);
}
#Override
public void paintComponent(Graphics g){
g.setClip(rect);
g.setColor(Color.RED);
g.fillRect(0, 0, 100, 100);
}
#Override
public void mouseClicked(MouseEvent e){
if(rect.contains(e.getPoint())){
JOptionPane.showConfirmDialog(this, "Click!");
}
}
// The rest of the MouseListener methods have been cut out
public static void main(String[] a){
JFrame frame = new JFrame("Canvas Thingy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 300, 300);
frame.add(new Canvas());
frame.setVisible(true);
}
}

Categories