The shape is not moving when using thread in java implementing runnable - java

I have this code, that the oval shape should automatically move to the right when implementing the runnable class. However it seems not moving. Any help is much appreciated. Thanks in advance.
package movingball;
import java.awt.Color;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingBall extends JPanel{
private static final int x = 30;
private static final int y = 30;
public MovingBall(){
setBackground(Color.BLACK);
}
public MovingBall(int x, int y){
x = this.x;
y = this.y;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
MovingBall movingBall = new MovingBall();
frame.add(movingBall);
frame.setVisible(true);
Calling the thread to assign the ball object
BallUsingThread ball = new BallUsingThread(x, y);
Thread first = new Thread(ball);
first.start();
}
#Override
public void paintComponent(Graphics canvas){
super.paintComponent(canvas);
canvas.setColor(Color.BLUE);
canvas.fillOval(x, y, 100, 100);
}
}
/*Here is the second class. Where the oval shape should be moving. Any `suggestions here? Also just let me know if there are some codes need to be adjusted.*/
class BallUsingThread implements Runnable{
int x = 30;
int y = 30;
public BallUsingThread(int x, int y){
this.x = x;
this.y = y;
}
#Override
public void run() {
for(;;){
x++;
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
System.out.printf("Error",ex);
}
}
}
}

This...
private static final int x = 30;
private static final int y = 30;
makes the values unchangable...
This...
class BallUsingThread implements Runnable{
int x = 30;
int y = 30;
public BallUsingThread(int x, int y){
this.x = x;
this.y = y;
}
#Override
public void run() {
for(;;){
x++;
is someone pointless. Because of the way Java pass variables, any modifications to the value x will only be made within the context of the BallUsingThread class, MovingBall would not see them, even if you could get it to repaint.
Instead, you should probably pass a reference of MovingBall to BallUsingThread and provide a method which BallUsingThread call call which updates the x position of the ball, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MovingBall extends JPanel {
private int ballX = 30;
private int ballY = 30;
public MovingBall() {
setBackground(Color.BLACK);
}
public MovingBall(int x, int y) {
x = this.ballX;
y = this.ballY;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 700);
MovingBall movingBall = new MovingBall();
frame.add(movingBall);
frame.setVisible(true);
BallUsingThread ball = new BallUsingThread(movingBall);
Thread first = new Thread(ball);
first.start();
}
#Override
public void paintComponent(Graphics canvas) {
super.paintComponent(canvas);
canvas.setColor(Color.BLUE);
canvas.fillOval(ballX, ballY, 100, 100);
}
public void updateBall() {
if (EventQueue.isDispatchThread()) {
ballX++;
repaint();
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateBall();
}
});
}
}
}
/*Here is the second class. Where the oval shape should be moving. Any `suggestions here? Also just let me know if there are some codes need to be adjusted.*/
class BallUsingThread implements Runnable {
private MovingBall movingBall;
public BallUsingThread(MovingBall mb) {
movingBall = mb;
}
#Override
public void run() {
for (;;) {
movingBall.updateBall();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.printf("Error", ex);
}
}
}
}
Now, Swing is not thread safe (which I've accounted for), but there is a simpler solution...
Use a Swing Timer instead...
MovingBall
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MovingBall extends JPanel {
private int ballX = 30;
private int ballY = 30;
public MovingBall() {
setBackground(Color.BLACK);
}
public MovingBall(int x, int y) {
x = this.ballX;
y = this.ballY;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 700);
MovingBall movingBall = new MovingBall();
frame.add(movingBall);
frame.setVisible(true);
BallUsingTimer ball = new BallUsingTimer(movingBall);
Timer timer = new Timer(40, ball);
timer.start();
}
#Override
public void paintComponent(Graphics canvas) {
super.paintComponent(canvas);
canvas.setColor(Color.BLUE);
canvas.fillOval(ballX, ballY, 100, 100);
}
public void updateBall() {
ballX++;
repaint();
}
}
BallUsingTimer
public class BallUsingTimer implements ActionListener {
private MovingBall movingBall;
public BallUsingTimer(MovingBall mb) {
movingBall = mb;
}
#Override
public void actionPerformed(ActionEvent e) {
movingBall.updateBall();
}
}
See Concurrency in Swing and How to use Swing Timers for more details

Your thread simply updates the program memory (at each stage it increments x). The windowing subsystem is not aware of the dirty state of the component, so the paint method is not called.
You must call JComponent.repaint() and please note that the call must happen in the UI thread (for example by using SwingUtilities.invokeLater()).
Note that in this way your program doesn't have any chance of running smoothly, and bursts a lot of CPU cycles. For animations and/or games you need a looper that lets you control the running time of the frames as well as the number of frames in one second.

Related

drawImage error when trying to draw a sprite onto a JFrame

I have this really crappy sprite sheet that I made, which is basically just a bunch of circles and ovals so I can grasp Sprite animation.
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class CircleSprite extends JFrame implements ActionListener, Runnable{
BufferedImage circles;
BufferedImage[] test;
Timer timer;
int cycle = 0;
Graphics g = getGraphics();
public void asd(){
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
circles = ImageIO.read(new File("CircleTest.png"));
} catch (IOException e) {
e.printStackTrace();
}
final int width = 206;
final int height = 206;
final int rows= 2;
final int columns = 3;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test = new BufferedImage[rows * columns];
try{
for(int i = 0; i < rows; i++)
for(int j = 0;j<columns;j++)
{
test[i*columns + j] = circles.getSubimage(j * width, i * height, width, height);
}
}catch(Exception e){
e.printStackTrace();
}
timer = new Timer(500, this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
//0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, etc.
repaint();
g.drawImage(test[cycle], 25, 25, null);
if(cycle >= 5){
cycle--;
}
if(cycle <=0){
cycle++;
}
}
public void run(){
asd();
while(timer.isRunning() == false && this.isVisible() == true){
timer.start();
try {
CircleSpriteRun.t1.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error occurs here: g.drawImage(test[cycle], 25, 25, null);
At first I though it had to do with the ImageObserver being null, and looking further into it, I was wrong. Now, I think it might be because of the timer, but I don't really know too much about Timers, let alone the swing one.
This all runs on a Thread being executed in another class, and it could also have to do with the while statement in the run method, since that also involves the timer.
Since you didn't provide a runnable example, I created one to show how to properly code a Swing application.
First, you must start a Swing application with the SwingUtilities.invokeLater method. Here's how I started the CircleSprite class.
public static void main(String[] args) {
SwingUtilities.invokeLater(new CircleSprite());
}
Second, you should use a JPanel for drawing, not a JFrame. Here's the DrawingPanel I created. My version of CircleSprite draws a circle in a random location every 2 seconds.
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -4603711384104715819L;
private int x;
private int y;
private BufferedImage image;
public DrawingPanel(BufferedImage image) {
this.image = image;
this.x = 0;
this.y = 0;
setPreferredSize(new Dimension(500, 500));
}
public void setPoint(int x, int y) {
this.x = x;
this.y = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, null);
}
}
Third, you create the Swing GUI before you do anything with the Swing GUI. Here's the run method from the CircleSprite class. I create the GUI, then I start the thread that does the random drawing.
public void run() {
circle = createCircle();
frame = new JFrame("Circle Sprite");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel(circle);
frame.add(drawingPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
new Thread(new RandomDraw(drawingPanel)).start();
}
Fourth, you only extend a Swing component when you want to override a method, like I did in the DraawingPanel class. You use Swing Components otherwise.
Here's the entire, runnable, CircleSprite class. You can use this as a model for future Swing applications.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CircleSprite implements Runnable {
private BufferedImage circle;
private DrawingPanel drawingPanel;
private JFrame frame;
#Override
public void run() {
circle = createCircle();
frame = new JFrame("Circle Sprite");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel(circle);
frame.add(drawingPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
new Thread(new RandomDraw(drawingPanel)).start();
}
private BufferedImage createCircle() {
BufferedImage image = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 100, 100);
g.setColor(Color.BLUE);
g.fillOval(10, 10, 80, 80);
g.dispose();
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new CircleSprite());
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -4603711384104715819L;
private int x;
private int y;
private BufferedImage image;
public DrawingPanel(BufferedImage image) {
this.image = image;
this.x = 0;
this.y = 0;
setPreferredSize(new Dimension(500, 500));
}
public void setPoint(int x, int y) {
this.x = x;
this.y = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, null);
}
}
public class RandomDraw implements Runnable {
private DrawingPanel drawingPanel;
private Random random;
public RandomDraw(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
this.random = new Random();
}
#Override
public void run() {
while (true) {
sleep();
int x = random.nextInt(400);
int y = random.nextInt(400);
drawingPanel.setPoint(x, y);
}
}
private void sleep() {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
}
}
}
}

animated background java game

I was programming a game similar to asteroid, but I do not understand how to spawn the asteroids in the background.
now i spawn an asteroid in the main class but i want create a class for the asteroid ho i do it?
MAIN CLASS
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(flag_img)
{
background(g2d);
logo(g2d);
menu(g2d);
spaceship(g2d);
crediti(g2d);
}
}
background function(now)
private void background(Graphics2D g2d)
{
asteroidi_g_x+=r.nextInt(4);
asteroidi_g_y+=r.nextInt(1);
g2d.drawImage(asteroidi_g[0], asteroidi_g_x,asteroidi_g_y,this);
}
background function(what i want)
private void background(Graphics2D g2d)
{
asteroid asteroid = new asteroid[10];
}
and class asteroid
public class asteroid extends JPanel implements ActionListener
{
private BufferedImage images_asteroid;
private boolean flag_img;
private JPanel jp;
private int x,y;
public asteroide_grande(JPanel jp)
{
flag_img = true;
x = (jp.getWidth()/2);
y = (jp.getHeight()/2);
this.jp = jp;
try {
images_asterod = ImageIO.read(this.getClass().getResource("images/asteroid/a1.png"));
} catch(IOException e){flag = false;}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(flag_img)
{
g.drawImage(images_asteroid, 100, 100,this);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
x=x-1;
y=y+1;
repaint();
}
method paintcomponent in class doesn't work
Don't have your Asteroid class extends JPanel. Instead have it as a class that model's asteroid data and has data manipulation methods. You'll also want to have a draw method that take a Graphic context. Something like
public class Asteroid {
Image asteroidImage;
JPanel panel;
int x, y;
public Asteroid(JPanel panel, Image image, int x, int y) {
this.panel = panel;
this.asteroidImage = image;
this.x = x;
this.y = y;
}
public void drawAsteroid(Graphics g) {
g.drawImage(asteroidImage, x, y, panel);
}
public void move() {
x += 5;
}
}
Now you have a model of an asteroid, you can create a List of Asteriod objects and iterate through them and use it's drawAsteroid method to paint them. Something like
public class GamePanel extends JPanel {
List<Asteroid> asteroids;
Image asteroidImage;
public GamePanel(){
asteroidImage = ...
asteroids = new ArrayList<>();
asteroids.add(new Asteroid(GamePanel.this, asteroidImage, 100, 100));
// add more asteriods
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Asteriod asteroid: asteriods) {
asteriod.drawAsteroid(g);
}
}
}
To animate them, you'll want to use a javax.swing.Timer. See more at How to Use Swing Timers. You'll want to manipulate the Asteriod data in the Timer. With the code provided above, you can just call it's move method, then call repaint(). Something like
public GamePanel(){
...
Timer timer = new Timer(30, new ActionListener(){
public void actionPerformed(ActionEvent e) {
Iterator it = asteroids.iterator();
while (it.hasNaext()) {
Asteroid asteriod = (Asteroid)it.next();
asteroid.move();
}
}
});
}
You can see a bunch more complete example of animating multiple objects here and here and here and here and here
Here's a full example. You'll see I included a Rectangle2D object in the Astreroid class. That's just if you want to check for collision detection. You should move the Rectangle2D x and/or y with every Asreroid movement of x and y. Then you can check if asteroid.rectangle.intersects(someOtherObject)
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AsteroidBackground extends JPanel {
private static final int D_W = 400;
private static final int D_H = 600;
BufferedImage asteroidImage;
BufferedImage background;
List<Asteroid> asteroids;
Random random = new Random();
int countToAddAsteroid = 0;
int y;
public AsteroidBackground() {
try {
asteroidImage = ImageIO.read(getClass().getResource("/resources/small-asteroid.png"));
background = ImageIO.read(getClass().getResource("/resources/space.png"));
} catch (IOException ex) {
Logger.getLogger(AsteroidBackground.class.getName()).log(Level.SEVERE, null, ex);
}
asteroids = new ArrayList<>();
y = 0 - asteroidImage.getHeight();
Timer timer = new Timer(40, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (countToAddAsteroid >= 25) {
int randX = random.nextInt(D_W);
asteroids.add(new Asteroid(AsteroidBackground.this, asteroidImage, randX, y));
countToAddAsteroid = 0;
}
countToAddAsteroid++;
Iterator it = asteroids.iterator();
while (it.hasNext()) {
Asteroid asteroid = (Asteroid)it.next();
if (asteroid.y >= D_H) {
it.remove();
} else {
asteroid.move();
}
}
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
for (Asteroid asteroid : asteroids) {
asteroid.drawAsteroid(g);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public class Asteroid {
Rectangle2D rectangle;
Image asteroidImage;
JPanel panel;
int x, y;
public Asteroid(JPanel panel, Image image, int x, int y) {
this.panel = panel;
this.asteroidImage = image;
this.x = x;
this.y = y;
rectangle = new Rectangle2D.Double(
x, y, image.getWidth(panel), image.getHeight(panel));
}
public void drawAsteroid(Graphics g) {
g.drawImage(asteroidImage, x, y, panel);
}
public void move() {
y += 5;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new AsteroidBackground());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Java applet repaint a moving circle

I've just moved over from Pygame so Java 2D in an applet is a little new to me, especially when it comes to repainting the screen. In pygame you can simply do display.fill([1,1,1]) but how do I do this in an applet in Java? I understand the use of repaint() but that doesn't clear the screen - any moving object is not 'removed' from the screen so you just get a long line of painted circles.
Here's my code that I've been testing with:
package circles;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
public class circles extends Applet implements Runnable {
private static final long serialVersionUID = -6945236773451552299L;
static Random r = new Random();
String msg = "Click to play!";
static int w = 800, h = 800;
int[] txtPos = { (w/2)-50,(h/2)-50 };
int[] radiusRange = { 5,25 };
int[] circles;
static int[] posRange;
int x = 0, y = 0;
int radius = 0;
int cursorRadius = 10;
boolean game = false;
public static int[] pos() {
int side = r.nextInt(5-1)+1;
switch(side) {
case 1:
posRange = new int[]{ 1,r.nextInt(w),r.nextInt((h+40)-h)+h,r.nextInt(270-90)+90 };
break;
case 2:
posRange = new int[]{ 2,r.nextInt((w+40)-w)+w,r.nextInt(h),r.nextInt(270-90)+90 };
break;
case 3:
posRange = new int[]{ 3,r.nextInt(w),r.nextInt(40)-40,r.nextInt(180) };
break;
case 4:
posRange = new int[]{ 4,r.nextInt(40)-40,r.nextInt(h),r.nextInt(180) };
break;
}
System.out.println(side);
return posRange;
}
public void start() {
setSize(500,500);
setBackground(Color.BLACK);
new Thread(this).start();
}
public void run() {
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics e) {
Graphics2D g = (Graphics2D) e;
if(System.currentTimeMillis()%113==0) {
x+=1;
y+=1;
}
g.setColor(Color.BLUE);
g.fillOval(x,y,20,20);
repaint();
}
}
You need to call super.paint(g); in your paint method, as to not leave paint artifacts.
Never call repaint() from inside the paint method
Don't explicitly call paint, as you do in update(), when you mean to call reapaint()
just update the x and y values from inside the update() method, then call repaint()
You don't need to take a Graphics argument in update()
You need to call update() somewhere repeatedly in a loop, as it updates the x and y and reapint()s
If your class is going to be a Runnable, then you should put some code in the run() method. That's probably where you should have your loop
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class circles extends Applet implements Runnable {
int x = 0, y = 0;
public void start() {
setSize(500, 500);
setBackground(Color.BLACK);
new Thread(this).start();
}
public void run() {
while (true) {
try {
update();
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
public void update() {
x += 5;
y += 6;
repaint();
}
public void paint(Graphics e) {
super.paint(e);
Graphics2D g = (Graphics2D) e;
g.setColor(Color.BLUE);
g.fillOval(x, y, 20, 20);
}
}
Side Notes
Why use Applets in the first place. If you must, why use AWT Applet and not Swing JApplet? Time for an upgrade.
Here's how I'd redo the whole thing in Swing, using a Swing Timer instead of a loop and Thread.sleep, as you should be doing.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Circle extends JPanel{
private static final int D_W = 500;
private static final int D_H = 500;
int x = 0;
int y = 0;
public Circle() {
setBackground(Color.BLACK);
Timer timer = new Timer(50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
x += 5;
y += 5;
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(x, y, 20, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new Circle());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
See How to use Swing Timers
See Create GUIs with Swing
Here's more advanced example for you to look at and ponder.
UPDATE
"Problem is, that's a JPANEL application. I specifically want to make an applet easily usable on a web page. "
You can still use it. Just use the JPanel. Take out the main method, and instead of Applet, use a JApplet and just add the JPanel to your applet. Easy as that.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CircleApplet extends JApplet {
#Override
public void init() {
add(new Circle());
}
public class Circle extends JPanel {
private static final int D_W = 500;
private static final int D_H = 500;
int x = 0;
int y = 0;
public Circle() {
setBackground(Color.BLACK);
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
x += 5;
y += 5;
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(x, y, 20, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
}
}

how to create repetitive Graphic object with Timer in Java

I've tried to create Graphic object that this object was working timer/timerTask.I could work for a single object but if I create new object it could not work as I want. I want to work it like tetris.
Here's my code
That's my first class prosek
import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.*;
public class prosek extends JPanel{
public static int boyut; // size
public static int koordinatx; //coordx
public static int koordinaty; //coordy
public static boolean tekrar; //repeat
public static int yukseklik; //height
private Timer timer;
private LinkedList<TimerTask> taskList=new LinkedList<TimerTask>();
public prosek(){
yukseklik=140;
tekrar=false;
koordinatx=0;
koordinaty=-20;
boyut=20;
startSampling();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.RED);
g2d.fillRect(koordinatx, koordinaty, boyut+1, boyut+1);
g2d.dispose();
}
public void moveRectangle()
{
if(yukseklik<=140)
{
if(koordinaty<140) koordinaty=koordinaty+boyut;
else
{
yukseklik-=20;
stopSampling();
}
}
}
void startSampling(){
TimerTask task=new TimerTask(){
public void run() {
moveRectangle();
repaint();
}
};
Timer timer=new Timer();
timer.scheduleAtFixedRate(task,0, 500);
taskList.add(task);
}
void stopSampling(){
if(taskList.isEmpty()){
return;
}
taskList.removeFirst().cancel();
}
}
------------
That's my second class prosekt
import javax.swing.*;
import java.awt.*;
public class prosekt extends JFrame {
public prosekt(){
Container container=getContentPane();
container.setLayout(new GridLayout(0,1));
container.add(new prosek());
setSize(100,200);
setVisible(true);
add(container);
}
public static void main(String args[])
{
prosekt p=new prosekt();
}
}
I've made some changes to your code.
The first thing I did was to define a DropObject class. This makes it easier to have more than one drop object.
Here's the code for the DropObject class. It's a basic getter / setter model class. I used a Rectangle to hold the coordinates and size of the drop object.
DropObject class
import java.awt.Rectangle;
public class DropObject {
private int yukseklik; // height
private Rectangle object;
public DropObject(int yukseklik, int x, int y, int size) {
this.yukseklik = yukseklik;
this.object = new Rectangle(x, y, size, size);
}
public int getYukseklik() {
return yukseklik;
}
public void setYukseklik(int yukseklik) {
this.yukseklik = yukseklik;
}
public Rectangle getObject() {
return object;
}
public void setObject(Rectangle object) {
this.object = object;
}
}
I modified your JPanel class to use the DropObject class. I also capitalized Prosek, since Java class names are supposed to start with a capital letter.
I added the new objects in the moveRectangle method, just so you would see more than one object falling. The adding of new objects needs to take place somewhere else.
Prosek class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class Prosek extends JPanel {
private static final int yukseklik = 140;
private DropObject koordinat;
private List<DropObject> objects = new LinkedList<DropObject>();
private LinkedList<TimerTask> taskList = new LinkedList<TimerTask>();
public Prosek() {
koordinat = new DropObject(yukseklik, 0, -20, 20);
objects.add(koordinat);
startSampling();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
for (DropObject o : objects) {
Rectangle r = o.getObject();
g2d.fillRect(r.x, r.y, r.width, r.height);
}
}
public void moveRectangle() {
for (int i = (objects.size() - 1); i >= 0; i--) {
DropObject o = objects.get(i);
Rectangle r = o.getObject();
if (o.getYukseklik() <= 140) {
if (r.y < 140) {
r.y += r.height;
o.setObject(r);
} else {
o.setYukseklik(o.getYukseklik() - r.height);
// stopSampling();
}
}
if ((r.y >= 70) && (r.y <= 80)) {
objects.add(new DropObject(yukseklik, 0, -20, 20));
}
}
}
void startSampling() {
TimerTask task = new TimerTask() {
public void run() {
moveRectangle();
repaint();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 500);
taskList.add(task);
}
void stopSampling() {
if (taskList.isEmpty()) {
return;
}
taskList.removeFirst().cancel();
}
}
I made some changes to your main class. I called the SwingUtilities invokeLater method to ensure that your Swing components were created and used on the Event Dispatch thread. I used a JFrame instead of extending JFrame. You should only extend a Swing component when you're overriding one of the component methods.
Composition over inheritance
Prosekt class
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Prosekt implements Runnable {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
container.setLayout(new GridLayout(0, 1));
container.add(new Prosek());
frame.setSize(100, 200);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Prosekt());
}
}

JPanel Layout Image Cutoff

I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either.
So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code.
Custom JPanel:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GraphicsPanel extends JPanel implements MouseListener {
private Entity test;
private Timer timer;
private long startTime = 0;
private int numFrames = 0;
private float fps = 0.0f;
GraphicsPanel() {
test = new Entity("test.png");
Thread t1 = new Thread(test);
t1.start();
Entity ent2 = new Entity("images.jpg");
ent2.setX(150);
ent2.setY(150);
Thread t2 = new Thread(ent2);
t2.start();
Entity ent3 = new Entity("test.png");
ent3.setX(0);
ent3.setY(150);
Thread t3 = new Thread(ent3);
t3.start();
//ESSENTIAL COMMENT ANY OF THESE and you will see the problem immediately
//You can use ANY image to reproduce the problem
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(test);
add(ent2);
add(ent3);
//GAMELOOP
timer = new Timer(30, new Gameloop(this));
timer.start();
addMouseListener(this);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setClip(0, 0, getWidth(), getHeight());
g2.setColor(Color.BLACK);
g2.drawString("FPS: " + fps, 1, 15);
}
public void getFPS()
{
++numFrames;
if (startTime == 0) {
startTime = System.currentTimeMillis();
} else {
long currentTime = System.currentTimeMillis();
long delta = (currentTime - startTime);
if (delta > 1000) {
fps = (numFrames * 1000) / delta;
numFrames = 0;
startTime = currentTime;
}
}
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
class Gameloop implements ActionListener
{
private GraphicsPanel gp;
Gameloop(GraphicsPanel gp) {
this.gp = gp;
}
public void actionPerformed(ActionEvent e) {
try {
gp.getFPS();
gp.repaint();
} catch (Exception ez) { }
}
}
}
Main class:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class MainWindow
{
public static void main(String[] args)
{
new MainWindow();
}
private JFrame frame;
private GraphicsPanel gp = new GraphicsPanel();
MainWindow()
{
EventQueue.invokeLater(new Runnable() {
public void run() {
frame = new JFrame("Graphics Practice");
frame.setSize(680, 420);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(gp);
}
});
}
}
Custom JComponent
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
public class Entity extends JComponent implements Runnable {
private BufferedImage bImg;
private int x = 0;
private int y = 0;
private int entityWidth, entityHeight;
private String filename;
Entity(String filename) {
this.filename = filename;
}
public void run() {
bImg = loadBImage(filename);
entityWidth = bImg.getWidth();
entityHeight = bImg.getHeight();
setPreferredSize(new Dimension(entityWidth, entityHeight));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(bImg, x, y, null);
g2d.dispose();
}
public BufferedImage loadBImage(String filename) {
try {
bImg = ImageIO.read(getClass().getResource(filename));
} catch (Exception e) { }
return bImg;
}
public int getEntityWidth() { return entityWidth; }
public int getEntityHeight() { return entityHeight; }
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; }
}
One thing I notice is that your preferred size is calculated incorrectly. You set the preferred size to be the size of the image. The problem is you paint the image at (x, y). So the preferred size needs to take that into account.
Otherwise I don't understand the question and running the code doesn't help since I don't know the size of your images whether they should be large, small, same size etc..
#camickr is likely right about why your existing approach isn't getting the results you want.
As an alternative, you might consider using JInternalFrame within a JDesktopPane. In this way, your images would be documents that could be individually moved, resized and scrolled. The article How to Use Internal Frames gives an idea of how such an implementation might look. This example shows a simple approach to staggering the frames and selecting them from a menu.

Categories

Resources