How to create a Graphics object to draw shapes on JFrame - java

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

Related

Adding an array of JComponent extended objects to a JFrame

I'm begining with JFrame, I'm triying to make a StarField, for the moment I'm adding the Star JComponent to the Starfield JFrame:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Star extends JComponent{
public int x;
public int y;
private final Color color = Color.YELLOW;
public Star(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 8, 8);
}
}
and the StarField code:
import javax.swing.*;
public class StarField extends JFrame{
public int size = 400;
public Star[] stars = new Star[50];
public static void main(String[] args) {
StarField field = new StarField();
field.setVisible(true);
}
public StarField() {
this.setSize(size, size);
for (int i= 0; i< stars.length; i++) {
int x = (int)(Math.random()*size);
int y = (int)(Math.random()*size);
stars[i] = new Star(x,y);
this.add(stars[i]);
}
}
}
The problem it's thar it only print one star, I think it is the last one, the coords are working like they are supposed to do it, so I think the mistake is in the JComponent or JFrame implementation, I'm self-learning, so maybe my code isn't the correct way for using swing.
Thank you, and sorry for my english, I'd tried to write it the best I know.
In your case you cannot use a layout manager, and need to reset it to null. See the my code below
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class StarField extends JFrame {
public int size = 400;
public Star[] stars = new Star[50];
public static void main(String[] args) {
StarField field = new StarField();
field.setVisible(true);
}
public StarField() {
this.setSize(size, size);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// usually you should use a normal layout manager, but for your task we need null
getContentPane().setLayout(null);
for (int i = 0; i < stars.length; i++) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
stars[i] = new Star(x, y);
this.add(stars[i]);
}
}
public class Star extends JComponent {
private final Color color = Color.YELLOW;
public Star(int x, int y) {
// need to set the correct coordinates
setBounds(x, y, 8, 8);
}
#Override
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(0, 0, getWidth(), getHeight());
}
}
}

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();
}
});
}
}

Error when using java packages

I am writing a game. Its directory tree is basically like this:
ShootGame------>game----------------------->input--------------------------------->InputHandler.class
|-->ShooterGame.class | |-->InputHandler.java
|-->ShooterGame.java |---->player-------------->Player.class
| |-->Player.java
|---->scenario---
|-->Block.class
|-->Block.java
I hope you understand my diagram, but the point is: the "game" folder has 3 folders inside it, "input","player","scenario".
Inside "InputHandler.java", I have declared package game.input.
Inside "Player.java", I have declared package game.player.
And inside "Block.java", I have declared package game.scenario.
So far, so good.
But when, in the Player.java, i do import game.input.InputHandler, it says "package game.input does not exist", even though I have already declared "game.input".
What have I done wrong here? If you need the codes inside the files, please leave a comment. I am not posting them here because I think the main problem I have is the package and import logic.
Thanks.
Edit:
Code
InputHandler.java
package game.input;
import java.awt.Component;
import java.awt.event.*;
public class InputHandler implements KeyListener{
static boolean[] keys = new boolean[256];
public InputHandler(Component c){
c.addKeyListener(this);
}
public boolean isKeyDown(int keyCode){
if (keyCode > 0 && keyCode < 256){
return keys[keyCode];
}
return false;
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() > 0 && e.getKeyCode() < 256){
keys[e.getKeyCode()] = true;
}
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() > 0 && e.getKeyCode() < 256){
keys[e.getKeyCode()] = false;
}
}
public void keyTyped(KeyEvent e){}
}
Player.java
package game.player;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.net.URL;
import java.awt.event.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import game.input.InputHandler;
public class Player{
private BufferedImage sprite;
public int x, y, width, height;
private final double speed = 5.0d;
public Player(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
try{
URL url = this.getClass().getResource("ship.png");
sprite = ImageIO.read(url);
} catch(IOException e){}
}
public void keyPlayer(double delta, InputHandler i){
if(i.isKeyDown(KeyEvent.VK_D)){
if(this.x>=1240) return;
else this.x+=speed*delta;
}
if(i.isKeyDown(KeyEvent.VK_A)){
if(this.x<=0) return;
else this.x-=speed*delta;
}
}
public void update(InputHandler inputP){
keyPlayer(1.7, inputP);
}
public void Draw(Graphics a){
a.drawImage(sprite,x,y,width,height,null);
}
public Rectangle getBounds(){
return new Rectangle(x,y,width,height);
}
}
Block.java
package game.scenario;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.net.URL;
import java.awt.event.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.Timer;
import java.util.TimerTask;
public class Block{
private Timer timer;
private BufferedImage sprite;
private final int t = 1;
public int x, y, width, height;
public Block(int x, int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
try{
URL url = this.getClass().getResource("meteor.png");
sprite = ImageIO.read(url);
} catch(IOException e){}
}
public void Draw(Graphics g){
g.drawImage(sprite,x,y,width,height,null);
}
public boolean destroy(Block b){
if(b.y>=630){
b = null;
timer.cancel();
timer.purge();
return true;
} else { return false; }
}
public void update(int sec){
//if(getBounds().intersects(ShooterGame.ShooterGameClass.player.getBounds())){ System.out.println("Collision detected!"); }
timer = new Timer();
timer.schedule(new Move(), sec*1000);
destroy(this);
}
class Move extends TimerTask{
public void run(){
int keeper = 5;
if(keeper>0){
y+=5;
}
}
}
public Rectangle getBounds(){
return new Rectangle(x,y,width,height);
}
}
The main class(The game start)
ShooterGame.java:
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.*;
import java.net.URL;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.event.MouseEvent;
import game.input.InputHandler;
import game.player.Player;
import game.scenario.Block;
public class ShooterGame extends JFrame{
static int playerX=500;
static int playerY=520;
InputHandler input = new InputHandler(this);
public static Player player = new Player(playerX,playerY,50,50);
Block meteor = new Block(100,100,30,30);
public static void main(String[] args){
ShooterGame game = new ShooterGame();
game.run();
System.exit(0);
}
static int windowWidth = 1300;
static int windowHeight = 600;
static int fps = 30;
static BufferedImage backBuffer = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
public void run(){
boolean running = true;
initialize();
while(running){
long time = System.currentTimeMillis();
update();
draw();
time = (1000 / fps) - (System.currentTimeMillis() - time);
if (time > 0) {
try{
Thread.sleep(time);
}
catch(Exception e){};
};
}
}
public void initialize(){
setTitle("--- Shooter Game ---");
setSize(windowWidth, windowHeight);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void update(){
player.update(input);
meteor.update(0);
}
public void draw(){
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.BLACK);
bbg.fillRect(0, 0, windowWidth, windowHeight);
player.Draw(bbg);
meteor.Draw(bbg);
g.drawImage(backBuffer, 0, 0, this);
}
}
Commands:
compiling Player, Block and InputHandler(javac file.java)
then run the game with _java ShooterGame
You are probably trying to compile from inside the directory that the file is in, which is incorrectly setting the classpath.
cd game/player
javac Player.java
Instead of going into the subpackages, set the classpath explicitly and compile from the top level. I'm assuming that ShooterGame.java is in your game folder:
cd path/to/project/ShootGame
javac -cp . game/player/Player.java
... compile other classes
java -cp . game.ShooterGame

Simple Java game draws only half window

I can not figure out why the game is only drawing only on half the window I make.
I add in actionPerformed to always implement to y position and it goes only on half the window , then the images stopes.
Main
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Main extends JFrame{
public static void main(String[]args){
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame ex = new Main();
ex.setVisible(true);
}
});
}
public Main(){
setTitle("Maze");
add(new Game());
pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Game
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener {
private final int GWIDTH = 400;
private final int GHEIGHT = 400;
private int GAME_DELAY = 10;
private Timer timer;
private Image player;
/*Player*/
private final int spawnPosition = 0;
int playerX = 0;
int playerY = spawnPosition;
/*Mouse*/
private Mouse m;
public Game(){
setFocusable(true);
setPreferredSize(new Dimension(GWIDTH, GHEIGHT));
addMouseListener(new Mouse());
initTime();
//Importam poza
loadPlayer();
//Mouse
m = new Mouse();
}
private void initTime(){
timer = new Timer(GAME_DELAY, this);
timer.start();
}
private void loadPlayer(){
ImageIcon img = new ImageIcon("smiley.png");
player = img.getImage();
}
public int getX(){ return playerX; }
public int getY() { return playerY; }
private void drawPlayer(Graphics2D g2d){
g2d.drawImage(player,getX(),getY(),null);
Toolkit.getDefaultToolkit().sync();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawPlayer(g2d);
g2d.dispose();
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
playerY += 1;
repaint();
}
}
Image

adding background pic to JFrame

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);
}
}

Categories