This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I was trying to draw a simple rectangular on a JFrame but when I tried to draw it it gave me a NullPointerException. I could not find the problem because it is one of my codes that I already used. The object that is Null is a Graphics object that I got from the super class. Can someone help me with this?
Error:
Exception in thread "Thread-2" java.lang.NullPointerException
at com.daansander.game.Game.render(Game.java:83)
at com.daansander.game.Game.run(Game.java:76)
at java.lang.Thread.run(Thread.java:745)
Full Code:
package com.daansander.game;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
/**
* Created by Daan on 12-9-2015.
*/
public class Game extends Canvas implements Runnable {
public static final int WIDTH = 500;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 2;
public static final String NAME = "2DGame";
private JFrame frame;
private volatile boolean running;
public Game() {
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game().start();
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
}
#Override
public void run() {
long lastTime = System.currentTimeMillis();
long current;
long delta = 0;
int frames = 0;
// int ticks = 0;
while (running) {
current = System.currentTimeMillis();
delta += current - lastTime;
lastTime = current;
frames++;
if (delta > 1000) {
delta -= 1000;
System.out.println("FRAMES " + frames);
frames = 0;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
render();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
Graphics g = bs.getDrawGraphics(); // <----- Line of error
// g.setColor(Color.black);
// g.drawRect(0, 0, 5, 5);
//
// g.dispose();
// bs.show();
}
public void tick() {
}
public void init() {
}
}
getBufferStrategy() is returning null. As fabian linked to above:
public BufferStrategy getBufferStrategy()
Returns the BufferStrategy used by this component. This method will return null if a BufferStrategy has not yet been created or has been disposed.
You need to create a BufferStrategy first.
Related
If I create a window with JFrame, several rows of pixels along the bottom and several columns along the right hand side are outside the window that is created so they don't show up. For example when I create a 800x600 window, the window will only show stuff in the top left 786x563 area. The amount that gets cut off also seems to vary with the size of the window. So far I've just manually adjusted the size and position of things. Currently in my code is set up like this:
import java.awt.*; //Canvas and Dimension
import java.util.*;
import javax.swing.JFrame;
import java.awt.image.BufferStrategy;
import java.awt.event.*;
public class Main extends Canvas implements Runnable {
static final int WIDTH = 800, HEIGHT = WIDTH/4*3; //800, 600
private Thread thread;
private boolean running = false;
public Main() { //constructor
new Window(WIDTH, HEIGHT, "Game", this);
requestFocus();
}
public synchronized void start() {
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop() {
try {
thread.join();
running = false;
}
catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 /amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames =0;
while(running) {
long now = System.nanoTime();
delta+= (now - lastTime) / ns;
lastTime = now;
while(delta>=1) {
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer+=1000;
frames = 0;
}
}
stop();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs==null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//creates a line that should be 38 units above the bottom but instead is right along the bottom
g.setColor(Color.GREEN);
g.fillRect(1, 562, 30, 1);
g.dispose();
bs.show();
try{Thread.sleep(5);} catch(Exception e) {}
}
public void tick() {
}
public static void main(String args[]) {
new Main();
}
}
class Window extends Canvas {
public Window(int w, int h, String t, Main game) {
JFrame frame = new JFrame(t);
frame.setPreferredSize(new Dimension(w,h));
frame.setMinimumSize(new Dimension(w,h));
frame.setMaximumSize(new Dimension(w,h));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
game.start();
}
}
If I didn't include enough of my code to diagnose the problem please tell me so I can put the rest of it.
I'm learning to make games using a a tutorial on youtube. Everything seems fine except when I run the program. A frame shows up with the accurate width I want but the height looks like it sets to a default no matter what value I give it.
package ca.vanzeben.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int Height = WIDTH/ 12*9;
public static final int SCALE = 3; // able to move screen
public static final String NAME = "Juego";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game() { //game constructor
setMinimumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes game completely
frame.setLayout(new BorderLayout());
frame.add(this,BorderLayout.CENTER); //adds canvas to JFrame and centers it
frame.pack();//keeps everything sized correctly
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {//so u can start from the applet
running = true;
new Thread(this).start();
}
public synchronized void stop(){
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000.0/60; //nanoseconds per tick or per update
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0.0; //how many unprocessed nano seconds
while(running){
long now = System.nanoTime();
delta+=(now-lastTime)/nsPerTick;
lastTime = now;
boolean shouldRender = true;
while(delta>=1){
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try{
Thread.sleep(2);
}catch(InterruptedException e){
e.printStackTrace();
}
if(shouldRender){
frames++;
render();
}
if(System.currentTimeMillis()-lastTimer>=1000){
lastTimer += 1000;
System.out.println(frames + " frames " + ticks + " ticks ");
frames = 0;
ticks = 0;
}
}
}
public void tick(){ //updates the game, updates the logic
tickCount++;
for(int i =0;i<pixels.length;i++){
pixels[i] = i + tickCount;
}
}
public void render(){ //prints out ^
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.setColor(Color.BLACK);
g.drawRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args){
new Game().start();
}
}
You defined Height and used HEIGHT. Change it to:
public static final int HEIGHT = WIDTH / 12 * 9;
This is how it looked like to me:
Before:
After:
So, first of all this is my first time posting and I am trying to make a top-down game with java(1.8) and IntelliJ, nothing else. I have all of my code good and done(for making the sprite show up), I test it and it keeps giving me error messages saying that certain parts are invalid. It is supposed to display an image (character) on the screen in the top right here is all code and please keep in mind that I do not have this fully finished:
Game.java
package main;
import main$entities.Player;
import main$gfx.ImageLoader;
import main$gfx.SpriteSheet;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.lang.*;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 700, HEIGHT = 400, SCALE = 1;
public static boolean running = false;
public Thread gameThread;
private BufferedImage spriteSheet;
private Player player;
public void init(){
ImageLoader loader = new ImageLoader();
spriteSheet = loader.load("./spritesheet.png");
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = new Player(0, 0, ss);
}
public synchronized void start(){
if(running)return;
running = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop(){
if(!running)return;
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {e.printStackTrace();}
}
public void run(){
long lastTime = System.nanoTime();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1){
tick();
delta--;
}
render();
}
stop();
}
public void tick(){
player.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// Render Here
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
player.render(g);
// End Render
g.dispose();
bs.show();
}
public static void main(String[] args){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame("Tile RPG");
frame.setSize(WIDTH *SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.setVisible(true);
game.start();
}
}
ImageLoader.java
package main$gfx;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class ImageLoader {
public BufferedImage load(String path){
try {
return ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
SpriteSheet.java
package main$gfx;
import java.awt.image.BufferedImage;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(BufferedImage sheet){
this.sheet = sheet;
}
public BufferedImage crop(int col, int row, int w, int h){
return sheet.getSubimage(col * 16, row * 16, w, h);
}
}
Player.java
package main$entities;
import main.Game;
import main$gfx.SpriteSheet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener{
private int x, y;
private SpriteSheet ss;
private boolean up = false, dn = false, lt = false, rt = false;
private final int SPEED = 3;
public Player(int x, int y, SpriteSheet ss){
this.x = x;
this.y = y;
this.ss = ss;
}
public void tick(){
if(up){
y -= SPEED;
}
if(dn){
y += SPEED;
}
if(lt){
x -= SPEED;
}
if(rt){
x += SPEED;
}
}
public void render(Graphics g){
g.drawImage(ss.crop(0 ,0, 16, 16), x, y, 16 * Game.SCALE, 16 * Game.SCALE, null);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
The error messages(It gives me multiple messages, each time is different // = what is on that line, so you don't have to find it by counting, your welcome):
First time I run the Game.java:
Exception in thread "Thread-2" java.lang.NullPointerException
at main.Game.tick(Game.java:64) // player.tick();
at main.Game.run(Game.java:56) // tick();
at java.lang.Thread.run(Thread.java:745) // this is in the JDK itself
Process finished with exit code 0
Second(and all that proceed) time I run the Game.java:
Exception in thread "Thread-2" java.lang.NullPointerException
at main.Game.render(Game.java:77) // player.render(g);
at main.Game.run(Game.java:59) // render();
at java.lang.Thread.run(Thread.java:745) // this is in the JDK itself
Process finished with exit code 0
That game.start(); takes all the responsibility. Your Game class is not extending a Thread, the thread itself will start automatically right after you instantiate your game's class, since the thread is created inside the game class.
So remove :
game.start();
Btw you fall on trap :
public static final int WIDTH = 700, HEIGHT = 400;
won't work, because those fields hide another fields, why? because
WIDTH & HEIGHT is preserved arguments for
.fillRect(...);
It's because you never call the init() method and, therefore the player and the spriteheet never gets created
You can add a constructor to the Game class like this:
public Game() {
init();
}
Or you can add the following line in the main method:
public static void main(String[] args){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame("Tile RPG");
frame.setSize(WIDTH *SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.setVisible(true);
// Add this line
game.init();
game.start();
}
}
But I prefer the first way
Hi i was coding and this came up
Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at spoderman.game.Main.render(Main.java:79)
at spoderman.game.Main.run(Main.java:64)
at java.lang.Thread.run(Unknown Source)
Here is the Code
i pinpointed the error which was createBufferStrategy(3);
Please Help!!!
package spoderman.game;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = 8496269517740959648L;
public static JFrame frame = new JFrame();
public static Thread gameThread = new Thread();
public static final int WIDTH = 720, HEIGHT = 240, SCALE = 2;
public static String title = "The Adventures of Spoderman";
public static boolean isrunning = false;
public synchronized void start(){
if(isrunning)return;
isrunning = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop(){
if(!isrunning)return;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
isrunning = false;
}
public void run() {
long lastTime = System.currentTimeMillis();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(isrunning){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1){
tick();
delta--;
}
render();
}
stop();
}
public void tick(){
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//ALL THAT IS RENDERED
g.fillRect(0, 0, WIDTH, HEIGHT);
//ALL THAT IS RENDERED
g.dispose();
bs.show();
}
public static void main (String [] args){
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.start();
JFrame();
}
public static void JFrame(){
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Try this on the Jframe
public static void JFrame(Main main) {// <---get de arg game.
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
edit on the main
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame(main);// get the Frame working and pas the main
main.start();// start main
}
and last just change the size
// g.fillRect(0, 0, WIDTH, HEIGHT);//The old one
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);// change the size
full code
package testCodeDel;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable {
private static final long serialVersionUID = 8496269517740959648L;
public static JFrame frame = new JFrame();
public static Thread gameThread = new Thread();
public static final int WIDTH = 720, HEIGHT = 240, SCALE = 2;
public static String title = "The Adventures of Spoderman";
public static boolean isrunning = false;
public synchronized void start() {
if (isrunning)
return;
isrunning = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop() {
if (!isrunning)
return;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
isrunning = false;
}
public void run() {
long lastTime = System.currentTimeMillis();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while (isrunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta >= 1) {
tick();
delta--;
}
render();
}
stop();
}
public void tick() {
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// ALL THAT IS RENDERED
// g.fillRect(0, 0, WIDTH, HEIGHT);//The old one
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);// change the size
// ALL THAT IS RENDERED
g.dispose();
bs.show();
}
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame(main);// get the Frame working pas de main
main.start();// start main
}
public static void JFrame(Main main) {// <---get de arg main.
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Or just delete JFrame() and do this on your main
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
//JFrame(main);// get the Frame working pas de main
JFrame frame = new JFrame();
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
main.start();// start main
}
I've been trying to get this rectangle to move that I've created using a for loop. All that's happening with this code is that there is an original rectangle and then a new one next to that rectangle. No animation happens, only those two rectangles show on the window. What are some methods to get this rectangle to animate?
import java.awt.*;
import javax.swing.*;
public class Gunman extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect (x, y, width, height);
g.fillRect (x, y, width, height);
for(int i = 0; i<=1024; i++){
g.setColor(Color.red);
g.drawRect(x++, y, width, height);
g.fillRect(x++, y, width, height);
}
}
}
Don't have program logic in a paint or paintComponent method, and by logic, I mean the for loop with "motion" as that just won't work. You want to
Almost never draw in a JComponent's paint method but rather in its paintComponent method.
Don't forget to call the super.paintComponent(g) method too, often as the first method call in the paintComponent(g) override.
Use a Swing Timer to step wise change the x and y values
call repaint() on the JComponent after the changes are made
For example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 900;
private static final int PREF_H = 700;
private static final int TIMER_DELAY = 30;
public int rectX = 10;
public int rectY = 10;
public int width = 8;
public int height = 10;
public Gunman() {
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent actEvt) {
if (rectX < PREF_W && rectY < PREF_H) {
rectX++;
rectY++;
repaint();
} else {
((Timer)actEvt.getSource()).stop();
}
}
}).start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(rectX, rectY, width, height);
g.fillRect(rectX, rectY, width, height);
}
public int getRectX() {
return rectX;
}
public void setRectX(int rectX) {
this.rectX = rectX;
}
public int getRectY() {
return rectY;
}
public void setRectY(int rectY) {
this.rectY = rectY;
}
private static void createAndShowGui() {
Gunman mainPanel = new Gunman();
JFrame frame = new JFrame("Gunman");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
There are numerous ways to animate. Here is another example. Notice the location of repaint() inside a background thread. This paints directly on a JFrame. Use paintComponent() when painting on JPanels.
public static void main(String args[]) throws Exception {
new JFrame("Draw a red box") {
Point pointStart = new Point(50,50);
Point pointEnd = new Point(200,200);
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.RED);
g.drawRect(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}}{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(300, 300);
setLocation(300, 300);
setVisible(true);
Thread t = new Thread(new Runnable() {
public void run() {
while (pointEnd.x > 0 && pointEnd.y > 0) {
pointEnd = new Point(--pointEnd.x, --pointEnd.y);
repaint();
try {
Thread.sleep(22);
} catch (InterruptedException e) {
e.printStackTrace();
}}
pointStart = null;
pointEnd = null;
}});
t.setDaemon(true);
t.start();
}};}
UPDATE: Ok previous answer was not so good from the old memory, here is the quickest, cheapest, most dirty way to get some animation quicksmart, you can copy and compile the code as is:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Test extends JFrame {
public Gunman g = new Gunman();
public static void main( String[] args ) {
Test t = new Test();
t.setSize( 800, 600 );
t.setVisible( true );
t.getContentPane().add( t.g );
while ( true ) {
t.g.x = t.g.x + 1;
t.g.y = t.g.y + 1;
t.repaint();
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
}
}
}
public void paintComponent( Graphics g ) {
g.clearRect( 0, 0, 800, 600 );
}
}
class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paintComponent( Graphics g ) {
g.setColor( Color.red );
g.fillRect( x, y, width, height );
}
}
There are ALOT of shortcuts in this, as Hovercraft of Eels has said, this is not an 'ideal' way to do it, but it has the basic structure. You have a canvas (I have used the JFrame, again not really recommended), and you add a component to it. You must override paintComponent (if you are using swing, which I do recommend you do), and this will draw your component.
You then need to alter your component's position in some way (recommend a proper method call on the object that does this), and ask the canvas to repaint itself.
I have included the wait so you can see what's happening, but if you are thinking of game programming, you should look into creating a game loop to manage this, I recommend Killer game programming in java, you can get a free ebook version with a quick google search.