Java: drawing multiple sprites in different threads at a time - java

I need to create a JPanel, where upon a mouse click a new Sprite must appear in a new thread. This is what I have:
public class BouncingSprites {
private JFrame frame;
private SpritePanel panel = new SpritePanel();
private Sprite ball;
public BouncingSprites() {
frame = new JFrame("Bouncing Sprite");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public void start(){
panel.animate(); // never returns due to infinite loop in animate method
}
public static void main(String[] args) {
new BouncingSprites().start();
}
}
Class SpritePanel:
public class SpritePanel extends JPanel
{
Sprite sprite;
public SpritePanel()
{
addMouseListener(new Mouse());
}
//method for creating a new ball
private void newSprite (MouseEvent event)
{
sprite = new Sprite(this);
}
public void animate()
{
}
private class Mouse extends MouseAdapter
{
#Override
public void mousePressed( final MouseEvent event )
{
newSprite(event);
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (sprite != null)
{
sprite.draw(g);
}
}
}
Class Sprite :
public class Sprite implements Runnable
{
public final static Random random = new Random();
final static int SIZE = 10;
final static int MAX_SPEED = 5;
SpritePanel panel;
private int x;
private int y;
private int dx;
private int dy;
private Color color = Color.BLUE;
private Thread animation;
public Sprite (SpritePanel panel)
{
this.panel = panel;
x = random.nextInt(panel.getWidth());
y = random.nextInt(panel.getHeight());
dx = random.nextInt(2*MAX_SPEED) - MAX_SPEED;
dy = random.nextInt(2*MAX_SPEED) - MAX_SPEED;
animation = new Thread(this);
animation.start();
}
public void draw(Graphics g)
{
g.setColor(color);
g.fillOval(x, y, SIZE, SIZE);
}
public void move()
{
// check for bounce and make the ball bounce if necessary
//
if (x < 0 && dx < 0){
//bounce off the left wall
x = 0;
dx = -dx;
}
if (y < 0 && dy < 0){
//bounce off the top wall
y = 0;
dy = -dy;
}
if (x > panel.getWidth() - SIZE && dx > 0){
//bounce off the right wall
x = panel.getWidth() - SIZE;
dx = - dx;
}
if (y > panel.getHeight() - SIZE && dy > 0){
//bounce off the bottom wall
y = panel.getHeight() - SIZE;
dy = -dy;
}
//make the ball move
x += dx;
y += dy;
}
#Override
public void run()
{
while (Thread.currentThread() == animation)
{
move();
panel.repaint();
try
{
Thread.sleep(40);
}
catch ( InterruptedException exception )
{
exception.printStackTrace();
}
}
}
}
This code creates a new moving sprite. However, the previous sprite gets removed from the panel. What I need to do is to add a new sprite with a mouse click, so that the previous sprite is not removed. If I click three times, three sprites should be painted.
How do I change my code to implement that?
Many thanks!

You could replace Sprite sprite; in the SpritePanel class with List<Sprite> sprites = new ArrayList<>();. Then, when you make a new Sprite, add it to the list. Then in your paintComponent method, you could iterate through the list, drawing all of the sprites.

Related

Mouse Collision with JComponent and AWT MouseEvent Problem

So I have a problem with my mouse detection using a object called Ornament that inherits JComponent and I am getting the mouse clicks using java.awt.event.MouseEvent.
The solution me and my group though would be the best is to compare the distance of each ornament to the mouse and if its less than 50 (which is the radius of the ornament) it would do something.
private class ME implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
for(int i = 0; i < ORNAMENT_AMOUNT; i++) {
Ornament current = oh.getOrnament(i);
int distance = (int)(Math.sqrt(((e.getX() - current.getX()) * (e.getX() - current.getX())) + ((e.getY() - current.getY()) * (e.getY() - current.getY()))));
if(distance <= 50) {
System.out.println("CIRCLE CLICKED!");
current.reset();
}
}
}
The problem that I am getting is that it just does not work how it should. I click in the same spot many times and eventually it will trigger the event on one of the ornaments. Its random and confusing.
Here is the Ornament class
//ornament class to define the game object ornament
public class Ornament extends JComponent{
private int xPos;
private int yPos;
private int velocity;
private int screenWidth;
private int screenHeight;
private Random rand;
public Ornament(int screenWidth, int screenHeight, int velocity) {....}
public int getY() { return yPos; }
public int getX() { return xPos; }
#Override
public void paintComponent(Graphics graphics) {
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
super.paintComponent(graphics);
graphics.setColor(new Color(r, g, b));
graphics.fillOval(0, 0, 50, 50);
}
....
public void reset() {
this.yPos = -(int)(Math.random()*500);
this.xPos = (int)(Math.random()*screenWidth);
this.velocity += 1;
update();
}
}
My whole approach to this might be wrong but it seems right in my head so help would be appreciated! :)
*note oh is an objecthandler class I made to run the game loop in a different thread that has an array of ornaments
public class ObjectHandler implements Runnable {
private int size;
private Ornament[] list;
private GUI game;
public ObjectHandler(int size, GUI game) {
....
list = new Ornament[size];
//init object list
for(int i = 0; i < size; i++) {
list[i] = new Ornament(game.getFrameX(), game.getFrameY(), game.getStartingVel());
game.add(list[i]);
}
}
public Ornament getOrnament(int index) { return list[index]; }
public void run() {
while(true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) { e.printStackTrace(); }
game.loadBackground();
for(int i = 0; i < size; i++) {
if(list[i].getY() >= game.getFrameY())
list[i].reset();
else
list[i].update();
}
}
}
}
Thank you all for your help!
I used Gilbert Le Blanc's method to get this to work.
I removed the JComponent off of the Ornament class and instead created a class that inherits JPanel
ublic class GamePanel extends JPanel{
private Ornament[] objectList;
......
public GamePanel(GUI game) {
....
MouseListener ml = new MouseListener();
addMouseListener(ml);
this.setBounds(0, 0, 500, 500);
}
I then added a paint component and rendered each Ornament in the objectList array using a for loop
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
.....
for(int i = 0; i < objectList.length; i++) {
Color c = new Color(objectList[i].r, objectList[i].g, objectList[i].b);
g2.setColor(c);
g2.fillOval(objectList[i].getX(), objectList[i].getY(), 50, 50);
}
}
}
Furthemore I added the mouselistener to the JPanel component. Using the same technique for mouse to object collision and it worked!
class MouseListener extends MouseAdapter
{
#Override
public void mousePressed(MouseEvent e)
{
if(!gameOver) {
for(int i = 0; i < objectList.length; i++) {
int distance = (int)(Math.sqrt(((e.getX() - objectList[i].getX()) * (e.getX() - objectList[i].getX())) + ((e.getY() - objectList[i].getY()) * (e.getY() - objectList[i].getY()))));
if(distance <= 50) {
game.incScore();
objectList[i].reset();
}
}
...
}
}
Shoutout to hfontanez and Gilbert Le Blanc for the help! :)

get width and height of JPanel outside of the class

So I created a simple simple simulation where squares are spawned randomly with random vectors and bounce of the edges of the window.
I wanted it to take into account the window being resized. So that if I change the dimensions of the window from 600x600 to 1200x600 the squares will bounce of the new border rather than 600x600.
I tried doing getWidth() getHeight() but it would return 0.
So I put it in the pain() (since it gets called on window resize) method and saved the return values as local variables. But I cannot call getjpWidth() from the Rect class.
So basically what I need is to get new window dimension into the move() method in the Rect class.
Please feel free to point out any other mistakes and things that can be done better. I'm new to 2D programming (studying Computer Science)
Application
import javax.swing.*;
public class Application {
private Application(){
//create a JFrame window
JFrame frame = new JFrame("Moving Squares");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add a JPanel
GamePanel gamePanel = new GamePanel();
frame.add(gamePanel);
//pack the window around the content
frame.pack();
//center
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]){
new Application();
}
}
GamePanel
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
public class GamePanel extends JPanel implements Runnable{
private int jpWidth=0, jpHeight=0;
//set JPanel size
private static final Dimension DESIRED_SIZE = new Dimension(600,600);
#Override
public Dimension getPreferredSize(){
return DESIRED_SIZE;
}
//constructor
GamePanel(){
Thread t = new Thread(this);
t.start();
}
private ArrayList <Rect> rect=new ArrayList<>();
public void run(){
for(int i=0; i<15; i++){
rect.add(new Rect());
}
while(true){
for(Rect rect:rect){
rect.move();
}
//repaint still image for better frames
//should be 100fps instead it's >144fps
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
}
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
jpWidth=getWidth();
jpHeight=getHeight();
g2d.setColor(Color.white);
g2d.fillRect(0,0,jpWidth,jpHeight);
for(Rect rect:rect) {
g2d.setColor(Color.black);
g2d.fillRect(rect.getXcord()-1, rect.getYcord()-1, rect.getWidth()+2, rect.getHeight()+2);
g2d.setColor(Color.getHSBColor(rect.getR(), rect.getG(), rect.getB()));
g2d.fillRect(rect.getXcord(), rect.getYcord(), rect.getWidth(), rect.getHeight());
}
}
public int getJpWidth() {
return jpWidth;
}
public int getJpHeight() {
return jpHeight;
}
}
Rect
import java.util.Random;
public class Rect {
//properties
private int width=30, height=30;
private int R, G, B;
//movement
private int xCord, yCord;
private int xVector, yVector;
private int xSlope, ySlope;
public Rect(){
Random rand = new Random();
//random color
R=rand.nextInt(255);
G=rand.nextInt(255);
B=rand.nextInt(255);
//random spawn position
xCord=rand.nextInt(600-width);
yCord=rand.nextInt(600-height);
//direction
do{
xVector=rand.nextInt(3) - 1;
yVector=rand.nextInt(3) - 1;
}while(xVector==0 || yVector==0);
//slope
do{
xSlope=rand.nextInt(3);
ySlope=rand.nextInt(3);
}while(xSlope==0 || ySlope==0);
xVector*=xSlope;
yVector*=ySlope;
}
public void move(){
//if(xCord>=//how to get screen width ? ){}
if((xCord>=600-width) || (xCord<=0)){
bounceX();
}
if((yCord>=600-height) || (yCord<=0)) {
bounceY();
}
xCord+=xVector;
yCord+=yVector;
}
public void bounceX(){
xVector*=-1;
}
public void bounceY(){
yVector*=-1;
}
public int getR() {
return R;
}
public int getG() {
return G;
}
public int getB() {
return B;
}
public int getXcord() {
return xCord;
}
public int getYcord() {
return yCord;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
}
So basically what I need is to get new window dimension into the move() method in the Rect class.
Don't know if it is the best design but I pass the "panel" as a parameter to the "move()" method so its width/height can be used.
Here is some old code I have lying around that shows this approach:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class BallAnimation4
{
private static void createAndShowUI()
{
BallPanel panel = new BallPanel();
JFrame frame = new JFrame("BallAnimation4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.pack();
frame.setLocationRelativeTo( null );
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible( true );
panel.addBalls(5);
panel.startAnimation();
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
class BallPanel extends JPanel implements ActionListener
{
private ArrayList<Ball> balls = new ArrayList<Ball>();
public BallPanel()
{
setLayout( null );
// setBackground( Color.BLACK );
}
public void addBalls(int ballCount)
{
Random random = new Random();
for (int i = 0; i < ballCount; i++)
{
Ball ball = new Ball();
ball.setRandomColor(true);
ball.setLocation(random.nextInt(getWidth()), random.nextInt(getHeight()));
// ball.setMoveRate(32, 32, 1, 1, true);
ball.setMoveRate(16, 16, 1, 1, true);
// ball.setSize(32, 32);
ball.setSize(64, 64);
balls.add( ball );
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Ball ball: balls)
{
ball.draw(g);
}
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(800, 600);
}
public void startAnimation()
{
Timer timer = new Timer(1000/60, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
move();
repaint();
}
private void move()
{
for (Ball ball : balls)
{
ball.move(this);
}
}
class Ball
{
public Color color = Color.BLACK;
public int x = 0;
public int y = 0;
public int width = 1;
public int height = 1;
private int moveX = 1;
private int moveY = 1;
private int directionX = 1;
private int directionY = 1;
private int xScale = moveX;
private int yScale = moveY;
private boolean randomMove = false;
private boolean randomColor = false;
private Random myRand = null;
public Ball()
{
myRand = new Random();
setRandomColor(randomColor);
}
public void move(JPanel parent)
{
int iRight = parent.getSize().width;
int iBottom = parent.getSize().height;
x += 5 + (xScale * directionX);
y += 5 + (yScale * directionY);
if (x <= 0)
{
x = 0;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (x >= iRight - width)
{
x = iRight - width;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (y <= 0)
{
y = 0;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
if (y >= iBottom - height)
{
y = iBottom - height;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
}
public void draw(Graphics g)
{
g.setColor(color);
g.fillOval(x, y, width, height);
}
public void setColor(Color c)
{
color = c;
}
public void setLocation(int x, int y)
{
this.x = x;
this.y = y;
}
public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove)
{
this.moveX = xMove;
this.moveY = yMove;
directionX = xDir;
directionY = yDir;
randomMove = randMove;
}
public void setRandomColor(boolean randomColor)
{
this.randomColor = randomColor;
switch (myRand.nextInt(3))
{
case 0: color = Color.BLUE;
break;
case 1: color = Color.GREEN;
break;
case 2: color = Color.RED;
break;
default: color = Color.BLACK;
break;
}
}
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
}
}
Also, note that for animation you should be using a Swing Timer to schedule the animation. Updates to Swing components should be done on the Event Dispatch Thread (EDT). While not likely to cause a problem with this simple application it is a good habit to make sure this basic rule is followed otherwise you can have random problems and it is never easy to debug a random problem.

Images not showing up on JPanel?

I am having some trouble getting both the squares I created in the program, and the ImageIcon imported to show up on my JPanel. I have been at this for a while now, and still am unable to figure out what I can do to make them show up, and allows the player image to move. Here is the first piece of my code which is the Maze class:
public class Maze extends JPanel{
int[][][] mazeArray; //will be defined in the loop depending on how many rectangles are spawned, also for making sure the player can't walk over the walls (first is what number wall it is, second is the x coordiante of the wall, and third is the y coordinate of the wall)
//depending on whether or not the rctangle is vertical or horizontal it will use both values for its height and width (vertical would have sideX for the height, and sideY for the width; this would be the opposite for the horizontal rectangle)
int sideX = 50; //x side length
int sideY = 50; //y side length
int x;
int y;
//setters and getters for use later (for changing the rctangles location and size)
public void setSideX(int sideX){
this.sideX = sideX;
}
public int getSideX(){
return sideX;
}
public void setSideY(int sideY){
this.sideY = sideY;
}
public int getSideY(){
return sideY;
}
public void setCoordinates(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x = x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y = y;
}
public int getY(){
return y;
}
//end setters and getters
public void generateMaze(){
//the left side of the maze
for(int i = 0; i < 10; i++){ //ten blocks on the left side
setX(0); //x is always 0 for the left side
setY(getY() + 50); //adds 50 to the previous Y coordinate amount, m making it go down the whole left side
}
setY(0); //set y back to zero to be able to start the right column of blocks
//the right side of the maze
for(int i = 0; i < 10; i++){
setX(500); //x is always 500 for the right side
setY(getY() + 50); //does the same as it did on the left side, except on the right
}
setY(0); //set y to zero again
setX(50); //start x at 50 since there is no need to remake the corners
for(int i = 0; i < 8; i++){ //only goes up to 8 this this time because the corners of the maze can be ignored
setY(0); //just in case y changes back
setX(getX() + 50); //x increases by 50 each time
}
setY(500);
setX(50);
for(int i = 0; i < 8; i++){ //same as above except for the bottom
setY(500);
setX(getX() + 50);
}
//the maze walls are now generated
}
public void paintComponent(Graphics g){ //for painting the rectangles
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(getX(), getY(), sideX, sideY); //uses x and y coordinates defined in the generateMaze loop, and the uses whatever current value for the two side, depending on what type of rectangle it is
}
}
This is what I am using to create the mazes walls. Now comes the Player class which deals with the player image, player coordinates, and the player's movement speed:
public class Player {
//Player starts in the top left corner
int playerX = 50;
int playerY = 50;
int moveSpeed = 5; //I can edit move speed here
Image character;
//getters and setters to utilize the player's location and image
public Player(){ //constructor for initial starting points
playerX = 50;
playerY = 50;
ImageIcon player = new ImageIcon("E://Workspace//Maze//images//Player.jpg");
character = player.getImage();
}
public void setPlayerX(int playerX){
this.playerX = playerX;
}
public int getPlayerX(){
return playerX;
}
public void setPlayerY(int playerY){
this.playerY = playerY;
}
public int getPlayerY(){
return playerY;
}
public void setMoveSpeed(int moveSpeed){
this.moveSpeed = moveSpeed;
}
public int getMoveSpeed(){
return moveSpeed;
}
public Image getPlayerImage(){
return character;
}
}
Next is where I think the problem is occurring for the player's image (for the maze I think it is something in the Maze class itself, although it could be a problem in the Layout class as well):
public class Layout extends JPanel implements ActionListener { //GUI with a non null FlowLayout
Maze m = new Maze();
Player p = new Player();
//500 x 500 seemed like a good size for the maze game
int x = 500;
int y = 500;
Image player;
JPanel panel;
public Layout() {
panel = new JPanel();
panel.setLayout(new FlowLayout()); //same as the JFrame
panel.addKeyListener(new Move(p));
panel.setFocusable(true);
panel.setBackground(Color.YELLOW); //background of the maze
m.generateMaze(); //create the maze
}
//for use in setting and getting the borders of the game
public void setX(int x){
this.x = x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y = y;
}
public int getY(){
return y;
}
public JPanel getPanel(){
return panel;
}
#Override //so it can repaint as needed
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(p.getPlayerImage(), p.getPlayerX(), p.getPlayerY(), this);
}
public void actionPerformed(ActionEvent ae){
repaint();
}
}
class Move implements KeyListener { //for player movement
final Player p;
Move(Player p){
this.p = p;
}
public void keyPressed(KeyEvent press) { //for the movement in the game
//I used both keys so that if the player woukld like to use WASD or the arrow keys either will work
if(press.getKeyCode() == KeyEvent.VK_W || press.getKeyCode() == KeyEvent.VK_UP){
//move up
p.setPlayerY(p.getPlayerY() - p.getMoveSpeed());
}
else if(press.getKeyCode() == KeyEvent.VK_S || press.getKeyCode() == KeyEvent.VK_DOWN){
//move down
p.setPlayerY(p.getPlayerY() + p.getMoveSpeed());
}
else if(press.getKeyCode() == KeyEvent.VK_A || press.getKeyCode() == KeyEvent.VK_LEFT){
//move left
p.setPlayerX(p.getPlayerX() - p.getMoveSpeed());
}
else if(press.getKeyCode() == KeyEvent.VK_D || press.getKeyCode() == KeyEvent.VK_RIGHT){
//move right
p.setPlayerX(p.getPlayerX() + p.getMoveSpeed());
}
}
public void keyReleased(KeyEvent release) {
//nothing is needed here
}
public void keyTyped(KeyEvent e) {
//does nothing if a key is type (no need for it)
}
}
Lastly is the class that runs it, although I don't think there is any issue here, but just in case I will throw it in here anyway:
public class Play extends JPanel {
public static void main(String[]args) {
play();
}
public static void play() {
JFrame f = new JFrame();
Layout l = new Layout();
JPanel j = l.getPanel();
f.setTitle("Maze Game for final project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(l.getX(), l.getY()); //size can be changed in layout
f.setVisible(true);
f.add(j); //adds the panel
}
}
I am trying to be able to have the player's image spawn at 50, 50 on start up, and then also have the walls spawn at start up as well. However currently the only thing that is showing up for the JPanel is the yellow background. Help would be greatly appreciated!
New updated code here:
public static void play() {
JFrame f = new JFrame();
Layout l = new Layout();
f.setTitle("Maze Game for final project");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(l.getX(), l.getY()); //size can be changed in layout
f.add(new Layout()); //adds the panel
f.setVisible(true);
}
and also for the Layout constructor
public Layout() {
setLayout(new FlowLayout());
addKeyListener(new Move(p));
setFocusable(true);
setBackground(Color.YELLOW);
m.generateMaze();
}
I can't say that I've gone through all of your code, but one thing did strike me:
Your Layout class extends JPanel and overrides paintComponet, but you never use this class as a JPanel. Instead you use some other JPanel variable within it called panel. Get rid of that variable and instead use the JPanel that is the Layout class itself, and at least some of your problems may be fixed.
e.g.,
public class Layout extends JPanel implements ActionListener {
Maze m = new Maze();
Player p = new Player();
int x = 500;
int y = 500;
Image player;
// JPanel panel;
public Layout() {
// panel = new JPanel();
// panel.setLayout(new FlowLayout()); //same as the JFrame
// panel.addKeyListener(new Move(p));
// panel.setFocusable(true);
// panel.setBackground(Color.YELLOW); //background of the maze
setLayout(new FlowLayout());
addKeyListener(new Move(p));
setFocusable(true);
setBackground(Color.YELLOW);
m.generateMaze();
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
// public JPanel getPanel() {
// return panel;
// }
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(p.getPlayerImage(), p.getPlayerX(), p.getPlayerY(), this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
}
Another problem is your use of KeyListeners since Key Bindings would be much preferable here, but I'll leave that for your next question.
Also, you're adding your JPanel to the JFrame after calling setVisible(true) on the JPanel -- don't do this. Call setVisible(true) only after adding all components.

ContentPane background color changes when adding object

I have the following code:
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Ball extends JPanel implements Runnable {
List<Ball> balls = new ArrayList<Ball>();
Color color;
int diameter;
long delay;
private int x;
private int y;
private int vx;
private int vy;
public Ball(String ballcolor, int xvelocity, int yvelocity) {
color = Color.PINK;
diameter = 30;
delay = 40;
x = 1;
y = 1;
vx = xvelocity;
vy = yvelocity;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
g.fillOval(x,y,50,50); //adds color to circle
g.setColor(Color.pink);
g2.drawOval(x,y,50,50); //draws circle
}
public void run() {
while(isVisible()) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
move();
repaint();
}
}
public void move() {
if(x + vx < 0 || x + diameter + vx > getWidth()) {
vx *= -1;
}
if(y + vy < 0 || y + diameter + vy > getHeight()) {
vy *= -1;
}
x += vx;
y += vy;
}
private void start() {
while(!isVisible()) {
try {
Thread.sleep(25);
} catch(InterruptedException e) {
System.exit(1);
}
}
Thread thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
public static void main(String[] args) {
Ball ball1 = new Ball("pink",6,6);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.BLACK);
f.getContentPane().add(ball1);
f.setSize(1000,500);
f.setLocation(200,200);
new Thread(ball1).start();
f.setVisible(true);
}
}
I would like to make the background black instead of the default grey one, but this only works if I get the ball out of the code, basically deleting f.getContentPane().add(ball1);. What I want is a pink ball bouncing on a black background, but it keeps going back to grey when adding the ball.
What is the problem?
Ball which extends from JPanel is opaque (not see through), so it is filling it's own background with it's default color...
You could make Ball transparent by using setOpaque(false) or set the Ball's background color to BLACK using setBackground(Color.BLACK) for example...
ps- I should add, because JFrame uses a BorderLayout, your Ball pane will occupy the entire available space within the center of the frame (CENTER being the default position and the frame not containing any other components)

method repaint() not repainting, ball gravity animation

The problem is that this ball after it is dragged and exited click, it is supposed to repaint according to the new y component given. This is calculated from the gravity final and added to the velocity which is added to the existing y component in a loop.
I have debugged many times and I just cant hit it on the head.
Its supposed to..
move to where you drag it >>> when you let go it is supposed to fall until it hits the ground.
Thank you ahead of time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
{
private static final int BALL_DIAMETER = 40;
private int screen_size_x = 300;
private int screen_size_y = 300;
private int ground_lvl = screen_size_y - 15;
private int _ballX = ground_lvl/2;
private int _ballY = ground_lvl - BALL_DIAMETER;
private final double GRAVITY = -9.8;
private double velocity;
private static final double TERM_VEL = -100;
private int _dragFromX = 0;
private int _dragFromY = 0;
private boolean _canDrag = false;
public DragBallPanel() throws InterruptedException
{
setPreferredSize(new Dimension(screen_size_x, screen_size_y));
setBackground(Color.darkGray);
setForeground(Color.darkGray);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Required for background.
g.setColor (Color.green);
g.fillRect (0, 280, 400, 50 );
g.setColor (Color.black);
g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);
}
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
&& y >= _ballY && y <= (_ballY + BALL_DIAMETER))\
{
_canDrag = true;
_dragFromX = x - _ballX;
_dragFromY = y - _ballY;
} else
{
_canDrag = false;
}
}
//===== mouseDragged ======
/** Set x,y to mouse position and repaint. */
public void mouseDragged(MouseEvent e)
{
if (_canDrag)
{ // True only if button was pressed inside ball.
//--- Ball pos from mouse and original click displacement
_ballX = e.getX() - _dragFromX;
_ballY = e.getY() - _dragFromY;
//--- Don't move the ball off the screen sides
_ballX = Math.max(_ballX, 0);
_ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
//--- Don't move the ball off top or bottom
_ballY = Math.max(_ballY, 0);
_ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
this.repaint();
}
}
public void mouseExited(MouseEvent e)
{
while(_ballY < ground_lvl)
{
simulateGravity();
}
}
public void simulateGravity()
{
if(_canDrag)
{
try{
velocity = velocity + GRAVITY;
if (velocity < TERM_VEL)
{
velocity = TERM_VEL;
}
if (_ballY >= ground_lvl - BALL_DIAMETER)
{
velocity = velocity/4;
}
_ballY += velocity;
Thread.sleep(400);
this.repaint();//**problem occurs here**
}catch(InterruptedException ie)
{
}
}
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
main() class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DragDemo extends JApplet
{
public static void main(String[] args) throws InterruptedException
{
JFrame window = new JFrame();
window.setTitle("Drag Demo");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//window.add(new DragBallPanel());
window.setContentPane(new DragBallPanel());
window.setResizable(false);
window.pack();
window.show();
}
public DragDemo() throws InterruptedException
{
new DragBallPanel();
}
}
This SSCCE begins to show the problems in the code.
Compile the code.
Run it.
Drag the ball upwards.
Release the ball.
Remove the mouse from the drawing area, to see..
The ball fall upwards!
You seem to have gotten the Y values upside down. They start at top of screen, and go downwards. Also, the code was blocking the EDT in an infinite loop. To solve that, run the animation using a Swing Timer.
Please read the document on the SSCCE & ask if there is anything in it you do not understand. I am well placed to explain. :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
{
private static final int BALL_DIAMETER = 40; // Diameter of ball
private int screen_size_x = 300;
private int screen_size_y = 300;
private int ground_lvl = screen_size_y - 15;
private int _ballX = ground_lvl/2;
private int _ballY = ground_lvl - BALL_DIAMETER;
private final double GRAVITY = -9.8;
private double velocity;
private static final double TERM_VEL = 100;
private int _dragFromX = 0; // pressed this far inside ball's
private int _dragFromY = 0; // bounding box.
/** true means mouse was pressed in ball and still in panel.*/
private boolean _canDrag = false;
public DragBallPanel()
{
setPreferredSize(new Dimension(screen_size_x, screen_size_y));
setBackground(Color.darkGray);
setForeground(Color.darkGray);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Required for background.
g.setColor (Color.green);
g.fillRect (0, 280, 400, 50 );
g.setColor (Color.black);
g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);
}
public void mousePressed(MouseEvent e)
{
int x = e.getX(); // Save the x coord of the click
int y = e.getY(); // Save the y coord of the click
if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
&& y >= _ballY && y <= (_ballY + BALL_DIAMETER)) {
_canDrag = true;
_dragFromX = x - _ballX; // how far from left
_dragFromY = y - _ballY; // how far from top
} else {
_canDrag = false;
}
}
//========= mouseDragged =================
/** Set x,y to mouse position and repaint. */
public void mouseDragged(MouseEvent e)
{
if (_canDrag) { // True only if button was pressed inside ball.
//--- Ball pos from mouse and original click displacement
_ballX = e.getX() - _dragFromX;
_ballY = e.getY() - _dragFromY;
//--- Don't move the ball off the screen sides
_ballX = Math.max(_ballX, 0);
_ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
//--- Don't move the ball off top or bottom
_ballY = Math.max(_ballY, 0);
_ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
this.repaint(); // Repaint because position changed.
}
}
//====================================================== method mouseExited
/** Turn off dragging if mouse exits panel. */
public void mouseExited(MouseEvent e)
{
System.out.println("Exited: " + e);
//_canDrag = false;
runGravity();
/* while(_ballY < ground_lvl)
{
simulateGravity();
}*/
}
Timer timer;
ActionListener animate;
public void runGravity() {
if (animate==null) {
animate = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Ground: " + (_ballY-ground_lvl));
if (_ballY > ground_lvl) {
timer.stop();
} else {
simulateGravity();
}
}
};
timer = new Timer(100,animate);
}
timer.start();
}
public void simulateGravity()
{
System.out.println("_canDrag: " + _canDrag);
if(_canDrag)
{
velocity = velocity + GRAVITY;
if (velocity > TERM_VEL)
{
velocity = TERM_VEL;
}
if (_ballY >= ground_lvl - BALL_DIAMETER)
{
//We have hit the "ground", so bounce back up. Reverse
//the speed and divide by 4 to make it slower on bouncing.
//Just change 4 to 2 or something to make it faster.
velocity = velocity/4;
}
_ballY += velocity;
//this.revalidate();
this.repaint();
}
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
DragBallPanel dbp = new DragBallPanel();
JOptionPane.showMessageDialog(null, dbp);
}
});
}
}
Try updateUI() instead of repaint().
If there is no effect remove the component and add it again.

Categories

Resources