adding background pic to JFrame - java

I'm trying to follow this answer to add a background picture to a JFrame and I'm getting a weird error. While debugging my url is coming back null and I get a window that pops up saying "Class File Editor" source not found the source attachment does not contain the source for the file Launcher.class you can change the source attachment by clicking Chang Attached Source below. What does that mean?
here's the code that I have so far:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
getContentPane().add(new BackgroundImage());
int xCoord = 10;
int yCoord = 10;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 10;
yCoord +=40;
}
xCoord += 40;
if(i % 40 == 0)
yCoord += 8;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
getContentPane().add(button[i]);
}
setTitle("Delux Keno");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.io.*;
public class Button extends JButton {
private String name;
private int xCoord;
private int yCoord;
private final int xSize = 40;
private final int ySize = 40;
private int buttonNumber;
private String picture;
public Button(String inName, int inXCoord, int inYCoord, int inButtonNumber)
{
xCoord = inXCoord;
yCoord = inYCoord;
buttonNumber = inButtonNumber;
picture = "graphics\\" + buttonNumber + "normal.png";
super.setName(name);
super.setIcon(new ImageIcon(picture));
super.setBounds(xCoord, yCoord, xSize, ySize);
}
}
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g)
{
//super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
any sugesstions will be appriciated!!

set classpath by #Gagandeep Bali
don't perform any FileIO in paintComponent, load this image one time as local variable, pass variable in paintComponent
for Bingo, Minesweaper to use JToggleButton instead of JButton

went at it a different way, using a JLabel. Here's my final code:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
JLabel background = new JLabel(new ImageIcon ("graphics\\formBackground.png"));
background.setBounds(0,0,600,600);
//getContentPane().add(new BackgroundImage());
int xCoord = 85;
int yCoord = 84;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 12;
yCoord +=44;
}
if(i % 40 == 0)
yCoord += 10;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
xCoord += 42;
getContentPane().add(button[i]);
}
add(background);
setTitle("Delux Keno");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}

another problem I found is that you need to use setBounds() for the JPanel for it to have any size. To do it the first way I tried this is the updated BackgroundImage class:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
super.setBounds(0,0,600,600);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}

Related

Java apps (based on JSwing) performance consuming?

I'm new to Java Programming. Recently I'm developing a mini game with JSWing. However, after coding for awhile the in-game FPS dropped terribly. When I tracked it on Task Manager I had result like this:
Can someone tell me what's wrong? I only used loops, JLabel with icons, Paint Graphics methods, mouseMotionEvent in my code.
Here is the code in the main game
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Game extends JPanel {
int numb = 2;
int pts = 5;
Kitty[] Kitties = new Kitty[4];
public Game() {
for (int i = 0; i < Kitties.length; i++)
Kitties[i] = new Kitty();
}
#Override
public void paint(Graphics graphics) {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("city.jpg"));
} catch (IOException e) {
System.out.println("java io");
}
graphics.drawImage(img, 0, 0, null);
//paints square objects to the screen
for (int i = 0; i < numb;i++) {
Kitties[i].paint(graphics);
}
}
public void update(TheJPanel frame) {
if (frame.a >= 0 && frame.a < 500) numb = 2;
if (frame.a>= 500) numb = 3;
for (int i = 0; i< numb; i++) {
int disty = 500 - Kitties[i].squareYLocation;
int distx = Kitties[i].squareXLocation - frame.x;
if ( Kitties[i].squareYLocation < 600 && disty <= 5 && disty >= -80 && distx < 260 && distx > -100){
frame.a +=pts;
if (Kitties[i].kittype == 6) frame.a += pts;
if (frame.a >= 500) {
Kitties[i].fallSpeed = Kitties[i].FallSpeedlvl2();
pts = 10;
}
Kitties[i].squareYLocation = -200;
Kitties[i].generateKittype();
Kitties[i].generateRandomXLocation();
Kitties[i].generateRandomFallSpeed();
frame.point.setText("Point:" + String.valueOf(frame.a));
frame.lives.setText("Lives:" + String.valueOf(frame.count));
}
if(Kitties[i].squareYLocation > 610){
frame.count--;
Kitties[i].generateKittype();
Kitties[i].generateRandomXLocation();
Kitties[i].generateRandomFallSpeed();
Kitties[i].squareYLocation = -200;
}
if (Kitties[i].squareYLocation >=605) frame.catFall(Kitties[i].squareXLocation);
if(Kitties[i].squareYLocation <= 610){
Kitties[i].squareYLocation += Kitties[i].fallSpeed;
}
}
}
public static void main(String[] args) throws InterruptedException {
Game game = new Game();
TheJPanel frame = new TheJPanel();
frame.add(game);
frame.setVisible(true);
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Saving kitties");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
while (frame.count>0) {
game.update(frame);
game.repaint();
Thread.sleep(4);
}
if (frame.count == 0) {
JOptionPane.showMessageDialog(null, "You lost!", "Game over!", JOptionPane.ERROR_MESSAGE);
game.setVisible(false);
frame.getContentPane().removeAll();
frame.getContentPane().repaint();
frame.bask.setVisible(false);
frame.background.setVisible(false);
}
}
}
Here is the code for the main Jframe
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* #author Imba Store
*/
public class TheJPanel extends JFrame implements MouseMotionListener {
protected int x;
protected int a = 0;
protected int count = 20;
protected JLabel bask = new JLabel();
protected JLabel background = new JLabel();
protected JLabel point = new JLabel();
protected JLabel lives = new JLabel();
Timer fall;
protected int time =0;
public TheJPanel() {
this.addMouseMotionListener(this);
InitContent();
}
protected void InitContent() {
Icon img = new ImageIcon(getClass().getResource("basket.png"));
bask.setIcon(img);
Icon themes = new ImageIcon(getClass().getResource("city2.png"));
background.setIcon(themes);
background.setBounds(0, 699, 1000, 300);
point.setFont(new java.awt.Font("Trebuchet MS", 1, 35));
point.setText("Point:" + String.valueOf(a));
point.setBounds(20,908,240,50);
point.setForeground(Color.white);
lives.setBounds(800, 908,200,50);
lives.setFont(new java.awt.Font("Trebuchet MS", 1, 35));
lives.setForeground(Color.white);
lives.setText("Point:" + String.valueOf(count));
point.setOpaque(false);
add(point);
add(lives);
add(bask);
add(background);
bask.setSize(400,148);
}
#Override
public void mouseMoved (MouseEvent me)
{
x = me.getX();
background.setBounds(0, 699, 1000, 300);
bask.setBounds(x, 700, 400, 148);
}
#Override
public void mouseDragged (MouseEvent me)
{
}
public void catFall(int getX){
Icon fell = new ImageIcon(getClass().getResource("kitty-fall.png"));
JLabel fellcat = new JLabel();
fellcat.setIcon(fell);
fellcat.setBounds(getX, 760, 220, 220);
add(fellcat);
add(background);
fall = new Timer(1500, new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
getContentPane().remove(fellcat);
}
});
fall.setRepeats(false);
fall.start();
}
}
And this is the class for the falling cats
package game;
/**
*
* #author Imba Store
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public final class Kitty extends JLabel {
protected int squareXLocation;
protected int squareYLocation = -200;
protected int fallSpeed = 1;
protected int kittype;
Random rand = new Random();
public int generateRandomXLocation(){
return squareXLocation = rand.nextInt(800);
}
public int generateRandomFallSpeed(){
return fallSpeed = rand.ints(3, 4).findFirst().getAsInt();
}
public int FallSpeedlvl2() {
return fallSpeed = rand.ints(3,7).findFirst().getAsInt();
}
public int generateKittype() {
return kittype = rand.ints(1,8).findFirst().getAsInt();
}
#Override
public void paint(Graphics g) {
BufferedImage img = null;
BufferedImage thugcat = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("kitty.png"));
thugcat = ImageIO.read(getClass().getResourceAsStream("thug-kitty.png"));
} catch (IOException e) {
System.out.println("Java IO");
}
if (kittype == 6) {
g.drawImage(thugcat, squareXLocation, squareYLocation, null);
}
else g.drawImage(img, squareXLocation,squareYLocation,null);
}
public Kitty(){
generateRandomXLocation();
generateRandomFallSpeed();
generateKittype();
}
public void paint(Graphics graphics) {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("city.jpg"));
Custom painting is done by overriding paintComponent(...) not paint(). The first statement should then be super.paintComponent().
A painting method is for painting only. Don't do I/O in the painting method. This will cause the image to be read every time you repaint the panel.
Thread.sleep(4);
Sleeping for 4ms is not enough. That will attempt to repaint 250 times a second which is too often. There is no need for the frame rate to be that fast.
Kitty[] Kitties = new Kitty[4];
Variable names should not start with an upper case character. Most of your names are correct. Be consistent!
point.setBounds(20,908,240,50);
Don't use setBounds(). Swing was designed to be used with layout managers. Set a layout manager for you background and then add the components.
public int FallSpeedlvl2() {
Methods should NOT start with an upper case character. Again, most are correct. Be Consistent!!!

Setting up javax.swing.Timer

Ok I'm doing a project and the image is supposed to move around randomly and when the user clicks on the image it's supposed to count how many times the click on it. From there on it keeps moving until they x out. However, I made the mistake of making the image move AFTER they click on it, so when the program starts the image isn't already moving. I need it to move from the beginning of the program.
Attached here because for whatever reason, stack overflow keeps saying I formatted wrong.
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
// Zombie class
public class Zombie {
//declare variables
private int x;
private int y;
private int size;
private Image image;
//constructor
public Zombie(int xIn, int yIn, String imagePath) {
x = xIn;
y = yIn;
size = Settings.DEFAULT_SIZE;
setImage(imagePath);
}
//getter for x
public int getX() {
return x;
}
//getter for y
public int getY() {
return y;
}
//setter for x
public void setX(int x) {
this.x = x;
}
//setter for y
public void setY(int y) {
this.y = y;
}
//drawImage method
public void update(Graphics g) {
g.drawImage(image, x, y, size, size, null);
}
//try catch exception, if image isn't found
public void setImage(String imagePath) {
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException ioe) {
System.out.println("Unable to load image file.");
}
}
}
public class Settings {
//adjusts the width and height of the creature
public static final int WIDTH = 500;
public static final int HEIGHT = 300;
public static final int DEFAULT_SIZE = 50;
//image name
public static final String ZOMBIE_IMAGE = "zombie.png";
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
class Controller implements MouseListener {
//declares variables
Zombie zombie;
View view;
private int count = 0;
Controller() {
//System.out.println ("Controller()");
}
public void addZombie(Zombie z){
//System.out.println("Controller: adding zombie");
this.zombie = z;
}
public void addView(View v){
//System.out.println("Controller: adding view");
this.view = v;
}
public void mousePressed(MouseEvent e) {
//System.out.println("Controller sees mouse pressed: acting on Model");
int prevX = e.getX();
int prevY = e.getY();
prevX -= zombie.getX();
prevY -= zombie.getY();
if((prevX > 0 && prevX < Settings.DEFAULT_SIZE) &&
(prevY > 0 && prevY < Settings.DEFAULT_SIZE)) {
//System.out.println("Got Zombie.");
Random r = new Random();
zombie.setX(r.nextInt(view.getWidth() - Settings.DEFAULT_SIZE));
zombie.setY(r.nextInt(view.getHeight() - Settings.DEFAULT_SIZE));
++count;
}
}
public int getCount() {
return count;
}
//mouse events
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void update(Graphics g) {
zombie.update(g);
}
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
public class View implements ActionListener {
private JFrame frame;
Controller controller;
public static void main(String[] args) {
Zombie zombie = new Zombie(Settings.WIDTH/2, Settings.HEIGHT/2, Settings.ZOMBIE_IMAGE);
View view = new View();
Controller myController = new Controller();
myController.addZombie(zombie);
myController.addView(view);
view.addController(myController);
new Timer(500, view).start();
}
private class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
controller.update(g);
revalidate();
}
}
private MyPanel panel;
View() {
//System.out.println("View()");
frame = new JFrame("Catch The Zombie");
// Create a panel to contain a label, a text box, and a button
panel = new MyPanel();
frame.add(panel);
frame.setSize(Settings.WIDTH, Settings.HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
// TODO Auto-generated method stub
System.out.println("Zombie was caught " + controller.getCount() + "times");
}
});
}
public void revalidate() {
}
public void addController(Controller controller){
//System.out.println("View : adding controller");
this.controller = controller;
frame.getContentPane().addMouseListener((MouseListener) controller);
}
public int getWidth() {
return frame.getWidth();
}
public int getHeight() {
return frame.getHeight();
}
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}

Mouse listener not working with JPanel

The paintcomponent works fine, the image shows up, no problems on that end or with the JFrame. I want to implement zooming and panning but not getting any luck as the added mouse listener isn't responding.
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class map extends JPanel {
public int moz = 100;
public void map()
{
addMouseListener(
new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
moz = moz +100;
repaint();
}
}
);
}
public void paintComponent(Graphics g){
.....
g.drawLine( 0, moz, 100, 0 );
}
}
Your class doesn't have a real constructor but rather has a "pseudo" constructor since it has a return type -- yes void counts. So get rid of the void return type by changing:
// this is not a constructor
public void map()
to:
// this is a real constructor
public map()
Also as a side recommendation, change your variable and class names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.
So in your case you'd name your class Map, and in playing with the code could have something like:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Map extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Color DRAW_RECT_COLOR = new Color(200, 200, 255);
public static final Stroke IMAGE_STROKE = new BasicStroke(3f);
public static final Color IMAGE_COLOR = Color.RED;
private BufferedImage image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
private Rectangle drawRectangle = null;
private List<Color> colors = new ArrayList<>();
private Random random = new Random();
public Map() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
for (int r = 0; r < 4; r++) {
int r1 = (r * 255) / 3;
for (int g = 0; g < 4; g++) {
int g1 = (g * 255) / 3;
for (int b = 0; b < 4; b++) {
int b1 = (b * 255) / 3;
colors.add(new Color(r1, g1, b1));
}
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D) g;
if (drawRectangle != null) {
g.setColor(DRAW_RECT_COLOR);
g2.draw(drawRectangle);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Point p1 = null;
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
if (p1 == null) {
return;
}
Point p2 = e.getPoint();
drawRectangle = createDrawRect(p2);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
Rectangle rectangle = createDrawRect(e.getPoint());
Graphics2D g2 = image.createGraphics();
g2.setStroke(IMAGE_STROKE);
Color c = colors.get(random.nextInt(colors.size()));
g2.setColor(c);
g2.draw(rectangle);
g2.dispose();
p1 = null;
drawRectangle = null;
repaint();
}
private Rectangle createDrawRect(Point p2) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
return new Rectangle(x, y, w, h);
}
}
private static void createAndShowGui() {
Map mainPanel = new Map();
JFrame frame = new JFrame("Map");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to create a Graphics object to draw shapes on JFrame

I want to make a program to animate a projectile (a ball flying in a projectile in 2D). In main I call a Shoot() function whose argument is a Graphics object, but I don't know how to create the object so that it draws on my JFrame object. Please help me.
import java.lang.Math;
import java.applet.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Projectile extends JPanel{
public static int ScreenH=1500;
public static int ScreenW=3000;
public static int Xcor=0;
public static int Ycor=0;
public static int ballRadius=20;
public static int prevXcor = 0;
public static int prevYcor = 0;
public static int newXcor = 0;
public static int newYcor = 0;
public static int Time = 0;
public static int Angle = 45;
public static int Velocity = 10;
public static double Acceleration = 9.8;
public static void InitGraphics(){
JFrame jframe = new JFrame();
jframe.setTitle("Projectile");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(ScreenW, ScreenH);
jframe.setResizable(false);
jframe.setVisible(true);
jframe.add(new Projectile());
}
public static void drawCenteredCircle(Graphics g, int x, int y) {
int a = x;
int b = 1000 - y;
g.fillOval(a,b, ballRadius, ballRadius);
}
public static void move() throws InterruptedException {
Thread.sleep(20);
Time += 20;
double XVelocity = Math.sin(Velocity);
double YVelocity = Math.cos(Velocity);
int X = (int) (XVelocity*Time);
int Y = (int) ((YVelocity*Time) + (0.5*Acceleration*Time*Time));
newXcor = X;
newYcor = Y;
}
public static void repaint(Graphics g) {
g.setColor(Color.white);
drawCenteredCircle(g, prevXcor, prevYcor);
g.setColor(Color.red);
drawCenteredCircle(g, newXcor, newYcor);
prevXcor = newXcor;
prevYcor = newYcor;
}
public static void Shoot(Graphics g) throws InterruptedException {
while ( (newXcor < (ScreenW - (4*ballRadius))) && (newYcor < (ScreenH - (4*ballRadius)))) {
move();
repaint(g);
}
}
public static void main(String[]args) {
InitGraphics();
Shoot();
}
}
The JFrame is just the window, you need to add a JComponent to it. JComponents contain a protected void paintComponent(Graphics g) method which you need to override like this:
JFrame frame = new JFrame();
JComponent canvas = new JComponent() {
protected void paintComponent(Graphics g) {
//call repaint(g) here instead of this
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
};
};
frame.add(canvas);
You will probably have to clear the background in repaint

Java catch the ball Game

I am having trouble with my Java project for school.
The plan was to make a simple game where you need to catch the ball and if you catch the ball you will get points.
At the moment I have 2 problems:
I have no idea how I make the balls appear at a random width and make it stay at that width (cause random value is constantly changing ).
How can I make a statement that checks if the catcher caught the ball?
This is my current code:
import instruct.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.Timer;
public class opdracht extends WindowPanel implements MouseMotionListener {
List<comet> comets;
Image afb1;
Image afb2;
Image comet;
int xmuis;
int score;
int random;
int h;
int plaats;
static int randomNum;
private static final int D_W = 700;
private static final int X_INC = 10;
public opdracht() throws IOException {
score = 0;
h = -100;
afb1 = ImageIO.read(new File("afb/space.jpg"));
afb2 = ImageIO.read(new File("afb/pipe.png"));
BufferedImage cometbuf = ImageIO.read(new File("afb/comet.png"));
File output = new File("comet.png");
ImageIO.write(cometbuf, "png", output);
comet = ImageIO.read(new File("comet.png"));
addMouseMotionListener(this);
try {
drawcomet();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
plaats = randomNum;
comets = new LinkedList<>();
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Iterator<comet> it = comets.iterator();
while (it.hasNext()) {
comet ball = it.next();
if (ball.h > D_W) {
it.remove();
System.out.println(comets.size());
} else {
ball.h += X_INC;
repaint();
}
}
}
});
timer.start();
}
public void paintComponent(Graphics g) {
g.drawImage(afb1, 0, 0, 1200, 800, this);
g.setColor(Color.yellow);
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("score = " + score, 1020, 30);
for (comet ball : comets) {
ball.drawcomet(g);
}
g.drawImage(afb2, xmuis, 730, 70, 75, this);
}
public static void randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
randomNum = rand.nextInt((max - min) + 1) + min;
System.out.print(randomNum);
}
public void drawcomet() throws InterruptedException {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
comets.add(new comet(comet));
}
}, 0, 2, TimeUnit.SECONDS);
}
public class comet {
protected int h;
Image comet;
public comet(Image image) {
comet = image;
}
public void drawcomet(Graphics g) {
g.drawImage(comet, plaats, h, 75, 50, null);
}
}
public void mouseMoved(MouseEvent e) {
xmuis = e.getX();
repaint();
}
public void mouseDragged(MouseEvent e) {
// do something
}
public static void main(String[] a) throws IOException {
new opdracht().createGUI();
}
}
package instruct;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class WindowPanel extends JPanel {
JFrame frame;
public WindowPanel() {
this.setPreferredSize(new Dimension(1200, 800));
this.setFocusable(true);
this.requestFocusInWindow();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// System.out.println( "class: "+ getClass().getName() );
frame.setTitle("Space Game");
}
protected void createAndShowGUI() {
frame = new JFrame();
frame.setSize(1200, 800);
frame.setLocation(300, 100);
frame.setResizable(false);
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
// Create a new blank cursor.
Cursor blankCursor =
Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
"blank cursor");
// Set the blank cursor to the JFrame.
frame.getContentPane().setCursor(blankCursor);
}
public void createGUI() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public JFrame getFrame() {
return frame;
}
}
First question: "I have no idea how i make the ball's appear at a random width."
I assume you want to give the ball (= an instance of the comet class) a random x position (= the plaats field)? You could make the following changes (which make the randomNum field no longer required, this could now be a local variable):
//plaats = randomNum;
plaats = randInt(0, 1200);
// more code...
//public static void randInt(int min, int max) {
public static int randInt(int min, int max) {
// more code...
return randomNum;
}
Second question: "And how can make a statement that checks if catcher cached ball."
To determine whether the ball is catched, you could compare xmuis to plaats when the y coordinate of the ball (the h field?) is equal to the top of the pipe (around 730).

Categories