BackGround in my JPanel, how can I resolve this? - java

Well my problem is that I'm making the stars move with a thread, they move verticaly and it works good but i do a random X for the star and sometimes it intersecs other stars like this :
This is my code for the JPanel:
class Backgroundmoving
public class Backgroundmoving extends JPanel {
ArrayList<starmoving> star;
public Backgroundmoving() {
this.setSize(650, 501);
star = new ArrayList<>();
for (int i = 0; i < 20; i++)
this.addStar();
}
public void addStar() {
int x, y;
x = (int) (Math.random() * 625);
y = (int) (Math.random() * 476);
starmoving e = new starmoving(x, y);
star.add(e);
Thread t = new Thread(e);
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
g.drawImage(new ImageIcon("background.png").getImage(), 0, 0, 650, 501, null);
for (int i = 0; i < star.size(); i++) {
star.get(i).draw(g);
}
repaint();
}
public static void main(String[] args) {
// TODO code application logic here
JFrame gui = new JFrame();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(650, 510);
gui.setResizable(false);
gui.add(new Backgroundmoving());
gui.setVisible(true);
}
}
class starmoving
public class starmoving implements Runnable {
int x;
int y;
int yVel;
public starmoving(int x, int y) {
this.x = x;
this.y = y;
yVel = 1;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
private void move() {
y += yVel;
if (y > 476) {
y = 0;
x = (int) (Math.random() * 625);
}
}
private boolean isOffScreen() {
if (y <= 476)
return false;
return true;
}
public void draw(Graphics g) {
g.drawImage(new ImageIcon("star.png").getImage(), x, y, 12, 12, null);
}
#Override
public void run() {
while (true) {
move();
try {
Thread.sleep(7);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
}
}
}

i don't want stars intersecting, was thinking in a if before the random X but how can i know if other star is in that X ?
You have an ArrayList that contains all your "StarMoving" objects. So you need to iterate through that list to make sure that none of the object intersect.
On top of that you have other problems.
Use proper Java class names. Java classes SHOULD start with an upper case character. (ie. "starmoving" is wrong)
Don't use multiple Threads for the animation. You current code starts 20 Threads. You should have a single Thread and then iterate through your ArrayList to move all the stars.
Don't read the image in the draw() method. Currently you code is reading the image every 7ms. This is not very efficient. The image should be read once and then stored as a property of your class.

Related

Drawing new Graphics in ArrayList

I have an application, in which a car is moving on a panel and it creates sound waves - circles. I want to :
1) have a few circles at the moment of opening the frame
2) when the Start button is selected I want them to move and I want more circles to be created, one after another, until the stop button is selected
the problem is:
1) when the frame is opened there are 5 circles, but they totally do not move
2) 5 new circles appears, but from the same XY position, they are just bigger - I want one circle after another, it grows, and next one appears
here is my code, I would appreciate some helpful sample or could you tell me where my mistake is. I used amount of 5 just to have some samples of waves.
public class WaveParameters {
int xPos=0;
int yPos = 375;
int width=60;
int height=60;
int velX = 0 ;
private Color color = Color.WHITE;
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getX() {
return xPos;
}
public void setX(int xPos) {
this.xPos = xPos;
}
public int getWidth(){
return width;}
public int getHeight(){
return height;}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void paint(Graphics g){
g.setColor(getColor());
g.drawOval(xPos,yPos,width/2,height/2);
}
}
Here is the panel of animation:
public class PanelAnimation extends JPanel implements ActionListener{
List<WaveParameters> waves = new ArrayList<WaveParameters>();
public PanelAnimation(ResourceBundle bundle) {
super();
resourceBundle = bundle;
t.start();
try {
imageBackground = ImageIO.read(newFile("bg.png"));
} catch (IOException ex) {
// handle exception...
}
}
CarParametrs pAuto = new CarParametrs();
HumanParametrs pHuman = new HumanParametrs() ;
Timer t = new Timer(60,this);
//WaveParameters pWave = new WaveParameters();
private BufferedImage imageBackground;
MainFrame mf;
public void addAuto(){
CarParametrs ap = new CarParametrs();
ap.setX(0);
pAuto = ap;
}
public void addHuman(){
HumanParametrs acz = new HumanParametrs();
acz.setX(0);
pHuman = acz;
}
public void addWave() {
for (int i=0; i<5; i++) {
WaveParameters wave = new WaveParameters();
// wave.setX(pAuto.xPos);
wave.setColor(Color.white);
wave.setWidth(wave.width*i);
wave.setHeight(wave.height*i);
waves.add(wave);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, null);
pAuto.paint(g);
pHuman.paint(g);
//if(mf.buttonStart.isSelected()) {
addWave();
//for (int i=0; i<5; i++) {
for (WaveParameters w : waves) {
// waves.add(new WaveParameters());
w.setX(pAuto.xPos);
w.paint(g);
//}
}
//}
}
public void actionPerformed(ActionEvent e) {
CarParametrs pa = pAuto;
pa.xPos += pa.velX;
/*//WaveParameters wp = pWave;
wp.xPos = pa.xPos;
wp.xPos+=wp.velX;
wp.height+=wp.velX;
wp.width+=wp.velX;
wp.yPos-=wp.velX/5 ;*/
for (WaveParameters w : waves) {
w.xPos = pa.xPos;
w.xPos+=w.velX;
w.height+=w.velX;
w.width+=w.velX;
w.yPos-=w.velX/5 ;
}
repaint();
}
and here is a wave-part of action listener for Start Button:
List<WaveParameters> wave = panelAnimation.waves;
for (WaveParameters w : wave) {
for (int i=0;i<5;i++) {
wave.add(new WaveParameters());
w.velX = Integer.parseInt(button2.getName());
w.xPos += w.velX;
w.width++;
w.height++;
w.yPos-=w.velX/5;
}
}
panelAnimation.repaint();
The five new bigger circles that appear are likely due to the last chunk of code where you iterate through all the waves in panel animation.
The "wave.add(new WaveParameters());" seems unnecessary, and may be the reason why your old waves are staying. Delete that line, and it may work.

Character can not move any more

So here is the code after taking the tips into account.
The map is kept being repainted, the keylistener has changed but there still seems to be a problem.
The problem again is, the little square in the upper left corner will not move, which is the desired outcome.
package schoolgamev2;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Spel {
public static void main(String[] args) {
Speelveld map = new Speelveld();
map.Speelveld();
map.GenerateMap();
}
}
class Speelveld extends JPanel {
final int rijen = 16;
final int kolommen = 16;
Speler speler = new Speler();
Loopgebied loopgebied = new Loopgebied();
Blokken blok = new Blokken();
int[][] coordinaten = new int[rijen][kolommen];
public void Speelveld() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
setFocusable(true);
addKeyListener(new KeyListener(this));
}
//genereer map
public void GenerateMap() {
Random random = new Random();
int x;
int y;
for (y = 0; y < rijen; y++) { //scan langs y
for (x = 0; x < kolommen; x++) { //scan langs x
//selecteert type blok voor coordinaten x y
coordinaten[x][y] = random.nextInt(4);
//debugprint
}
//debugprint
}
coordinaten[0][0] = 4; //speler begint altijd links boven
coordinaten[15][15] = 5; //finish is altijd rechts onder
}
public int[][] getCoordinaten() {
return coordinaten;
}
public Speler getSpeler2() {
return speler;
}
public int getSpelerX() {
return speler.getX();
}
public int getSpelerY() {
return speler.getY();
}
public void setSpelerX(int x) {
speler.setX(x);
}
public void setSpelerY(int y) {
speler.setY(y);
}
//#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x;
int y;
for (y = 0; y < rijen; y++) { //scan langs y
System.out.println("");
for (x = 0; x < kolommen; x++) { //scan langs x
blok.setX(x);
blok.setY(y);
blok.setType(coordinaten[x][y]);
System.out.print(coordinaten[x][y] + " ");
switch (blok.getType()) {
case 0:
loopgebied.teken(g);
break;
case 4:
speler.teken(g);
/*case 5:
eindveld.teken(g);
break;*/
default:
break;
}
}
}
}
}
class Speler extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX(), blok.getY(), 10, 10);
}
}
class Loopgebied extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX() * size, blok.getY() * size, size, size);
}
}
class Blokken {
private static int x;
private static int y;
private static int type;
public int size = 16;
//setters voor x y en type
public void setX(int xIn) {
x = xIn;
}
public void setY(int yIn) {
y = yIn;
}
public void setType(int typeIn) {
type = typeIn;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getType() {
return type;
}
}
class KeyListener extends KeyAdapter {
private static final int SCALE = 3;
private Speelveld speelveld;
public KeyListener(Speelveld speelveld) {
this.speelveld = speelveld;
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
int deltaX = 0;
int deltaY = 0;
if (key == KeyEvent.VK_LEFT) {
deltaX = -1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_UP) {
deltaX = 0;
deltaY = -1 * SCALE;
} else if (key == KeyEvent.VK_RIGHT) {
deltaX = 1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_DOWN) {
deltaX = 0;
deltaY = 1 * SCALE;
} else {
return;
}
int x = speelveld.getSpelerX() + deltaX;
int y = speelveld.getSpelerY() + deltaY;
speelveld.setSpelerX(x);
speelveld.setSpelerY(y);
speelveld.repaint();
}
}
As mentioned in comments, you got your player, the Speler class, that extends JPanel and is wired to use a KeyListener, but note that it is not being used as a JPanel, and so the KeyListener is non-functioning, because they only work when they have been added to a visible component that has focus.
Suggestions:
Again as per comments, make Speler a non-GUI logical class. Meaning don't have it extend JPanel or any other Swing component, and certainly don't add a KeyListener to it.
Instead give it code for the player's behavior and for having the player draw itself, and that's it. What I'm suggesting is that you try to separate part of your "Model" here the player from the "View" here the Swing GUI.
Have one JPanel and only one that does drawing. Have it override paintComponent (don't forget to call the super's paintComponent within it), and have it draw each logical component by calling the logical component's draw method (public void verf(Graphics2D g2)? or public void teken(Graphics2D g2)?) within its paintComponent method.
As a general rule, you also don't want your GUI component classes, the JPanel here, directly implementing listener interfaces, such as the KeyListener, but will want to keep them separate.
Either make this drawing JPanel focusable, give it focus and add the KeyListener, a separate class, to it.
Or better, use Key Bindings as per the tutorial: Key Bindings
For example the simple [MCVE] below doesn't use a Swing Timer or change velocities, but rather it uses a KeyListener to change position of the Speler2 object using only one drawing JPanel and a KeyListener. If I were making this more robust and larger, I would use the Swing Timer, would use Key Bindings, and would change the velocities using the key bindings.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Spel2 {
private static final int VELD_WIDTH = 500;
private static void createAndShowGui() {
Speelveld2 speelveld2 = new Speelveld2(VELD_WIDTH, VELD_WIDTH);
JFrame frame = new JFrame("Spel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(speelveld2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
speelveld2.requestFocusInWindow();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyKeyListener extends KeyAdapter {
private static final int SCALE = 3;
private Speelveld2 speelveld2;
public MyKeyListener(Speelveld2 speelveld2) {
this.speelveld2 = speelveld2;
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
int deltaX = 0;
int deltaY = 0;
if (key == KeyEvent.VK_LEFT) {
deltaX = -1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_UP) {
deltaX = 0;
deltaY = -1 * SCALE;
} else if (key == KeyEvent.VK_RIGHT) {
deltaX = 1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_DOWN) {
deltaX = 0;
deltaY = 1 * SCALE;
} else {
return;
}
int x = speelveld2.getSpelerX() + deltaX;
int y = speelveld2.getSpelerY() + deltaY;
speelveld2.setSpelerX(x);
speelveld2.setSpelerY(y);
speelveld2.repaint();
}
}
#SuppressWarnings("serial")
class Speelveld2 extends JPanel {
private int prefW;
private int prefH;
private Speler2 speler2 = new Speler2();
public Speelveld2(int prefW, int prefH) {
this.prefW = prefW;
this.prefH = prefH;
setFocusable(true);
addKeyListener(new MyKeyListener(this));
}
public Speler2 getSpeler2() {
return speler2;
}
public int getSpelerX() {
return speler2.getX();
}
public int getSpelerY() {
return speler2.getY();
}
public void setSpelerX(int x) {
speler2.setX(x);
}
public void setSpelerY(int y) {
speler2.setY(y);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
speler2.teken(g2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
}
class Speler2 extends Blokken2 {
private static final int RECT_W = 10;
public Speler2() {
super(BlokkenType.SPELER);
}
#Override
public void teken(Graphics2D g2) {
int x = getX();
int y = getY();
g2.drawRect(x, y, RECT_W, RECT_W);
}
}
class Blokken2 {
private int x;
private int y;
private int velx = 0;
private int vely = 0;
private BlokkenType type;
private BufferedImage img;
public Blokken2(BlokkenType type) {
this.type = type;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
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 BlokkenType getType() {
return type;
}
public void setType(BlokkenType type) {
this.type = type;
}
public void setImg(BufferedImage img) {
this.img = img;
}
public BufferedImage getImg() {
return img;
}
public void teken(Graphics2D g2) {
if (img != null) {
g2.drawImage(img, x, y, null);
}
}
}
enum BlokkenType {
LOOPGEBIED, BARRICADE, MUUR, SLEUTEN, SPELER, EINDVELD
}
Edit: your latest code has an error here:
class Speler extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX(), blok.getY(), 10, 10);
}
}
Regarding your edit:
Now when you create a Speler instance, you create TWO Blokken instances, one which is the Speler instance since it extends Blokken and the other which is contained by the Speler instance since it also has a Blokken field.
You update the x/y state of the first one, but you draw with the second one, and that's why no motion is being displayed. The solution is obvious: use one or the other but not both. Either have Speler extend Blokken or have it contain a Blokken instance but don't do both.

How do I paint multiple objetcs that move at different speeds in Java?

I am working on homework for class, and its late because I can't seem to understand the material despite all the research that I am doing. I am a beginner and do not know much in the way of java. Also, this is my first post so please be forgiving when you are reading this.
I am building on source code from my textbook, which I updated recently for past homework, but now I am trying to generate a class that draws multiple squares and moves those objects independently and at different speeds. They will all need to rebound off the walls as well. I followed the instructions and created two arrays that will hold the random x and y values between 1 and 10. However, I struggle with arrays and I am sure that I am not doing it correctly. So, I would love some feedback to see if I have it set up correctly.
I have a the jpanel pulling up and drawing, and as long as there is 1 square it is working fine bouncing off the walls, but things change when I draw more than one. The do not move independently and they also share the same speed. Some even disappear from time to time. This has really thrown me off. I appreciate any help!
In short, I am trying to paint new squares that all travel in different directions and at different speeds. Per the instructions we are suppose create and use a two arrays that handle the x and y values.
Here is what I have so far:
public class DotsPanel extends JPanel
{
private int delay = 15;
private final int SIZE = 7, IMAGE_SIZE = 3; // radius of each dot
private Timer timer;
private int x, y, i;
private ArrayList<Point> pointList;
static int [] xarray = new int [1000];
static int [] yarray = new int [1000];
Random rand = new Random();
//-----------------------------------------------------------------
// Constructor: Sets up this panel to listen for mouse events.
//-----------------------------------------------------------------
public DotsPanel()
{
pointList = new ArrayList<Point>();
int [] xarray = new int [1000];
int [] yarray = new int [1000];
timer = new Timer(delay, new ReboundListener());
addMouseListener (new DotsListener());
addMouseMotionListener (new DotsListener());
setBackground(Color.gray);
setPreferredSize(new Dimension(700, 500));
for(int i = 0; i < xarray.length; i++)
{
xarray[i] = rand.nextInt(7);
yarray[i] = rand.nextInt(7);
}
timer.start();
}
//-----------------------------------------------------------------
// Draws all of the dots stored in the list.
//-----------------------------------------------------------------
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.BLUE);
for (Point spot : pointList)
{
page.fillRect(spot.x-SIZE, spot.y-SIZE, 25, 25);
page.drawString("Count: " + pointList.size(), 5, 15);
}
}
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class DotsListener implements MouseListener, MouseMotionListener
{
//--------------------------------------------------------------
// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//--------------------------------------------------------------
public void mousePressed(MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
public void mouseDragged(MouseEvent event)
{
// initially I had two xarray and yarray in here just like in
// mouseClicked
// but it did not change anything when removed
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked(MouseEvent event)
{
xarray[i] = rand.nextInt(7);
yarray[i] = rand.nextInt(7);
}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent e) {}
}
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
for (Point spot : pointList)
{
spot.x += xarray[i];
spot.y += yarray[i];
if (spot.x <= 0 || spot.x >= 700)
xarray[i] = xarray[i] * -1;
if (spot.y <= 0 || spot.y >= 500)
yarray[i] = yarray[i] * -1;
repaint();
}
}
}
}
However, I struggle with arrays and I am sure that I am not doing it correctly.
I wouldn't use Arrays.
Instead, have a Ball object manage its own state. Then you can have different color, speed, size etc for each Ball. Then when the Timer fires you just calculate the new position and repaint the Ball.
Here is an example to get you started:
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.setSize(800, 600);
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);
balls.add( ball );
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Ball ball: balls)
{
ball.draw(g);
}
}
public void startAnimation()
{
Timer timer = new Timer(75, 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;
}
}
}
Since your Arrays only contain the Point you want to paint you don't have any information about the speed each point should be moved at. The best you could do is create a random amount each point should be moved each time its location is changed. This would give erratic movement as each time you move a point the distance would be random.
If you want more constant speed then you would need to create a second Array to contain the distance each point should move every time.
This starts to get messy creating a new Array every time you want a new property to be unique for the object you want to paint. That is why the approach to create a custom Object with multiple properties is easier to manage.

Java Swing - paintComponent() not drawing my Threads

I want to add to an ArrayList of Thread's which represent a ball with (x,y) coordinated and a move() method a new ball Thread every 5 seconds.
So my JPanel implements Runnable and in there i add to the ArrayList a new ball Thread.
In the paintComponent() method i use foreach loop to iterate the ArrayList of ball Thread's and start their Thread which moves them and call for repaint(). Problem is i i don't see any drawing at all(Only the player drawing).
MyPanel.java:
public class MyPanel extends JPanel implements KeyListener,Runnable
{
private static final long serialVersionUID = 1L;
private static final Color BACKGROUND_COLOR = Color.WHITE;
private static final Color NPC_BALLS_COLOR = Color.RED;
// The player is an oval
private int playerRadius = 20;
private int playerX;
private int playerY;
// True - first player position, false - otherwise
private boolean playerPosition = true;
// Array of all the balls threads
private ArrayList<BallThread> balls = new ArrayList<BallThread>();
private Thread generateBallsThread;
public MyPanel()
{
this.setBackground(MyPanel.BACKGROUND_COLOR);
this.setFocusable(true);
this.addKeyListener(this);
this.generateBallsThread = new Thread();
generateBallsThread.start();
}
// Drawing
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
final double PANEL_WIDTH = this.getWidth();
final double PANEL_HEIGHT = this.getHeight();
if (this.playerPosition)
{
this.playerX = (int)(PANEL_WIDTH / 2 - this.playerRadius);
this.playerY = (int)(PANEL_HEIGHT / 2 - this.playerRadius);
this.playerPosition = false;
}
// Drawing the player
g.setColor(Color.BLACK);
g.fillOval(playerX,playerY, this.playerRadius * 2, this.playerRadius * 2);
// Drawing npc's balls
g.setColor(MyPanel.NPC_BALLS_COLOR);
for (BallThread ball: this.balls)
{
ball.start();
g.fillOval(ball.getBall().getX(), ball.getBall().getY(),
ball.getBall().radius, ball.getBall().radius);
repaint();
}
}
// Keyboard listeners
#Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_W: // Up
{
this.playerY -= 5;
repaint();
break;
}
case KeyEvent.VK_S: // Down
{
this.playerY += 5;
repaint();
break;
}
case KeyEvent.VK_D: // Right
{
this.playerX += 5;
repaint();
break;
}
case KeyEvent.VK_A: // Left
{
this.playerX -= 5;
repaint();
break;
}
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
public int getBallXStartingPositionFromTop()
{
return (int) Math.random() * 101; // 0 - 100
}
//public int getBallYStartingPositionFromLeft()
//{
// return (int) Math.random() * 101; // 0 - 100
//}
/**
*
*
*
* Class for the balls threads.
*
*/
public class BallThread extends Thread
{
private Ball ball;
public BallThread(Ball ball)
{
this.ball.setX(ball.getX());
this.ball.setY(ball.getY());
}
#Override
public void run()
{
try
{
this.ball.move();
Thread.sleep(4000);
repaint(); // Execute paintComponent() method
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public Ball getBall()
{
return this.ball;
}
public void setBall(Ball ball)
{
this.ball = ball;
}
}
#Override
public void run()
{
try
{
Thread.sleep(5000); // 5 seconds
this.balls.add(new BallThread(new Ball(20,20)));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
} // End of MyPanel class
Ball.java:
public class Ball
{
int x;
int y;
int velocity = 1;
public int radius = 10;
public boolean directionX = true; // True - right, false - left
public boolean directionY = false; // True - up, false - down
public static final int Y_STARTING_POSITION_FROM_TOP = 0;
public Ball(int x, int y)
{
this.x = x;
this.y = y;
}
public Ball()
{
}
public int getX()
{
return this.x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return this.y;
}
public void setY(int y)
{
this.y = y;
}
public void move()
{
if (this.directionX) // Right
{
this.x += this.velocity;
}
else // Left
{
this.x -= this.velocity;
}
if (this.directionY) // Up
{
this.y -= this.velocity;
}
else
{
this.y += this.velocity;
}
}
}
And i omitted a simple JFrame class and a main() who generates the JFrame with the JPanel added to it.
Any ideas why i don't get to see the drawing of the ball Thread's?
this.generateBallsThread = new Thread();
generateBallsThread.start();
That does nothing. It is an empty Thread with no logic.
I think you want
this.generateBallsThread = new BallsThread();
generateBallThread.start();
Also, you should not be using a Thread for animation. You should be using a Swing Timer. Any logic that updates the state of a Swing component should be executed on the Event Dispatch Thread. Read the section from the Swing tutorial on Concurrency for more information. The tutorial also has a section on How to Use Swing Timers.

repaint only working after resize

I want to let a ball bounce in a screen with the following code. The problem is that it only moves when I Resize the frame. So i have my paintcomponent in my panel method. While my thread is running i run a loop where i move the ball, sleep the thread and repaint.
The ball is only moving when i resize the frame.
Can anyone help me?
public class SpelPaneel extends JPanel {
private JLabel spelLabel;
private JPanel spelPaneel;
private Image background;
private Bal bal;
public SpelPaneel() {
spelPaneel = new JPanel();
spelLabel = new JLabel("spel");
add(spelLabel);
try {
background = ImageIO.read(new File("src/Main/images/background2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
bal = new Bal(spelPaneel, 50, 50, 15);
bal.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, getWidth(), getHeight(), null);
bal.teken(g, Color.red);
}
}
class Bal extends Thread {
private JPanel paneel;
private int x, y, grootte;
private int dx, dy;
private boolean doorgaan;
public Bal(JPanel paneel, int x, int y, int grootte) {
this.paneel = paneel;
this.grootte = grootte;
this.x = x;
this.y = y;
dy = 2;
doorgaan = true;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void run() {
while (doorgaan) {
paneel.repaint();
slaap(10);
verplaats();
}
}
public void teken(Graphics g, Color kleur) {
g.setColor(kleur);
g.fillOval(x, y, 15, 15);
}
public void verplaats() {
if (x > 335 || x < 50) {
dx = -dx;
}
if (y > 235 || y < 50) {
dy = -dy;
}
x += dx;
y += dy;
setX(x);
setY(y);
}
private void slaap(int millisec) {
try {
Thread.sleep(millisec);
} catch (InterruptedException e) {
}
}
}
spelPaneel = new JPanel(); //
Your SpelPaneel class extends JPanel so there is no need to create another panel. The above line of code just creates a JPanel in memory but does nothing with it.
bal = new Bal(spelPaneel, 50, 50, 15);
Then you create your Bal Thread and pass this dummy panel to it and later attempt to do a repaint on this dummy panel.
Intead I would guess the code should be:
bal = new Bal(this, 50, 50, 15);
since "this" refers to the actual instance of the SeplPaneel that you created.

Categories