How to stop my bubbles animation from flickering? Tried nearly everything - java

I'm in despair, because my animation isn't as smooth as I expected. So I know, there is a lot of stuff around this problem, but mine is different in that way, that I know the common problems and I think, I'm doing it right. So firstly, this is my code:
Game.java
import de.lwerner.collisions.CircleCollision;
import de.lwerner.collisions.math.Vector2D;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class Game extends JPanel implements ActionListener {
private static final Color BACKGROUND_COLOR = new Color(0, 0, 25);
private static final Color TEXT_COLOR = Color.WHITE;
private static final int TARGET_FPS = 60;
private javax.swing.Timer swingTimer;
private JFrame window;
private Timer timer;
private Timer fpsTimer;
private int counter;
private long[] diffs;
private int fps;
private LinkedList<Circle> circles;
private LinkedList<Sprite> sprites;
public Game() {
timer = new Timer();
fpsTimer = new Timer(System.currentTimeMillis());
diffs = new long[TARGET_FPS];
circles = new LinkedList<>();
circles.add(new Circle(100, 100, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(250, 250, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(400, 400, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(550, 550, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(700, 700, 50, 300, 300, Color.WHITE));
// circles.add(new Circle(100, 700, 50, -300, 300, Color.WHITE));
// circles.add(new Circle(250, 550, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(550, 250, 50, 300, -300, Color.WHITE));
// circles.add(new Circle(700, 100, 50, -300, 300, Color.WHITE));
sprites = new LinkedList<>();
sprites.addAll(circles);
window = new JFrame("Game");
window.setContentPane(this);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setUndecorated(true);
window.setResizable(false);
window.validate();
window.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
stop();
}
});
window.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
stop();
}
});
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(window);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Sprite s: sprites) {
s.render(g);
}
g.setColor(TEXT_COLOR);
g.drawString(fps + " FPS", 10, 20);
diffs[counter % TARGET_FPS] = fpsTimer.tick();
if (++counter % TARGET_FPS == 0) {
int sum = 0;
for (long diff: diffs) {
sum += diff;
}
fps = 1000 / (sum / TARGET_FPS);
}
}
private void step() {
long tick = timer.tick();
for (Sprite s: sprites) {
s.update(tick);
}
repaint();
checkCollisions();
}
private void checkCollisions() {
for (Sprite s1: sprites) {
BoundingBox bb = s1.getBoundingBox();
int offset = 0;
if (s1 instanceof Circle) {
offset = ((Circle) s1).getRadius();
}
if (bb.getLeft() < 0 || bb.getRight() >= getWidth()) {
s1.setVelX(-s1.getVelX());
if (bb.getLeft() < 0) {
s1.setX(0 + offset);
} else {
s1.setX(getWidth() - 1 - offset);
}
}
if (bb.getTop() < 0 || bb.getBottom() >= getHeight()) {
s1.setVelY(-s1.getVelY());
if (bb.getTop() < 0) {
s1.setY(0 + offset);
} else {
s1.setY(getHeight() - 1 - offset);
}
}
}
// Set<Set<Circle>> collidingPairs = new HashSet<>();
// for (Circle c1: circles) {
// for (Circle c2: circles) {
// if (c1 == c2) {
// continue;
// } else {
// if (c1.intersects(c2)) {
// Set<Circle> pair = new HashSet<>(Arrays.asList(c1, c2));
// if (!collidingPairs.contains(pair)) {
// collidingPairs.add(pair);
// de.lwerner.collisions.Circle cc1 = new de.lwerner.collisions.Circle(c1.getX(), c1.getY(), c1.getRadius(), new Vector2D(c1.getVelX(), c1.getVelY()));
// de.lwerner.collisions.Circle cc2 = new de.lwerner.collisions.Circle(c2.getX(), c2.getY(), c2.getRadius(), new Vector2D(c2.getVelX(), c2.getVelY()));
// CircleCollision collision = new CircleCollision(cc1, cc2);
// collision.resolveCollision();
// Vector2D v1New = cc1.getV();
// Vector2D v2New = cc2.getV();
// c1.setVelX((int) v1New.getX());
// c1.setVelY((int) v1New.getY());
// c2.setVelX((int) v2New.getX());
// c2.setVelY((int) v2New.getY());
// }
// }
// }
// }
// }
}
private void stop() {
if (swingTimer.isRunning()) {
swingTimer.stop();
window.dispose();
}
}
public void start() {
swingTimer = new javax.swing.Timer(1000 / TARGET_FPS, this);
swingTimer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Game().start());
}
}
Sprite.java
import java.awt.*;
public abstract class Sprite {
protected double x;
protected double y;
protected int width;
protected int height;
protected int velX;
protected int velY;
public Sprite(int x, int y, int width, int height) {
this(x, y, width, height, 0, 0);
}
public Sprite(int x, int y, int width, int height, int velX, int velY) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velX = velX;
this.velY = velY;
}
public int getX() {
return (int)Math.round(x);
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return (int)Math.round(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 getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}
public void update(long tick) {
x += tick * velX / 1000.0;
y += tick * velY / 1000.0;
}
public BoundingBox getBoundingBox() {
return new BoundingBox(getY(), getX() + width, getY() + height, getX());
}
public boolean intersects(Sprite other) {
return getBoundingBox().intersects(other.getBoundingBox());
}
public abstract void render(Graphics g);
}
Circle.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Circle extends Sprite {
private Color color;
private BufferedImage image;
public Circle(int x, int y, int r, Color c) {
super(x, y, r * 2, r * 2);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
public Circle(int x, int y, int r, int velX, int velY, Color c) {
super(x, y, r * 2, r * 2, velX, velY);
color = c;
// try {
// loadImage();
// } catch (Exception e) {
//
// }
}
private void loadImage() throws IOException {
image = ImageIO.read(getClass().getResource("/bubble.png"));
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getRadius() {
return width / 2;
}
public boolean intersects(Circle other) {
int dx = Math.abs(getX() - other.getX());
int dy = Math.abs(getY() - other.getY());
int r1 = getRadius();
int r2 = other.getRadius();
return dx * dx + dy * dy < (r1 + r2) * (r1 + r2);
}
#Override
public BoundingBox getBoundingBox() {
return new BoundingBox(getY() - getRadius(), getX() + getRadius(), getY() + getRadius(), getX() - getRadius());
}
#Override
public void render(Graphics g) {
if (image == null) {
g.setColor(color);
g.fillOval(getX() - getRadius(), getY() - getRadius(), width, height);
} else {
g.drawImage(image, getX() - getRadius(), getY() - getRadius(), null);
}
}
}
Timer.java
public class Timer {
private long lastTime;
public Timer() {
this(0L);
}
public Timer(long initialTime) {
lastTime = initialTime;
}
public long tick() {
if (lastTime == 0) {
lastTime = System.currentTimeMillis();
return 0;
}
long current = System.currentTimeMillis();
long diff = current - lastTime;
lastTime = current;
return diff;
}
}
BoundingBox.java
import java.awt.*;
public class BoundingBox {
private int top;
private int right;
private int bottom;
private int left;
public BoundingBox(int top, int right, int bottom, int left) {
this.top = top;
this.right = right;
this.bottom = bottom;
this.left = left;
}
public int getTop() {
return top;
}
public int getRight() {
return right;
}
public int getBottom() {
return bottom;
}
public int getLeft() {
return left;
}
public Rectangle getRectangle() {
return new Rectangle(left, top, right - left, bottom - top);
}
public boolean intersects(BoundingBox other) {
return getRectangle().intersects(other.getRectangle());
}
#Override
public String toString() {
return "BoundingBox{" +
"top=" + top +
", right=" + right +
", bottom=" + bottom +
", left=" + left +
'}';
}
}
So I don't know, what I'm doing wrong. Common problems such as calling paint(), using not-doublebuffered components, using wrong methods for periodically run code and so on aren't present, yet it's flickering. The FPS are constant.
So, please help me! I'd be very glad to come over this...
Thanks!

Related

Trying to create Circles using MouseListener and MouseMotionListener - what I am doing wrong?

I'm trying to create Circles in JFrame using JComponent. Here's what I'm trying to achieve:
And here's what's happening with my code:
I have no idea what's causing this problem. Here's my code:
CircleViewer.java
import javax.swing.JFrame;
import java.awt.event.*;
public class CircleViewer
{
public static void main(String[] args)
{
final CirclePanel panel = new CirclePanel();
class MousePressListener implements MouseListener, MouseMotionListener
{
public void mouseClicked(MouseEvent event) { }
public void mouseEntered(MouseEvent event) { }
public void mouseExited(MouseEvent event) { }
public void mouseWheelMoved(MouseWheelEvent event) { }
public void mouseMoved(MouseEvent event) { }
public void mousePressed(MouseEvent event)
{
var x = event.getX();
var y = event.getY();
panel.addCircle(x, y);
}
public void mouseDragged(MouseEvent event)
{
var x = event.getX();
var y = event.getY();
panel.moveTo(x, y);
}
public void mouseReleased(MouseEvent event)
{
panel.finalMove();
}
}
MousePressListener listener = new MousePressListener();
panel.addMouseListener(listener);
panel.addMouseMotionListener(listener);
JFrame frame = new JFrame("Circle Shapes");
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HEIGHT = 500;
}
CirclePanel.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.util.ArrayList;
import java.awt.Color;
import java.lang.Math;
import java.awt.BasicStroke;
import java.awt.Stroke;
public class CirclePanel extends JComponent
{
private int lineX;
private int lineY;
private boolean isDraged;
private ArrayList<Circle> circleList;
private BasicStroke dashLine;
public CirclePanel()
{
this.circleList = new ArrayList<Circle>();
this.isDraged = false;
this.lineX = 0;
this.lineY = 0;
this.dashLine = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{6}, 0);
}
public void addCircle(int x, int y)
{
lineX = x;
lineY = y;
isDraged = true;
circleList.add(new Circle(x, y, 0, Color.RED));
repaint();
}
public void moveTo(int x, int y)
{
var circleTemp = circleList.get(circleList.size() - 1);
isDraged = true;
var tempR = (int)Math.sqrt(Math.pow(x - circleTemp.get(0), 2) + Math.pow(y - circleTemp.get(1), 2));
System.out.println(tempR);
var tempX = circleTemp.get(0) - (tempR / 2);
var tempY = circleTemp.get(1) - (tempR / 2);
circleList.get(circleList.size() - 1).setCords(tempX, tempY, tempR);
lineX = x;
lineY = y;
repaint();
}
public void finalMove()
{
isDraged = false;
circleList.get(circleList.size() - 1).setColor(Color.BLUE);
repaint();
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Stroke defaultStroke;
defaultStroke = g2.getStroke();
if (!circleList.isEmpty())
{
if (isDraged)
{
g2.setColor(Color.RED);
g2.setStroke(dashLine);
g2.drawLine(circleList.get(circleList.size() - 1).get(0), circleList.get(circleList.size() - 1).get(1), lineX, lineY);
}
for (Circle circle : circleList)
{
g2.setStroke(defaultStroke);
circle.draw(g2);
isDraged = false; //this is prob reduntant
}
}
}
}
And finally, Circle.java
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
public class Circle
{
private int x;
private int y;
private int radius;
private Color color;
public Circle(int x, int y, int radius, Color color)
{
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
public int get(int option)
{
switch (option)
{
case 0:
return this.x;
case 1:
return this.y;
case 2:
return this.radius;
}
return 0;
}
public Color get()
{
return this.color;
}
public void setCords(int x, int y, int r)
{
this.x = x;
this.y = y;
this.radius = r;
}
public void set(int option, int value)
{
switch (option)
{
case 0: //set x
this.x = value;
break;
case 1:
this.y = value;
break;
case 2:
radius = value;
break;
}
}
public void setColor(Color color)
{
this.color = color;
}
public void draw(Graphics2D g2)
{
g2.setColor(color);
g2.draw(new Ellipse2D.Double(x, y, radius, radius));
}
}
Rather than finding the specific problem in you code, I just decided to make a cleaner implementation. Using this circle class
class Circle {
final int x;
final int y;
int radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}
You can implement CirclePanel like this:
public class CirclePanel extends JPanel {
private static final Stroke DASHED = new BasicStroke(1,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL,
0, new float[]{6}, 0);
public Color oldCircleColor = Color.BLUE;
public Color newCircleColor = Color.RED;
public Color backgroundColor = Color.LIGHT_GRAY;
private final List<Circle> oldCircles = new ArrayList<>();
private Circle newCircle = null;
private int mouseX = 0;
private int mouseY = 0;
private class MouseHelper implements MouseListener, MouseMotionListener {
#Override public void mouseMoved(MouseEvent e) {}
#Override public void mouseClicked(MouseEvent e) {}
#Override public void mousePressed(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseExited(MouseEvent e) {}
#Override
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if (newCircle == null) {
newCircle = new Circle(mouseX, mouseY, 0);
} else {
int dX = newCircle.x - mouseX;
int dY = newCircle.y - mouseY;
newCircle.radius = (int) Math.sqrt(dX*dX + dY*dY);
}
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (newCircle != null) {
oldCircles.add(newCircle);
newCircle = null;
repaint();
}
}
}
public CirclePanel() {
MouseHelper helper = new MouseHelper();
addMouseListener(helper);
addMouseMotionListener(helper);
setPreferredSize(new Dimension(400, 400));
}
#Override
public void paint(Graphics g) {
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(oldCircleColor);
for (Circle c : oldCircles) {
drawCircle(g, c);
}
Circle c = newCircle;
if (c != null) {
g.setColor(newCircleColor);
drawCircle(g, c);
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(DASHED);
g2.drawLine(c.x, c.y, mouseX, mouseY);
g2.dispose();
}
}
private void drawCircle(Graphics g, Circle c) {
// note: drawOval takes top-left corner and diameter, NOT center and radius
g.drawOval(c.x - c.radius, c.y - c.radius, c.radius * 2, c.radius * 2);
}
}
And test to see that it works
public static void main(String[] args) {
JFrame frame = new JFrame();
CirclePanel panel = new CirclePanel();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Like #SirLenz0rlot mentioned in the comments there is a bug in your moveTo method. The problem is the call circleList.get(circleList.size() - 1).setCords(tempX, tempY, tempR); which is setting the position of the circle to tempX, tempY, but you probably only want to set the radius of the circle, while the coords are not changed.
Changing the moveTo method to the code below should help:
public void moveTo(int x, int y)
{
var circleTemp = circleList.get(circleList.size() - 1);
isDraged = true;
var tempR = (int)Math.sqrt(Math.pow(x - circleTemp.get(0), 2) + Math.pow(y - circleTemp.get(1), 2));
System.out.println(tempR);
var tempX = circleTemp.get(0) - (tempR / 2);
var tempY = circleTemp.get(1) - (tempR / 2);
//EDITED HERE
circleList.get(circleList.size() - 1).setCords(circleTemp.get(0), circleTemp.get(1), tempR);//using getX() and getY() on your circle would be easier to understand here, but this should also work...
lineX = x;
lineY = y;
repaint();
}
For some reason your circleTemp.get(0) and (1) doesn't give you the (x,y) coordinates
circleTemp.get(0)
What you should do is save the circle's (x,y) coordinates, and use them in the moveTo method.
Correct Change
And in the end for the draw line, you should again, use the saved (x,y) coordinates and the new coordinated of the mouse. (not the circleList.size() -1).get(0) - Line 67)
(Ex. I added the drawLineX and drawLineY)

Java 2D Platformer Collision Detection for multiple Rectangles

I am working on a 2D platformer in Java for an assignment. The assignment specifies I must use an abstract shape class to draw shapes. The problem I am having is getting my collision detection to work with multiple Rectangle Objects which I am using as platforms - I store these in a list. At the moment my collision detection will move my player regardless of which platform I have collided with, so if I collide with a platform from the right it will move me to the top of that platform because it's still checking another platform below me, and will assume I've hit that, therefore moving me to the top of the platform. I was wondering how I can change this so that my collision detection also detects which platform I have collided with and collide relative to that platform (as opposed to every platform).
Here's what is currently happening:
Expected Output:
My player should stop where it is when colliding with platforms.
My App class:
package A2;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class App extends JFrame {
public App() {
final Player player = new Player(200, 100);
final ArrayList<Rectangle> platforms = new ArrayList<>();
platforms.add(new Rectangle(100, 500, 400 ,10));
platforms.add(new Rectangle(500, 100, 10 ,400));
JPanel mainPanel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
player.draw(g);
for(Rectangle r : platforms){
r.draw(g);
}
}
};
mainPanel.addKeyListener(new InputControl(this, player, platforms));
mainPanel.setFocusable(true);
add(mainPanel);
setLayout(new GridLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 600);
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
abstract class Shape {
public void draw(Graphics g) { }
}
My input handling class:
package A2;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import static java.awt.event.KeyEvent.*;
public class InputControl implements ActionListener, KeyListener {
App app;
Player player;
Timer time = new Timer(5, this);
ArrayList<Rectangle> platforms;
ArrayList<Integer> keyList = new ArrayList<>();
boolean keyReleased = false;
boolean keyPressed = false;
boolean[] keyUp = new boolean[256];
boolean[] keyDown = new boolean[256];
boolean topCollision = false;
boolean rightCollision = false;
boolean leftCollision = false;
boolean botCollision = false;
boolean onGround = false;
private static final double GRAVITY = 2;
private static final int MAX_FALL_SPEED = 5;
double Xoverlap = 0;
double Yoverlap = 0;
boolean collision = false;
public InputControl(App app, Player player, ArrayList<Rectangle> platforms) {
this.app = app;
this.player = player;
this.platforms = platforms;
time.start();
}
public void gravity(){
if(player.yVelocity > MAX_FALL_SPEED){
player.yVelocity = MAX_FALL_SPEED;
}
player.yVelocity += GRAVITY;
}
public void momentum(){}
public void actionPerformed(ActionEvent e) {
Rectangle2D offset = player.getOffsetBounds();
for(int i = 0; i < platforms.size(); i++) {
Rectangle r = platforms.get(i);
//If collision
if (offset.intersects(r.obj.getBounds2D())) {
//Collision on Y axis
if (offset.getX() + offset.getWidth() > r.obj.getX() &&
offset.getX() < r.obj.getX() + r.obj.getWidth() &&
offset.getY() + offset.getHeight() > r.obj.getY() &&
offset.getY() + player.yVelocity < r.obj.getY() + r.obj.getHeight()) {
player.y -= (offset.getY() + offset.getHeight()) - r.obj.getY();
}
//Collision on X axis
if (offset.getX() + offset.getWidth() + player.xVelocity > r.obj.getX() &&
offset.getX() + player.xVelocity < r.obj.getX() + r.obj.getWidth() &&
offset.getY() + offset.getHeight() > r.obj.getY() &&
offset.getY() < r.obj.getY() + r.obj.getHeight()) {
player.x -= (offset.getX() + offset.getHeight()) - r.obj.getX();
}
}
else {
player.x += player.xVelocity;
player.y += player.yVelocity;
}
}
player.x += player.xVelocity;
player.y += player.yVelocity;
app.repaint();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() >= 0 && e.getKeyCode() < 256) {
keyDown[e.getKeyCode()] = true;
keyUp[e.getKeyCode()] = false;
keyPressed = true;
keyReleased = false;
}
if (keyDown[VK_UP]) {
player.yVelocity = -1;
}
if (keyDown[VK_RIGHT]){
player.xVelocity = 1;
}
if (keyDown[VK_LEFT]) {
player.xVelocity = -1;
}
if (keyDown[VK_DOWN]) {
player.yVelocity = 1;
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() >= 0 && e.getKeyCode() < 256) {
keyDown[e.getKeyCode()] = false;
keyUp[e.getKeyCode()] = true;
keyPressed = false;
keyReleased = true;
}
if(keyUp[VK_RIGHT] || keyUp[VK_LEFT]){
player.xVelocity = 0;
}
if(keyUp[VK_UP]){
player.yVelocity = 0;
}
}
public void keyTyped(KeyEvent e) { }
}
My Player class:
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Player extends Shape {
public double xVelocity;
public double yVelocity;
public double x;
public double y;
public double width = 60;
public double height = 60;
public double weight = 5;
public Rectangle2D obj;
public Player(double x, double y) {
this.x = x;
this.y = y;
obj = new Rectangle2D.Double(x, y, width, height);
}
public Rectangle2D getOffsetBounds(){
return new Rectangle2D.Double( x, y, width, height);
}
public void draw(Graphics g) {
Color c =new Color(1f,0f,0f,0.2f );
obj = new Rectangle2D.Double(x, y, width, height);
g.setColor(Color.BLACK);
Graphics2D g2 = (Graphics2D)g;
g2.fill(obj);
g.drawString("(" + String.valueOf(x) + ", " + String.valueOf(y) + ")", 10, 20);
g.drawString("X Speed: " + String.valueOf(xVelocity) + " Y Speed: " + String.valueOf(yVelocity) + ")", 10, 35);
g.setColor(c);
}
}
My Rectangle class:
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Rectangle extends Shape {
public double width;
public double height;
public double x;
public double y;
boolean hasCollided = false;
public Rectangle2D obj;
public Rectangle(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
obj = new Rectangle2D.Double(x, y, width, height);
}
public void draw(Graphics g) {
g.setColor(Color.ORANGE);
Graphics2D g2 = (Graphics2D)g;
g2.fill(obj);
}
}
First, define ColorRectangle class that extends Shape and provide logic for drawing:
// extends java.awt.Shape
abstract class ColorRectangle extends Rectangle {
private static final long serialVersionUID = -3626687047605407698L;
private final Color color;
protected ColorRectangle(int x, int y, int width, int height, Color color) {
super(x, y, width, height);
this.color = color;
}
public void draw(Graphics2D g) {
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
Second, define separate class for represent Player and Platform:
public final class Player extends ColorRectangle {
private static final long serialVersionUID = -3909362955417024742L;
public Player(int width, int height, Color color) {
super(0, 0, width, height, color);
}
}
public final class Platform extends ColorRectangle {
private static final long serialVersionUID = 6602359551348037628L;
public Platform(int x, int y, int width, int height, Color color) {
super(x, y, width, height, color);
}
public boolean intersects(Player player, int offsX, int offsY) {
return intersects(player.x + offsX, player.y + offsY, player.width, player.height);
}
}
Third, define class that contains logic of demo application. Actually, you could split logic for demo and logic for board (including actiona and key listeners), but these classes are very simple, so in given case, no need to split it.
public class CollisionDetectionDemo extends JFrame {
public CollisionDetectionDemo() {
setLayout(new GridLayout());
add(new MainPanel());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 600);
}
private static class MainPanel extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 8771401446680969350L;
private static final int OFFS = 5;
private final Player player = new Player(60, 60, Color.BLACK);
private final List<Platform> platforms = Arrays.asList(
new Platform(100, 500, 400, 10, Color.ORANGE),
new Platform(500, 100, 10, 410, Color.RED),
new Platform(150, 300, 100, 10, Color.BLUE),
new Platform(150, 100, 100, 10, Color.GREEN));
private MainPanel() {
player.x = 200;
player.y = 200;
new Timer(5, this).start();
setFocusable(true);
addKeyListener(this);
}
private void drawPlayerPosition(Graphics g) {
g.setColor(Color.BLACK);
g.drawString(String.format("(%d, %d)", player.x, player.y), 10, 20);
}
private void movePlayer(int offsX, int offsY) {
if (!intersects(player, offsX, offsY)) {
player.x += offsX;
player.y += offsY;
}
}
private boolean intersects(Player player, int offsX, int offsY) {
for (Platform platform : platforms)
if (platform.intersects(player, offsX, offsY))
return true;
return false;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Color color = g.getColor();
drawPlayerPosition(g);
player.draw((Graphics2D)g);
platforms.forEach(platform -> platform.draw((Graphics2D)g));
g.setColor(color);
}
#Override
public void actionPerformed(ActionEvent event) {
repaint();
}
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == VK_UP)
movePlayer(0, -OFFS);
else if (event.getKeyCode() == VK_DOWN)
movePlayer(0, OFFS);
else if (event.getKeyCode() == VK_LEFT)
movePlayer(-OFFS, 0);
else if (event.getKeyCode() == VK_RIGHT)
movePlayer(OFFS, 0);
}
#Override
public void keyReleased(KeyEvent event) {
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CollisionDetectionDemo().setVisible(true));
}
}

java - Graphics2D rendering is too slow?

I was making a class for rectangles that are able to change angle, fill color, line color, line thickness. And the rectangles are to be rendered that way. I decided to do a little check up. During the check, I found out that the rectangles are rendered too slowly. I could see them being rendered from top to bottom. What might be the reason?
GEdit
import javax.swing.*;
public class GEdit {
public static void main(String[] args)
{
frame app = new frame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(1000,1000);
app.setVisible(true);
}
}
Figure.java
import java.awt.*;
import java.awt.geom.Point2D;
public abstract class Figure
{
public static final int TOPLEFT = 0;
public static final int TOPCENTER = 1;
public static final int TOPRIGHT = 2;
public static final int CENTERLEFT = 3;
public static final int CENTER = 4;
public static final int CENTERRIGHT = 5;
public static final int BOTTOMLEFT = 6;
public static final int BOTTOMCENTER = 7;
public static final int BOTTOMRIGHT = 8;
private boolean fill_able;
private int fill_option;
private Color fill_color;
private int fill_transparency;
private Color line_color;
private float line_thickness;
private int line_transparency;
private int width;
private int height;
private float rotate_angle;
private boolean width_height_ratio_fixed;
private Point location;
private int base;
public Figure(boolean fill_able,
int fill_option,
Color fill_color,
int fill_transparency,
Color line_color,
float line_thickness,
int line_transparency,
int width, int height,
float rotate_angle,
boolean width_height_ratio_fixed,
int x, int y,
int base)
{
this.fill_able = fill_able;
this.fill_option = fill_option;
this.fill_color = fill_color;
this.fill_transparency = fill_transparency;
this.line_color = line_color;
this.line_thickness = line_thickness;
this.line_transparency = line_transparency;
this.width = width;
this.height = height;
this.rotate_angle = rotate_angle;
this.width_height_ratio_fixed = width_height_ratio_fixed;
this.location = new Point(x,y);
this.base = base;
}
public boolean is_fill_able()
{
return fill_able;
}
public int get_fill_option()
{
return fill_option;
}
public Color get_fill_color()
{
return fill_color;
}
public int get_fill_transparency()
{
return fill_transparency;
}
public Color get_line_color()
{
return line_color;
}
public float get_line_thickness()
{
return line_thickness;
}
public int get_line_transparency()
{
return line_transparency;
}
public int get_width()
{
return width;
}
public int get_height()
{
return height;
}
public float get_rotate_angle()
{
return rotate_angle;
}
public boolean is_width_height_ratio_fixed()
{
return width_height_ratio_fixed;
}
public Point get_location()
{
return location;
}
public Point get_render_location()
{
int x, y;
switch(base)
{
case TOPLEFT:
x = location.x;
y = location.y;
break;
case TOPCENTER:
x = location.x - (int)Math.round(width / 2);
y = location.y;
break;
case TOPRIGHT:
x = location.x - width;
y = location.y;
break;
case CENTERLEFT:
x = location.x;
y = location.y - (int)Math.round(height / 2);
break;
case CENTER:
x = location.x - (int)Math.round(width / 2);
y = location.y - (int)Math.round(height / 2);
break;
case CENTERRIGHT:
x = location.x - width;
y = location.y - (int)Math.round(height / 2);
break;
case BOTTOMLEFT:
x = location.x;
y = location.y - height;
break;
case BOTTOMCENTER:
x = location.x - (int)Math.round(width / 2);
y = location.y - height;
break;
case BOTTOMRIGHT:
x = location.x - width;
y = location.y - height;
break;
default:
x = 0; y = 0;
break;
}
return new Point(x, y);
}
public int get_base()
{
return base;
}
public void set_fill_option(int option)
{
this.fill_option = option;
}
public void set_fill_color(Color color)
{
this.fill_color = color;
}
public void set_fill_transparency(int transparency)
{
this.fill_transparency = transparency;
}
public void set_line_color(Color color)
{
this.line_color = color;
}
public void set_line_transparency(int transparency)
{
this.line_transparency = transparency;
}
public void set_width(int width)
{
if(this.width_height_ratio_fixed)
{
float ratio = this.height / this.width;
this.width = width;
this.height = (int)Math.round(width * ratio);
}
else { this.width = width;}
}
public void set_height(int height)
{
if(this.width_height_ratio_fixed)
{
float ratio = this.width / this.height;
this.height = height;
this.width = (int)Math.round(height * ratio);
}
else{ this.height = height;}
}
public void set_rotate_angle(float angle)
{
if(angle > 360)
{
this.rotate_angle = angle % 360;
}
else this.rotate_angle = angle;
}
public void set_location(int x, int y)
{
this.location.setLocation(x, y);
}
public void set_location(Point location)
{
this.location = location;
}
public void set_base(int base)
{
this.base = base;
}
abstract public void render(Graphics2D g);
}
Rectangle.java
import java.awt.*;
import java.awt.Graphics2D;
import java.awt.geom.*;
public class Rectangle extends Figure {
public Rectangle(Color fill_color, Color line_color, float line_thickness, int width, int height, int x, int y)
{
super(true,
0,
fill_color,
255,
line_color,
line_thickness,
255,
width, height,
0,
false,
x, y,
TOPLEFT);
}
public void render(Graphics2D g)
{
Rectangle2D rectangle = new Rectangle2D.Float(get_width(),get_height(),get_render_location().x,get_render_location().y);
g.rotate(Math.toRadians(get_rotate_angle()),rectangle.getCenterX(),rectangle.getCenterY());
if(is_fill_able())
{
Color color = new Color(
get_fill_color().getRed(),
get_fill_color().getGreen(),
get_fill_color().getBlue(),
get_fill_transparency());
g.setColor(color);
g.fill(rectangle);
}
Stroke old_stroke = g.getStroke();
g.setStroke(new BasicStroke(get_line_thickness()));
Color line_color = new Color(
get_line_color().getRed(),
get_line_color().getGreen(),
get_line_color().getBlue(),
get_line_transparency());
g.setColor(line_color);
g.draw(rectangle);
g.setStroke(old_stroke);
g.rotate(Math.toRadians(get_rotate_angle() * -1),rectangle.getCenterX(),rectangle.getCenterY());
}
}
frame.java
import javax.print.DocFlavor;
import javax.swing.JFrame;
import java.awt.*;
import java.util.Random;
public class frame extends JFrame{
public frame()
{
super("test");
}
#Override
public void paint(Graphics g) {
Graphics2D graphics2D = (Graphics2D)g;
RenderingHints renderingHints1 = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints renderingHints2 = new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHints(renderingHints1);
graphics2D.setRenderingHints(renderingHints2);
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0,0,1000,1000);
for(int i =0;i < 10; i++)
{
Rectangle rectangle = new Rectangle(Color.CYAN,Color.BLACK,random.nextInt(10),random.nextInt(1000),random.nextInt(1000),random.nextInt(300),random.nextInt(300));
rectangle.set_fill_transparency(random.nextInt(255));
rectangle.set_rotate_angle(random.nextInt(180));
rectangle.render(graphics2D);
}
}
}
Don't override paint of top level containers like JFrame, start with something like JPanel and override it's paintComponent method - that way you get double buffering for free.
Consider not creating new objects on each paint cycle - this is create a number of short lived objects which can affect performance
You could perform some of the operations outside of the paint method (setting the properties) and just focus on painting the inside the paint method
Remember, transformations (such as rotate and translate) are compounding, this means they will affect everything painted after them. You either need to take a snapshot of the Graphics context before hand and dispose of it when you're finished, or reverse the transformations.
You might like to take a look at Performing Custom Painting and Painting in AWT and Swing for more details about how painting works in Swing.
Without changing anything, other then using a JPanel and paintComponent, it works fine.
I even threw in a Swing Timer and repainted the panel at 25fps a second without issue. And just for fun, I set it to 200fps without issue
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Random random = new Random();
public TestPane() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
RenderingHints renderingHints1 = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints renderingHints2 = new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(renderingHints1);
g2d.setRenderingHints(renderingHints2);
for (int i = 0; i < 10; i++) {
Rectangle rectangle = new Rectangle(Color.CYAN,
Color.BLACK,
random.nextInt(10),
random.nextInt(200),
random.nextInt(200),
random.nextInt(200), random.nextInt(200));
rectangle.set_fill_transparency(random.nextInt(255));
rectangle.set_rotate_angle(random.nextInt(180));
Graphics2D iDontTrustYou = (Graphics2D) g2d.create();
rectangle.render(iDontTrustYou);
iDontTrustYou.dispose();
}
g2d.dispose();
}
}
public abstract class Figure {
public static final int TOPLEFT = 0;
public static final int TOPCENTER = 1;
public static final int TOPRIGHT = 2;
public static final int CENTERLEFT = 3;
public static final int CENTER = 4;
public static final int CENTERRIGHT = 5;
public static final int BOTTOMLEFT = 6;
public static final int BOTTOMCENTER = 7;
public static final int BOTTOMRIGHT = 8;
private boolean fill_able;
private int fill_option;
private Color fill_color;
private int fill_transparency;
private Color line_color;
private float line_thickness;
private int line_transparency;
private int width;
private int height;
private float rotate_angle;
private boolean width_height_ratio_fixed;
private Point location;
private int base;
public Figure(boolean fill_able,
int fill_option,
Color fill_color,
int fill_transparency,
Color line_color,
float line_thickness,
int line_transparency,
int width, int height,
float rotate_angle,
boolean width_height_ratio_fixed,
int x, int y,
int base) {
this.fill_able = fill_able;
this.fill_option = fill_option;
this.fill_color = fill_color;
this.fill_transparency = fill_transparency;
this.line_color = line_color;
this.line_thickness = line_thickness;
this.line_transparency = line_transparency;
this.width = width;
this.height = height;
this.rotate_angle = rotate_angle;
this.width_height_ratio_fixed = width_height_ratio_fixed;
this.location = new Point(x, y);
this.base = base;
}
public boolean is_fill_able() {
return fill_able;
}
public int get_fill_option() {
return fill_option;
}
public Color get_fill_color() {
return fill_color;
}
public int get_fill_transparency() {
return fill_transparency;
}
public Color get_line_color() {
return line_color;
}
public float get_line_thickness() {
return line_thickness;
}
public int get_line_transparency() {
return line_transparency;
}
public int get_width() {
return width;
}
public int get_height() {
return height;
}
public float get_rotate_angle() {
return rotate_angle;
}
public boolean is_width_height_ratio_fixed() {
return width_height_ratio_fixed;
}
public Point get_location() {
return location;
}
public Point get_render_location() {
int x, y;
switch (base) {
case TOPLEFT:
x = location.x;
y = location.y;
break;
case TOPCENTER:
x = location.x - (int) Math.round(width / 2);
y = location.y;
break;
case TOPRIGHT:
x = location.x - width;
y = location.y;
break;
case CENTERLEFT:
x = location.x;
y = location.y - (int) Math.round(height / 2);
break;
case CENTER:
x = location.x - (int) Math.round(width / 2);
y = location.y - (int) Math.round(height / 2);
break;
case CENTERRIGHT:
x = location.x - width;
y = location.y - (int) Math.round(height / 2);
break;
case BOTTOMLEFT:
x = location.x;
y = location.y - height;
break;
case BOTTOMCENTER:
x = location.x - (int) Math.round(width / 2);
y = location.y - height;
break;
case BOTTOMRIGHT:
x = location.x - width;
y = location.y - height;
break;
default:
x = 0;
y = 0;
break;
}
return new Point(x, y);
}
public int get_base() {
return base;
}
public void set_fill_option(int option) {
this.fill_option = option;
}
public void set_fill_color(Color color) {
this.fill_color = color;
}
public void set_fill_transparency(int transparency) {
this.fill_transparency = transparency;
}
public void set_line_color(Color color) {
this.line_color = color;
}
public void set_line_transparency(int transparency) {
this.line_transparency = transparency;
}
public void set_width(int width) {
if (this.width_height_ratio_fixed) {
float ratio = this.height / this.width;
this.width = width;
this.height = (int) Math.round(width * ratio);
} else {
this.width = width;
}
}
public void set_height(int height) {
if (this.width_height_ratio_fixed) {
float ratio = this.width / this.height;
this.height = height;
this.width = (int) Math.round(height * ratio);
} else {
this.height = height;
}
}
public void set_rotate_angle(float angle) {
if (angle > 360) {
this.rotate_angle = angle % 360;
} else {
this.rotate_angle = angle;
}
}
public void set_location(int x, int y) {
this.location.setLocation(x, y);
}
public void set_location(Point location) {
this.location = location;
}
public void set_base(int base) {
this.base = base;
}
abstract public void render(Graphics2D g);
}
public class Rectangle extends Figure {
public Rectangle(Color fill_color, Color line_color, float line_thickness, int width, int height, int x, int y) {
super(true,
0,
fill_color,
255,
line_color,
line_thickness,
255,
width, height,
0,
false,
x, y,
TOPLEFT);
}
public void render(Graphics2D g) {
Rectangle2D rectangle = new Rectangle2D.Float(get_width(), get_height(), get_render_location().x, get_render_location().y);
g.rotate(Math.toRadians(get_rotate_angle()), rectangle.getCenterX(), rectangle.getCenterY());
if (is_fill_able()) {
Color color = new Color(
get_fill_color().getRed(),
get_fill_color().getGreen(),
get_fill_color().getBlue(),
get_fill_transparency());
g.setColor(color);
g.fill(rectangle);
}
Stroke old_stroke = g.getStroke();
g.setStroke(new BasicStroke(get_line_thickness()));
Color line_color = new Color(
get_line_color().getRed(),
get_line_color().getGreen(),
get_line_color().getBlue(),
get_line_transparency());
g.setColor(line_color);
g.draw(rectangle);
g.setStroke(old_stroke);
g.rotate(Math.toRadians(get_rotate_angle() * -1), rectangle.getCenterX(), rectangle.getCenterY());
}
}
}
A slightly better optimised version might look something like...
public class TestPane extends JPanel {
private Random random = new Random();
private List<Rectangle> rectangles = new ArrayList<>(25);
public TestPane() {
for (int i = 0; i < 1000; i++) {
Rectangle rectangle = new Rectangle(Color.CYAN,
Color.BLACK,
random.nextInt(10),
random.nextInt(200),
random.nextInt(200),
random.nextInt(200), random.nextInt(200));
rectangle.set_fill_transparency(random.nextInt(255));
rectangle.set_rotate_angle(random.nextInt(180));
rectangles.add(rectangle);
}
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Rectangle rectangle : rectangles) {
rectangle.set_height(random.nextInt(200));
rectangle.set_width(random.nextInt(200));
rectangle.set_location(random.nextInt(200), random.nextInt(200));
rectangle.set_fill_transparency(random.nextInt(255));
rectangle.set_rotate_angle(random.nextInt(180));
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
RenderingHints renderingHints1 = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
RenderingHints renderingHints2 = new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(renderingHints1);
g2d.setRenderingHints(renderingHints2);
for (Rectangle rectangle : rectangles) {
Graphics2D iDontTrustYou = (Graphics2D) g2d.create();
rectangle.render(iDontTrustYou);
iDontTrustYou.dispose();
}
g2d.dispose();
}
}
If you still find that the performance isn't up to what you want, you might consider having a look at BufferStrategy which will give you complete control over the painting process
You are overriding the method paint, which is usually a bad idea.
You are also calculating all the information needed DURING the paint, which is another bad idea: they should be calculated before. If you need 4x10 random numbers, maybe calculate them before the paint and store the 40 numbers in a int[] array.
As someone mentioned, you should want to use a JPanel and the method paintComponent.
The following link might be an interesting reading for you:
http://www.billharlan.com/papers/Improving_Swing_Performance.html

GUI thread move() method misbehaving

EDIT
: it seems that in my move() method, java has to skip one of the 2 if statements
Keeping it simple. I'm trying to make a GUI in java that models the following class Truck behavior: the blue squares are supposed to run up their diagonales, which they do. But when they are supposed to bounce back once they reach the edge point of the square they just fly away. I've placed a condition to prevent this, but it never passes. I'll upload GUI and Drawable, but I don't think they are needed.
Class Truck:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.plaf.ButtonUI;
public class Truck extends Thread implements Drawable {
private boolean isFull = false;
private int x, y;
private int capacity;
private Panel panel;
static int r = 20;
private int dx, dy;
private Site site;
private Building building;
public Truck(int x, int y, Panel panel, Building building, Site site) {
this.x = x;
this.y = y;
this.building = building;
this.panel = panel;
this.site = site;
this.start();
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
#Override
public void run() {
super.run();
while (true) {
move();
panel.repaint();
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setDirection(int i) {
if (i == 0) {
dx = -1;
dy = -1;
}
if (i == 1) {
dx = 1;
dy = -1;
}
if (i == 2) {
dx = -1;
dy = 1;
}
if (i == 3) {
dx = 1;
dy = 1;
}
}
private void move() {
if (site.truckOnSite(x, y)) {
site.loadTruck(this);
dx *= -1;
dy *= -1;
}
if (building.containsTruck(this)) {
building.unloadTruck(this);
dx *= -1;
dy *= -1;
}
x += dx;
y += dy;
}
public int getDx() {
return dx;
}
public void setFull(boolean isFull) {
this.isFull = isFull;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.BLUE);
if (isFull)
g.fillRect(x - 10, y - 10, r, r);
else
g.drawRect(x - 10, y - 10, r, r);
}
}
Class Panel:
package construction_site;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JPanel;
public class Panel extends JPanel {
private ArrayList<Drawable> drawables = new ArrayList<>();
private Site site;
private Building[] buildings = new Building[4];
private Truck[] trucks = new Truck[4];
private Van[] vans = new Van[4];
public Panel(int w, int h) {
setPreferredSize(new Dimension(w, h));
site = new Site(100, 75, 500, 500, this);
drawables.add(site);
buildings[0] = new Building(100, 75, this);
buildings[1] = new Building(100 + 500, 75, this);
buildings[2] = new Building(100, 75 + 500, this);
buildings[3] = new Building(100 + 500, 75 + 500, this);
for (Building b : buildings)
drawables.add(b);
trucks[0] = new Truck(100 + 250, 75 + 250, this, buildings[0], site);
trucks[1] = new Truck(100 + 250, 75 + 250, this, buildings[1], site);
trucks[2] = new Truck(100 + 250, 75 + 250, this, buildings[2], site);
trucks[3] = new Truck(100 + 250, 75 + 250, this, buildings[3], site);
for (int i = 0; i < 4; i++)
trucks[i].setDirection(i);
for (Truck t : trucks)
drawables.add(t);
}
#Override
public void paint(Graphics g) {
super.paint(g);
for (Drawable d : drawables)
d.draw(g);
g.setColor(Color.GREEN);
for (int i = 1; i <= 3; i++)
g.drawLine(buildings[0].getX(), buildings[0].getY(), buildings[i].getX(), buildings[i].getY());
g.drawLine(buildings[1].getX(), buildings[1].getY(), buildings[2].getX(), buildings[2].getY());
}
}
Class Building:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Building extends Thread implements Drawable {
private Panel panel;
private boolean done = false;
private int x, y;
static int w = 100;
static int h = 100;
private ReentrantLock lock = new ReentrantLock();
private Condition insufficientMaterial = lock.newCondition();
private Condition insufficientMisc = lock.newCondition();
private Condition sufficient = lock.newCondition();
private int material = 0;
private int misc = 0;
private int spent = 0;
public Building(int x, int y, Panel panel) {
this.x = x;
this.y = y;
this.panel = panel;
this.start();
}
#Override
public void run() {
super.run();
lock.lock();
while(material < 100 )
try {
insufficientMaterial.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
spent += 150;
misc -= 50;
material -= 100;
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void unloadVan(Van v) {
lock.lock();
System.out.println("Truck got in");
if (material >= 100 && misc >=50) {
}
misc += 50;
v.setCapacity(0);
insufficientMisc.signalAll();
lock.unlock();
}
public void unloadTruck(Truck t) {
lock.lock();
material += 10000;
t.setCapacity(0);
t.setFull(false);
insufficientMaterial.signalAll();
lock.unlock();
}
public void setMaterial(int material) {
this.material = material;
}
public void setMisc(int misc) {
this.misc = misc;
}
public boolean containsVan(int x2, int y2) {
return ( Math.sqrt((x - x2)*(x - x2) + (y - y2)*(y - y2)) <= h/2 );
}
public boolean containsTruck(Truck t) {
return (x == t.getX() && y == t.getY());
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(x - 50, y - 50, 100, 100);
}
}
Class Site:
package construction_site;
import java.awt.Color;
import java.awt.Graphics;
public class Site implements Drawable {
private int x, y, w, h;
private Panel panel;
public Site(int x, int y, int w, int h, Panel panel) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.panel = panel;
}
public boolean contains(int x2, int y2) {
return (x == x2 && y == 2);
}
public boolean truckOnSite(int x2, int y2) {
return ( x2 == x + w / 2 && y2 == y + h / 2);
}
public boolean vanOnSite(int x2, int y2) {
return ( (x2 == x && y2 == y + h / 2) || (x2 == x + w && y2 == y + h / 2) );
}
public void loadVan(Van v) {
v.setCapacity(5000);
}
public void loadTruck(Truck t) {
t.setCapacity(10000);
t.setFull(true);
}
#Override
public void draw(Graphics g) {
g.setColor(Color.GRAY);
g.fillRect(x, y, w, h);
}
}
As it turned out much later, it doesn't seem truncation errors were the problem at hand. It was a mistake at setting the trucks' starting point and the condition that decides when they're supposed to turn the other way. What looked like the truck bouncing off, was actually the oppsoite truck from the same diagonal passing through. A simple change in direction of my Truck's move() method did the trick.
public void setDirection(int i) {
if (i == 0) {
dx = -1;
dy = -1;
}
if (i == 1) {
dx = 1;
dy = -1;
}
if (i == 2) {
dx = -1;
dy = 1;
}
if (i == 3) {
dx = 1;
dy = 1;
}
}

My mainBall class wont repaint when i press a key

I created a class that draws a ball on a screen and my goal is to move it with the keys, but the ball stays in one spot. the coordinates of the ball change according to the key presses but not the actual ball itself
import java.applet.Applet;
import java.awt.Color;
import java.awt.Component;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class game extends Applet implements Runnable
{
static final int WIDTH = 450;
static final int HEIGHT = 450;
private Image dbImage;
private Graphics dbg;
public static long NEW_DOT_FREQ = TimeUnit.SECONDS.toMillis(3);
public long lastUpdateTime;
public long timeSinceLastNewDot;
public ArrayList<Ball> BALLS;
Color[] color = {Color.red, Color.blue, Color.green, Color.yellow, Color.magenta, Color.black};
int colorIndex;
static final int NUM_OF_BALLS = 4;
int i;
int t;
MainBall mainBall = new MainBall(100, 100, 10, 10, 100, 100, 0, 0);
Thread updateTime = new updateTime();
public void start()
{
lastUpdateTime = System.currentTimeMillis();
Thread th = new Thread(this);
th.start();//start main game
updateTime.start();
}
public void updateGame()
{
//Get the current time
long currentTime = System.currentTimeMillis();
//Calculate how much time has passed since the last update
long elapsedTime = currentTime - lastUpdateTime;
//Store this as the most recent update time
lastUpdateTime = currentTime;
//Create a new dot if enough time has passed
//Update the time since last new dot was drawn
timeSinceLastNewDot += elapsedTime;
if (timeSinceLastNewDot >= NEW_DOT_FREQ)
{
int newX = randomNumber();
int newY = randomNumber();
debugPrint("New dot created at x:" + newX + ", y:" + newY + ".");
BALLS.add(new Ball(newX, newY, 20, 20));
timeSinceLastNewDot = 0;
}
}
private void debugPrint(String value)
{
System.out.println(value);
}
public class updateTime extends Thread implements Runnable
{
public void run()
{
for(t = 0; ; t++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
public int randomNumber()
{
return (int)(Math.random() * 400);
}
public int getRandomColor()
{
return (int)(Math.random() * 6);
}
public class MainBall
{
int x;
int y;
int width;
int height;
int xpos = 100;
int ypos = 100;
int xspeed = 0;
int yspeed = 0;
public MainBall(int x, int y, int width, int height, int xpos, int ypos, int xspeed, int yspeed)
{
this.x = 100;
this.y = 100;
this.width = 10;
this.height = 10;
this.xpos = 100;
this.ypos = 100;
this.xspeed = 0;
this.yspeed = 0;
}
public void paintMainBall(Graphics g)
{
g.setColor(Color.black);
g.fillOval(x, y, width, height);
g.drawString(xpos + ", " + ypos, 20, 40);
}
}//mainBall
class Ball
{
int x;
int y;
int width;
int height;
public Ball(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}//end ball
public void paint(Graphics g)
{
g.setColor(color[getRandomColor()]);
g.fillOval(x, y, width, height);
}//end paint
}//ball class
public void update(Graphics g)//double buffer don't touch!!
{
if(dbImage == null)
{
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public boolean keyDown (Event e, int key)
{
if(key == Event.LEFT)
{
mainBall.xspeed = -5;
mainBall.yspeed = 0;
}
if(key == Event.RIGHT)
{
mainBall.xspeed = 5;
mainBall.yspeed = 0;
}
if(key == Event.UP)
{
mainBall.yspeed = -5;
mainBall.xspeed = 0;
}
if(key == Event.DOWN)
{
mainBall.yspeed = 5;
mainBall.xspeed = 0;
}
return true;
}
public void run()
{
while(true)
{
repaint();
if (mainBall.xpos < 1)
{
mainBall.xpos = 449;
}
if (mainBall.xpos > 449)
{
mainBall.xpos = 1;
}
if (mainBall.ypos < 1)
{
mainBall.ypos = 449;
}
if (mainBall.ypos > 449)
{
mainBall.ypos = 1;
}
mainBall.ypos += mainBall.yspeed;
mainBall.xpos += mainBall.xspeed;
try
{
Thread.sleep(20);
}
catch(InterruptedException ex){}
}
}
public void init()
{
this.setSize(WIDTH, HEIGHT);
BALLS = new ArrayList<Ball>();
}
public void paint(Graphics g)
{
g.drawString("time: " + t, 20, 20);
mainBall.paintMainBall(g);
for (Ball ball : BALLS)
{
ball.paint(g);
}
updateGame();
}
}
You update the xPos/yPos values of the ball, but never the x/y values
public void paintMainBall(Graphics g) {
System.out.println("PaintMainBall");
g.setColor(Color.RED);
g.fillOval(x, y, width, height);
g.drawString(xpos + ", " + ypos, 20, 40);
}

Categories

Resources