Drawing a Image from Thread - java

I have got application with class extends JPanel. This panel is drawing an Image. here is a code:
public class BackgroundImage extends JPanel{
private BufferedImage img;
private File imageFile;
public BackgroundImage(){
super();
Samolot s1 = new Samolot(200,200,new Dimension(15,15));
s1.start();
imageFile = new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_mapa.jpg");
try {
mapa = ImageIO.read(imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, getWidth(), getHeight(), null);
}
}
What i want to do is a class ball which will be extends Threads.
Each ball will be next thread. Balls need to move, for example from left to right by simply incrementation coordinate int x which defines X-position of created ball.
To show that ball is moving i need to draw an image in current coordinates. after changing position, thread repaint ball to next position. What is more i need to add MouseListener to my ball, to not make problem harder after click it need just to System.out.println("somemessage");
My questions:
where i need to draw my ball? in class Ball? or BackgroundImage? How it should be look like?
where and how add MouseListener to make him works propertly.
how to repaint my panel in every cycle of thread.
here is a code of my Ball class:
class Ball extends Thread {
// The image to display
private BufferedImage img;
private int x;
private int y;
Dimension dim;
public void run() {
super.run();
try {
while(x<1000){
Thread.sleep(300);
x++;
System.out.println(x);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Instantiate the panel and perform initialization
Samolot(int x, int y, Dimension d) {
this.x = x;
this.y = y;
this.dim = d;
try {
img = ImageIO.read(new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_samolot.png"));
} catch (IOException e) { }
}
}
I read that i shouldnt draw anything in other threads then my main thread(here BackgroundImage).
I was thinking about something like that, however it doesnt work:
class Ball:
class Ball extends JComponent implements Runnable {
MouseListener listener;
public void addListener(MouseListener toAdd) {
listener = toAdd;
}
// The image to display
private BufferedImage img;
private int x;
private int y;
Dimension dim;
public void run() {
try {
while(x<1000){
Thread.sleep(300);
x++;
listener.mouseClicked(new MouseEvent(this, 1, 1, 0, x, y, 1, true));
System.out.println(x);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Instantiate the panel and perform initialization
Samolot(int x, int y, Dimension d) {
this.x = x;
this.y = y;
this.dim = d;
try {
img = ImageIO.read(new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_samolot.png"));
} catch (IOException e) { }
}
public BufferedImage getImg(){
return this.img;
}
}
Class BackgroundImage:
public class BackgroundImage extends JPanel implements MouseListener{
private BufferedImage mapa;
private File imageFile;
private Ball s1;
public MapaSwiata(){
super();
s1 = new Ball(200,200,new Dimension(15,15));
Thread t = new Thread(s1);
t.start();
imageFile = new File("C:\\Users\\Katie\\Documents\\Eclipse\\Samolot\\src\\Pics\\img_mapa.jpg");
try {
mapa = ImageIO.read(imageFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(mapa, 0, 0, getWidth(), getHeight(), null);
g2d.drawImage(s1.getImg(), 200, 200, 15, 15, null);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("message");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}

Related

Repaint() not being called if i use ImageIO.read()

When i try to set value to BufferedImage called dinoImage in Dino.java in a constructor i just get a blank screen every time (second picture) because repaint() is not being called, but if i set it to null it is working just fine but without this image (first picture).
No exceptions, everything seems fine in this code, this problem appears when i try to set value to this field using static method getImage of Resource.java which uses this line of code ImageIO.read(new File(path)) and it causes that repaint() is not being called, i guess this line causes such weird behavior but i dont know how to solve it.
Main.java
public class Main {
public static void main(String[] args) {
GameWindow gameWindow = new GameWindow();
gameWindow.startGame();
}
}
GameWindow.java
public class GameWindow extends JFrame {
private GameScreen gameScreen;
public GameWindow() {
super("Runner");
setSize(1000, 500);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameScreen = new GameScreen();
add(gameScreen);
}
public void startGame() {
gameScreen.startThread();
}
}
GameScreen.java
public class GameScreen extends JPanel implements Runnable, KeyListener {
private Thread thread;
public static final double GRAVITY = 0.1;
public static final int GROUND_Y = 300;
private Dino dino;
public GameScreen() {
thread = new Thread(this);
dino = new Dino();
}
public void startThread() {
thread.start();
}
#Override
public void run() {
while(true) {
try {
Thread.sleep(20);
dino.updatePosition();
repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.drawLine(0, GROUND_Y, getWidth(), GROUND_Y);
dino.draw(g);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
dino.jump();
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("Key Released");
}
}
Dino.java
public class Dino {
private double x = 100;
private double y = 100;
private double speedY = 0;
private BufferedImage dinoImage;
public Dino() {
dinoImage = getImage("data/dino.png");
}
public void updatePosition() {
if(y + speedY >= GROUND_Y - 100) {
speedY = 0;
y = GROUND_Y - 100;
} else {
speedY += GRAVITY;
y += speedY;
}
}
public void jump() {
if(y == GROUND_Y - 100) {
speedY = -5;
y += speedY;
}
}
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect((int)x, (int)y, 100, 100);
g.drawImage(dinoImage, (int)x, (int)y, null);
}
}
Resource.java
public class Resource {
public static BufferedImage getImage(String path) {
BufferedImage image = null;
try {
image = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
setSize(1000, 500);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameScreen = new GameScreen();
add(gameScreen);
Swing components need to be added to the frame BEFORE the frame is made visible. Otherwise the panel has a size of (0, 0) and there is nothing to paint.
The code should be something like:
gameScreen = new GameScreen();
add(gameScreen);
setSize(1000, 500);
setVisible(true);

How to draw a circle on top of an image?

I'm learning how to make java applets, and I'm trying to take an image of an intersection and run a circle across it. I'm able to import the image and have it displayed in the applet, but the circle won't show on top of it. I'm just having it start in the top left and go towards the left of the screen. Any ideas?
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.TextField;
public class App extends Applet implements Runnable{
int x,y;
boolean running = true;
Image background;
/**
*
*/
private static final long serialVersionUID = -8667920279388305018L;
public void init() {
x = 0;
y = 0;
background = getImage(getCodeBase(), "street.png");
BackGroundPanel bgp = new BackGroundPanel();
bgp.setLayout(new FlowLayout());
bgp.setBackGroundImage(background);
setSize(500,500);
// set the layout of the applet to Border Layout
setLayout(new BorderLayout());
// now adding the panel, adds to the center
// (by default in Border Layout) of the applet
add(bgp);
}
#Override
public void start() {
new Thread(this).start();
}
#Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillOval(x, y, 100, 100);
}
#Override
public void run() {
while(running) {
++x;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
````}
class BackGroundPanel extends Panel implements ImageObserver {
/**
*
*/
private static final long serialVersionUID = 1L;
Image backGround;
BackGroundPanel() {
super();
}
public void paint(Graphics g) {
// get the size of this panel (which is the size of the applet),
// and draw the image
g.drawImage(getBackGroundImage(), 0, 0,
(int)getBounds().getWidth(), (int)getBounds().getHeight(), this);
}
public void setBackGroundImage(Image backGround) {
this.backGround = backGround;
}
private Image getBackGroundImage() {
return backGround;
}
}
You can draw everything in paint and not use the panel:
public class App extends Applet implements Runnable{
int x,y;
boolean running = true;
Image background;
/**
*
*/
private static final long serialVersionUID = -8667920279388305018L;
public void init() {
x = 0;
y = 0;
background = getImage(getCodeBase(), "street.png");
setSize(500,500);
// set the layout of the applet to Border Layout
setLayout(new BorderLayout());
}
#Override
public void start() {
new Thread(this).start();
}
#Override
public void paint(Graphics g) {
g.drawImage(background, 0, 0,
(int)getBounds().getWidth(), (int)getBounds().getHeight(), this);
g.setColor(Color.BLACK);
g.fillOval(x, y, 100, 100);
}
#Override
public void run() {
while(running) {
++x;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
Or if you want the panel you add it and draw everything there - you have to move some stuff to the panel though such as the x, y and the image - and you repaint the panel:
public class App extends Applet implements Runnable{
boolean running = true;
BackGroundPanel bgp = new BackGroundPanel();
/**
*
*/
private static final long serialVersionUID = -8667920279388305018L;
public void init() {
bgp.setLayout(new FlowLayout());
bgp.setImage(getImage(getCodeBase(), "street.png"));
setSize(500,500);
// set the layout of the applet to Border Layout
setLayout(new BorderLayout());
// now adding the panel, adds to the center
// (by default in Border Layout) of the applet
add(bgp);
}
#Override
public void start() {
new Thread(this).start();
}
#Override
public void paint(Graphics g) {
}
#Override
public void run() {
while(running) {
++bgp.x;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bgp.repaint();
}
}
````}
class BackGroundPanel extends Panel implements ImageObserver {
int x,y;
/**
*
*/
private static final long serialVersionUID = 1L;
Image background;
BackGroundPanel() {
super();
x = 0;
y = 0;
}
public void setImage (Image i) {
background=i;
}
public void paint(Graphics g) {
// get the size of this panel (which is the size of the applet),
// and draw the image
g.drawImage(background, 0, 0,
(int)getBounds().getWidth(), (int)getBounds().getHeight(), this);
g.setColor(Color.BLACK);
g.fillOval(x, y, 100, 100);
}
public void setBackGroundImage(Image backGround) {
this.backGround = backGround;
}
private Image getBackGroundImage() {
return backGround;
}
}

how can i display my player's sprite sheet using java

hello i really need your help if you would be kind to help me out i'll appreciate it a lot .i have recently started learning java
i am making a java program that allows my player to jump and move to the place of the mouse i think that i have succeeded to make that but it not really SPECIFIC ;
also i want to display my sprite sheet so that he would look like he is really walking but i am having a problem in this part
here is my codes :
package animation;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.awt.*;
import javax.swing.*;
import animation.Boulle.move;
import gfx.Sprite;
import gfx.SpriteSheet;
public class deux_bulle extends JFrame implements MouseListener, MouseMotionListener {
Monp p;
int X, Y, x = 150, y = 150;
Thread t, t2, t3,t4;
int f = 0;
boolean b = false;
public Graphics g;
private int framedelay;
public static SpriteSheet sheet;
public static gfx.Sprite Sprite[] = new gfx.Sprite[3]; // my sprite sheet
// has 3 pictures
public deux_bulle() {
setSize(400, 400);
p = new Monp();
sheet = new SpriteSheet("/Untitled.png");
add(p);
p.addMouseListener(this);
p.addMouseMotionListener(this);
for (int i = 0; i < Sprite.length; i++) {
Sprite[i] = new Sprite(sheet, i + 1, 1);
}
}
class Monp extends JPanel {
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
}
}
class moveX implements Runnable {
#Override
public void run() {
while (x < X) {
try {
x++;
if (f < 3)
//g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (x > X) {
try {
x--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class image implements Runnable{
public void run() {
framedelay++;
if (framedelay>=3)
{f++;
if(f>=3)
{f=0;}
framedelay=0;}
}}
class moveY implements Runnable {
#Override
public void run() {
while (y < Y) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y > Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class jump implements Runnable {
#Override
public void run() {
int p = y;
while (y != Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y != p) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
deux_bulle db = new deux_bulle();
db.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Y = 70;
t3 = new Thread(new jump());
t3.start();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
X = e.getX();
Y = e.getY();
t4 = new Thread(new image());
t = new Thread(new moveX());
t2 = new Thread(new moveY());
t.start();
t2.start();
t4.start();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
my sprite sheet class
package gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(String path) {
try {
sheet= ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getSprite(int x,int y)
{
return sheet.getSubimage(x*66-66,y*66-66,66,66);}
}
my sprite class
package gfx;
import java.awt.image.BufferedImage;
public class Sprite {
public SpriteSheet sheet;
public BufferedImage image;
public Sprite(SpriteSheet sheet,int x,int y) {
image= sheet.getSprite(x, y);
}
public BufferedImage getBufferedIamge(){
return image;
}
}

Fix background image applet

I'm having some issues with my code.
I want to fix the background image to stay there fixed, meanwhile other components can move.
It's a simple a game where a circle avoid the squares but the istruction about the game will be added further.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;
import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{
Thread r;
Image bg = null;
int a,b;
int x = 600;
int y = 400;
public void init(){
setSize(600,600);
try
{
MediaTracker tr = new MediaTracker (this);
bg = getImage
(new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
tr.addImage(bg, 0);
} catch (Exception e) { System.out.println(e.toString());
}
}
public void start(){
if(r == null){
r = new Thread(this);
r.start();
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,this);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(20));
g2.draw(new Line2D.Float(0, 500, 600, 500));
g.fillRect(x, y, 20, 20);
}
public void pp(Graphics g){
}
public void run() {
Thread Th = Thread.currentThread();
while(r == Th) {
if(a < 600) {
a = a+10;
x = x-10;
repaint();
}else{
repaint();
a = 30;
x = 600;
}
try {
Thread.sleep(100);
} catch(InterruptedException e) { }
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
if you run the code, you'll see that the line and the background will be loaded a lot of time...

Costume component error "no ComponentUI class"

I am creating a costume component in Model UIDelegate using DrawPad example. However, for some reason I get the error UIDefaults.getUI() failed: no ComponentUI class. I am not even sure if I am implementing Model UIDelegate properly. But why am I getting that error?
Main
public class Main {
static JFrame frame;
static JButton clearButton;
static DrawPad drawPad;
public static void main(String[] args) {
UIManager.put("DrawPadUI", "BasicDrawPadUI");
frame = new JFrame();
drawPad = new DrawPad();
clearButton = new JButton("Clear");
frame.add(drawPad, BorderLayout.CENTER);
clearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Graphics g = frame.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
}
});
frame.add(clearButton, BorderLayout.SOUTH);
frame.setSize(280, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
BasicDrawPadUI
public class BasicDrawPadUI extends ComponentUI implements MouseListener, MouseMotionListener {
Image image;
Graphics2D graphics2D;
int currentX, currentY, oldX, oldY;
JFrame frame;
JButton clearButton;
public static ComponentUI createUI(JComponent c) {
return new BasicDrawPadUI();
}
public void paintComponent(Graphics g, JComponent c) {
if (image == null) {
image = c.createImage(c.getWidth(), c.getHeight());
graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
clear(c);
}
g.drawImage(image, 0, 0, null);
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
currentX = e.getX();
currentY = e.getY();
if (graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
//repaint();
oldX = currentX;
oldY = currentY;
}
public void clear(JComponent c) {
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, c.getWidth(), c.getHeight());
graphics2D.setPaint(Color.black);
c.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
oldX = e.getX();
oldY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
DrawPad
class DrawPad extends JComponent {
private final static String ID = "DrawPadUI";
public DrawPad() {
updateUI();
}
public void updateUI() {
setUI(UIManager.getUI(this));
}
#Override
public String getUIClassID() {
return ID;
}
}
Change UIManager.put("DrawPadUI", "BasicDrawPadUI"); to UIManager.put("DrawPadUI", "drawpad.BasicDrawPadUI");
You need to specify the full qualified class name of the UI class, including the package name
I'll need to have a look to be sure, but when it calls createUI, you could grab a reference to the component
Override the installUI method from ComponentUI and when it's called, maintain a reference to the component that is passed to you.
private DrawPad drawPad;
//...
#Override
public void installUI(JComponent c) {
drawPad = (DrawPad) c;
// Install required listeners and other functionality
}
Equally, in uninstallUI, you should dereference any strong references you have and uninstall your listeners
#Override
public void uninstallUI(JComponent c) {
// Uninstall any listeners
drawPad = null;
}
Have a look at custom java Swing component Model, UIDelegate, component format for a complete implementation.
Also, you should NEVER maintain a reference to a Graphics2D context that you did not create yourself

Categories