I tried to find a question that answers my problem but could not find any since the questions asked are about that repaint() is never called
My problem is that when i start the application it either works without problems, or that only paintComponent() is not called (there are no errors)
My code:
GamePanel.java:
public class GamePanel extends JPanel implements KeyListener, ActionListener {
private static final long serialVersionUID = 1819637299730865623L;
private Timer time;
private long oldTime;
private int Width;
private int Height;
public GamePanel(int Width, int Height) {
this.Width = Width;
this.Height = Height;
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(true);
oldTime = System.nanoTime();
setup();
System.console().printf("Begin!");
time = new Timer(0,this);
time.start();
}
#Override
public void actionPerformed(ActionEvent e) {
update(((float)(System.nanoTime() - oldTime)) / (float)1000000000);
System.console().printf("Running!");
oldTime = System.nanoTime();
repaint();
time.start();
}
float x = 0;
float del;
#Override
public void paintComponent(Graphics g) {
System.console().printf("Drawing!");
g.setColor(new Color(0,0,0));
g.fillRect(0, 0, Width, Height);
g.setColor(new Color(0,0,255));
g.fillOval((int)x-40,60,80,80);
g.setColor(new Color(255,255,255));
g.drawString(Float.toString(1 / del), Width / 2, Height / 2);
g.dispose();
}
public void update(float delta) {
x += delta * 50;
del = delta;
}
public void setup() {
}
Renderer.java (this is created in the main function)
public class Renderer {
int Height, Width;
JFrame obj;
GamePanel pan;
public Renderer(int Width, int Height, int StartposX, int StartposY, String title) {
obj = new JFrame();
this.Height = Height;
this.Width = Width;
obj.setBounds(StartposX,StartposY,Width,Height);
obj.setTitle(title);
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pan = new GamePanel(Width,Height);
obj.add(pan);
}
}
To fix the problem all that one has to do is:
remove
g.dispose();
add
super.paintComponent(g);
at paintComponent()
and add
obj.setVisible(true);
after obj.add(pan);
I run your whole code adding a main() method in the Renderer.java to be able to test it.
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Renderer(300, 300, 10, 10, "Testing Renderer");
}
});
}
You code program runs fine if I removed all the System.console().printf codes.
Related
I am building the test application to improve later. I have a Java Graphic Element drawn on a canvas using a Game Loop (update,render). It is a red ball that changes its color when the mouse is placed on top of it.
I am trying to figure out a method to create a JPanel when the mouse is on top of the ball,to show some sort of "Hidden Information" inside the ball. My original idea is to display a histogram made with JFreeChart API as the "Hiden information, so I believe that if I create this JPanel I can later add the histogram to the JPanel created. Similar to this http://www.bitjuice.com.au/research/#hierarchicalclassificationexample. In the link, whenever you put the mouse on top of the rectangles, you display extra information.
So far I've got this code:
*Window.java * (The JFrame)
public class Window extends JFrame {
JLabel title_label = new JLabel();
public Window(int width, int height, String title, Animation animation){
setTitle(title);
setPreferredSize(new Dimension(width,height));
setMaximumSize(new Dimension(width,height));
setMinimumSize(new Dimension(width,height));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
add(animation);
add(title_label, BorderLayout.SOUTH);
setVisible(true);
animation.start();
}
public void update(){
title_label.setText(Animation.mouseX + " " + Animation.mouseY);
}
}
Animation.java(The game Loop)
public class Animation extends Canvas implements Runnable {
public static final int WIDTH = 1024, HEIGHT = WIDTH/12*9 ;
private Thread thread;
private boolean running = false;
public static int mouseX,mouseY;
public Window window;
Button button = new Button();
public Animation(){
window = new Window(WIDTH, HEIGHT,"Test", this);
addMouseMotionListener(new Handler(window));
addMouseListener(new Handler(window));
}
public void run() {
this.requestFocus();
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){
update();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer >1000){
//System.out.println(frames);
timer += 1000;
frames = 0;
}
}
stop();
}
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 static int getMouseX(){
return mouseX;
}
public static int getMouseY(){
return mouseY;
}
public static void setMouseX(int x){
mouseX = x;
}
public static void setMouseY(int y){
mouseY = y;
}
private void update(){
window.update();
button.update();
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(4);
return;
}
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(rh);
g2d.setColor(Color.white);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
button.render(g);
g.dispose();
g2d.dispose();
bs.show();
}
public static void main(String args[]){
new Animation();
}
}
Handler.java
public class Handler extends MouseAdapter {
int x,y;
private Window window;
public Handler(Window window){
this.window = window;
}
public void mouseMoved(MouseEvent e){
Animation.setMouseX(e.getX());
Animation.setMouseY(e.getY());
}
}
Button.java
public class Button {
Ellipse2D mask;
boolean mouseIsOn = false;
public Button(){
mask = new Ellipse2D.Double(500,350,50,50);
}
public void update(){
if(mask.contains(Animation.mouseX,Animation.mouseY)){
mouseIsOn = true;
}else
mouseIsOn = false;
}
public void render(Graphics g){
if(mouseIsOn)
g.setColor(Color.green);
else
g.setColor(Color.red);
g.fillOval(500,350, 50, 50);
}
}
I appreciate the help.
Heavy weight and light weight components don't mix. JPanel is a lightweight component and Canvas is heavyweight. Heavyweight components always get drawn on top of lightweight ones.
What you may want to do instead is just draw the mouseover portion directly to your canvas. You can use FontMetrics for drawing Strings if that is what you need.
I have an Issue painting jcomponent
//class where the rectangle should drawed
public class Board extends JComponent
{
private Case[][] cases= new Case[10][10];
public Plateau() {
super();
this.setLayout(new GridLayout(10,10));
this.setSize(getPreferredSize());
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if ((i + j) % 2 == 0) {
cases[i][j] = new WhiteCase(j * Case.LONGUEUR, i * Case.LONGUEUR, Case.LONGUEUR, Case.LONGUEUR);
} else {
cases[i][j] = new BlackCase(j * Case.LONGUEUR, i * Case.LONGUEUR, Case.LONGUEUR, Case.LONGUEUR);
}
add(cases[i][j]);
}
}
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
}
//class Base for rectangle
public abstract class Case extends JComponent {
protected static final int LONGUEUR=60;
protected int x,y,width,height;
protected abstract void paintComponent(Graphics g);
public Dimension getPreferredSize() { return new Dimension(LONGUEUR, LONGUEUR);
}
}
///black Case
public class BlackCase extends Case
{
private Piece piece;
private static final long serialVersionUID = 1L;
public CaseNoire(int x, int y,int width,int height)
{
this.x=x;
this.y=y;
this.width = width;
this.height= height;
}
public Dimension getPreferredSize() {
return new Dimension(LONGUEUR, LONGUEUR);
}
#Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.darkGray);
g.fillRect(x, y,width,height);
}
}
public class CaseWhite extends Case {
/**
*
*/
private static final long serialVersionUID = 1L;
public CaseBlanche(int x, int y,int width,int height)
{
this.x=x;
this.y=y;
this.width = width;
this.height= height;
}
#Override
public void paintComponent(Graphics g)
{
g.setColor(Color.white);
g.fillRect(x, y,width,height);
g.setColor(Color.BLACK);
g.drawString("X= "+x , 10, 10);
}
public Dimension getPreferredSize() {
return new Dimension(LONGUEUR, LONGUEUR);
}
}
//Main class
public class CheckersGame extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args )
{
CheckersGame checkers= new CheckersGame();
}
public CheckersGame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Jeu de Dames");
JPanel panelPrincipalDame = new JPanel(new GridBagLayout());
Board board = new Board();
GridBagConstraints c = new GridBagConstraints();
c.fill= GridBagConstraints.NONE;
c.gridx =0;
c.gridy = 0 ;
c.gridheight= 2;
c.gridwidth= 2;
panelPrincipalDame.add(plateau,c);
setSize(800, 700);
setContentPane(panelPrincipalDame);
![//setVisible(true);][1]
setResizable(false);
}
}
The result of this code is ( Note X+ 0 etc.. is just for debug purpose )
But what I want is this
Please why I get only one rectangle?
So much for listening to my suggestion to NOT create "CaseNoire" and "CaseBlanch" classes I gave in your last question: paintComponent does not paint correctly from two weeks ago. These classes are not needed. What happens if you ever want to give the user the flexibility to choose the colors of the squares. Your game logic should never be based on the class name or anything like that. So get rid of the classes and use the built in Swing features to color the background of the component.
I think the problem is because you created variables "x, y, width, height" in the Case class. I believe these variables already defined in the Component class, to represent the size/location of the component.
Get rid of the variables, you don't need to manage the size/location of each component because the GridLayout will do this for you.
Again, look at the example code I gave you that shows how to create a "ChessBoard".
I resolved it I just set the X=0 and Y= 0 in the paintComponent()
protected void paintComponent(Graphics g)
{
g.setColor(Color.darkGray);
g.fillRect(0, 0,width,height);
}
Any ideas why my oval is not moving to the right? I have a game loop but somehow the circle stays where it appears, instead of moving by 2pixels to the right every cycle.
The strange thing is that it enters the loop before actually painting. But then the graphics object show up(at a fixed position).
public class GamePanel extends JPanel implements Runnable {
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private Thread t1;
boolean running;
private int FPS = 60;
private long optimalTime = 1000 / FPS;
private int heroX = 200;
private int heroY = 200;
public void addNotify(){
Dimension size = new Dimension(WIDTH,HEIGHT);
setPreferredSize(size);
setFocusable(true);
requestFocus();
running = true;
t1 = new Thread(this);
t1.start();
}
public void paintComponent (Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, WIDTH, HEIGHT);
g2.setColor(Color.BLACK);
g2.fillOval(heroX, heroY, 50, 50);
g2.dispose();
}
public void run() {
long startTime;
long passedTime;
long waitTime;
while (running){
startTime = System.nanoTime();
System.out.println("Runs");
update();
draw();
repaint();
passedTime = System.nanoTime() - startTime;
waitTime = optimalTime - passedTime / 1000000;
try {
if (waitTime <= 0){
waitTime = 2;
}
Thread.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void draw() {
}
private void update() {
heroX += 2;
}
}
You should use a swing Timer instead of trying to use threads. If you need to do something time consuming in the background, use SwingWorkers. It is possible to use your own threading with swing should you really need to (you need a twisted user case to need to do that), but do not try to do that until you have a good grasp of threads and the way to use them with swing.
public class GamePanel extends JPanel {
private static final int DELAY = 1000 / 60;
private final Timer timer;
// ...
private int heroX = 200;
private int heroY = 200;
public GamePanel() {
timer = new Timer(DELAY, new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
update();
repaint();
}
});
// ...
}
// No need to make this public
#Override
protected void paintComponent (Graphics g) {
// ...
}
#Override
public Dimension getPreferredSize() {
// Overriding is cleaner than using set*Size(). Search old questions to see why
}
public void startAnimation() {
timer.start();
}
public void stopAnimation() {
timer.stop();
}
// Remove addNotify() and run()
}
After reading and testing, I just wanted to do this. It works as intended, even if paintComponent is outside the EDT.
public class GamePanel extends JPanel implements Runnable {
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private int cordX = WIDTH / 2;
private Thread t1;
private boolean running = true;
public void addNotify() {
super.addNotify();
Dimension size = new Dimension (WIDTH, HEIGHT);
setPreferredSize(size);
t1 = new Thread(this);
t1.start();
}
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillOval(cordX, HEIGHT /2 , 20, 20);
}
public void run() {
while(running) {
cordX += 2;
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I'm completely stuck on a problem i'm having with this program where I have to draw a city with swing. Basically what i'm trying to do is make it so that the windows don't change every frame. I've tried just about everything I can think of and nothing has worked yet.
Here is the main class that draws everything
import java.applet.Applet;
import java.awt.*;
import java.util.*;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Skyline extends JFrame implements MouseMotionListener
{
private int mX, mY; //Mouse cooddinates
private Image mImage; //Image buffer
//private Image mImage2; //Image buffer
private int num = 0;
private Building bldg1 = new Building(305, 110, 30);
private Building bldg2 = new Building(380, 125, 170);
private Building bldg3 = new Building(245, 200, 325);
private Building bldg4 = new Building(470, 170, 555);
private Building bldg5 = new Building(395, 200, 755);
private Background bg = new Background();
public void init ()
{
}
public static void main(String []args)
{
Skyline f = new Skyline();
f.setSize(1017, 661); //Sets size of window
f.setTitle("Skyline"); //Sets title of window
f.show();
}
public void paintOffscreen(Graphics page)
{
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200)
num = 0;
page.setColor(Color.yellow);
page.fillRect(num,100,100,100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
//Mouse move square
int s = 100;
page.setColor(Color.yellow);
page.fillRect(mX - s / 2, mY - s / 2, s, s);
repaint();
}
//====================================BUFFER CODE========================================
public void paint(Graphics g)
{
//Clear the buffer
Dimension d = getSize();
checkOffscreenImage();
Graphics offG = mImage.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(mImage.getGraphics());
//Draw the buffer
g.drawImage(mImage, 0, 0, null);
}
private void checkOffscreenImage()
{
Dimension d = getSize();
if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height)
mImage = createImage(d.width, d.height);
}
//=======================================================================================
//==================================MOUSE MOVE CODE======================================
public Skyline()
{
addMouseMotionListener(this);
setVisible(true);
}
public void mouseMoved(MouseEvent me)
{
Graphics g = getGraphics();
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
update(g);
//repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseMoved(me);
}
//=======================================================================================
}
And here is the window class that might be able to be fixed somehow.
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
import javax.swing.JFrame;
public class Windows extends JFrame
{
private Random gen = new Random();
private int height, width, locX;
private int onOff = 0;
public Windows()
{
height = 305;
width = 110;
locX = 30;
}
public Windows(int height, int width, int locX)
{
this.height = height;
this.width= width;
this.locX = locX;
}
public void draw(Graphics page)
{
page.setColor (Color.darkGray);
page.fillRect (locX, 550 - height, width, height);
for (int i = 550 - height + 5; i < 550; i += 15)
{
for (int x = locX + 5; x < locX + width; x += 15)
{
onOff = gen.nextInt(2);
if(onOff == 0)
page.setColor(Color.black);
else
page.setColor(Color.yellow);
page.fillRect (x,i,10,10);
}
}
}
}
Heres the building class just in case.
import java.applet.Applet;
import java.awt.*;
import javax.swing.JFrame;
public class Building extends JFrame
{
private int height, width, locX;
private int onOff;
private Windows windows1;// = new Windows(height, width, locX);
public Building()
{
height = 305;
width = 110;
locX = 30;
windows1 = new Windows(height, width, locX);
}
public Building(int height, int width, int locX)
{
this.width = width;
this.height = height;
this.locX = locX;
windows1 = new Windows(height, width, locX);
}
public void draw(Graphics page)
{
page.setColor (Color.darkGray);
page.fillRect (locX, 550 - height, width, height);
windows1.draw(page);
}
}
And the bg class just to be safe
import java.applet.Applet;
import java.awt.*;
public class Background extends Applet
{
private int height, width;
public Background()
{
height = 400;
width = 2000;
}
public Background(int height, int width)
{
this.height = height;
this.width = width;
}
public void draw(Graphics page)
{
//Draws the sky
page.setColor(Color.cyan);
page.fillRect(0,0,2000,2000);
//Draws the grass
page.setColor (Color.green);
page.fillRect (0,500,width,height);
}
}
A number of things jump out at me immediately...
You're trying to use a off screen buffer, but you're recreating it each time you paint to the screen...
public void paintOffscreen(Graphics page)
{
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200)
num = 0;
page.setColor(Color.yellow);
page.fillRect(num,100,100,100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
//Mouse move square
int s = 100;
page.setColor(Color.yellow);
page.fillRect(mX - s / 2, mY - s / 2, s, s);
repaint();
}
Additionally, the last call in the method is to repaint. This is a bad idea. This could cause you paint method to be recalled, again and again and again...
You would be better of rendering the backing buffer only when it needs to change...
public void paint(Graphics g)
{
super.paint(g); // YOU MUST CALL super.paint!!!!
//Clear the buffer
Dimension d = getSize();
checkOffscreenImage();
//Draw the buffer
g.drawImage(mImage, 0, 0, null);
}
private void checkOffscreenImage()
{
Dimension d = getSize();
if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height) {
mImage = createImage(d.width, d.height);
Graphics offG = mImage.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(offG);
offG.dispose(); // If you create it, you must dispose of it...
}
}
Now, this is going to raise some issues with invalidating the buffer. This can be achieved by overriding invalidate and setting the mImage to null
public void invalidate() {
mImage = null;
super.invalidate();
}
You're extending most of your components from JFrame???
Building, Window and Background do no painting of there own (from the content of Swing), you are simply calling the draw method. There is no need to extend from JFrame or JApplet, they're adding no benefit to your program and are simply confusing the issues.
You should, only very rarely, need to override paint on a top level container like JFrame. You are better off using something like JPanel and override the paintComponent method, if for no other reason, they (top level containers) aren't double buffered.
I would move the logic for Skyline into a JPanel and then add it to a JFrame for displaying - IMHO
UPDATED
I've gone through the code and updated it to work the (basic) way I think it should and found a couple of other things along the way...
This this is a bad idea...
public void mouseMoved(MouseEvent me) {
Graphics g = getGraphics();
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
update(g);
//repaint();
}
There should never be any need for you to call update(Graphics), besides, the Graphics context you got is simply a snap shot of the last repaint. This will drastically slow you painting process any way, as it is repeatedly calling paint.
So, this is my take...
public class Skyline extends JFrame {
private int num = 0;
private Building bldg1 = new Building(305, 110, 30);
private Building bldg2 = new Building(380, 125, 170);
private Building bldg3 = new Building(245, 200, 325);
private Building bldg4 = new Building(470, 170, 555);
private Building bldg5 = new Building(395, 200, 755);
private Background bg = new Background();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
Skyline f = new Skyline();
f.setSize(1017, 661); //Sets size of window
f.setTitle("Skyline"); //Sets title of window
f.setVisible(true);
}
});
}
public Skyline() {
setLayout(new BorderLayout());
add(new SkyLinePane());
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class SkyLinePane extends JPanel {
private Image mImage; //Image buffer
private boolean painting = false;
private int mX, mY; //Mouse cooddinates
public SkyLinePane() {
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
repaint();
}
});
}
protected void updateBuffer() {
if (!painting && mImage == null) {
painting = true;
new BackgroundPainter(this).execute();
}
}
//====================================BUFFER CODE========================================
#Override
public void paintComponent(Graphics g) {
Dimension d = getSize();
if (mImage != null) {
g.drawImage(mImage, 0, 0, null);
} else {
updateBuffer();
}
g.setColor(Color.RED);
g.drawOval(mX - 5, mY - 5, 10, 10);
}
//=======================================================================================
protected void setBackground(Image image) {
mImage = image;
painting = false;
repaint();
}
}
public class BackgroundPainter extends SwingWorker<Image, Image> {
private SkyLinePane skyLinePane;
public BackgroundPainter(SkyLinePane skyLinePane) {
this.skyLinePane = skyLinePane;
}
#Override
protected Image doInBackground() throws Exception {
Dimension d = skyLinePane.getSize();
Image backgroundBuffer = null;
if (d.width > 0 && d.height > 0) {
System.out.println("Paint offscreen...");
backgroundBuffer = createImage(d.width, d.height);
Graphics offG = backgroundBuffer.getGraphics();
offG.setColor(getBackground());
offG.fillRect(0, 0, d.width, d.height);
//Save frame to buffer
paintOffscreen(offG);
offG.dispose();
System.out.println("Done Paint offscreen...");
}
return backgroundBuffer;
}
#Override
protected void done() {
try {
skyLinePane.setBackground(get());
} catch (ExecutionException exp) {
exp.printStackTrace();
} catch (InterruptedException exp) {
exp.printStackTrace();
}
}
public void paintOffscreen(Graphics page) {
//Draws the background
bg.draw(page);
//Moving square
num++;
if (num > 1200) {
num = 0;
}
page.setColor(Color.yellow);
page.fillRect(num, 100, 100, 100);
//Draws the buildings
bldg1.draw(page);
bldg2.draw(page);
bldg3.draw(page);
bldg4.draw(page);
bldg5.draw(page);
}
}
//=======================================================================================
public class Windows {
private Random gen = new Random();
private int height, width, locX;
private int onOff = 0;
public Windows() {
height = 305;
width = 110;
locX = 30;
}
public Windows(int height, int width, int locX) {
this.height = height;
this.width = width;
this.locX = locX;
}
public void draw(Graphics page) {
page.setColor(Color.darkGray);
page.fillRect(locX, 550 - height, width, height);
for (int i = 550 - height + 5; i < 550; i += 15) {
for (int x = locX + 5; x < locX + width; x += 15) {
onOff = gen.nextInt(2);
if (onOff == 0) {
page.setColor(Color.black);
} else {
page.setColor(Color.yellow);
}
page.fillRect(x, i, 10, 10);
}
}
}
}
public class Building {
private int height, width, locX;
private int onOff;
private Windows windows1;// = new Windows(height, width, locX);
public Building() {
height = 305;
width = 110;
locX = 30;
windows1 = new Windows(height, width, locX);
}
public Building(int height, int width, int locX) {
this.width = width;
this.height = height;
this.locX = locX;
windows1 = new Windows(height, width, locX);
}
public void draw(Graphics page) {
page.setColor(Color.darkGray);
page.fillRect(locX, 550 - height, width, height);
windows1.draw(page);
}
}
public class Background {
private int height, width;
public Background() {
height = 400;
width = 2000;
}
public Background(int height, int width) {
this.height = height;
this.width = width;
}
public void draw(Graphics page) {
//Draws the sky
page.setColor(Color.cyan);
page.fillRect(0, 0, 2000, 2000);
//Draws the grass
page.setColor(Color.green);
page.fillRect(0, 500, width, height);
}
}
}
Basically, I moved the core rendering of the skyling to it's own panel and used JComponent#paintComponent to render the skyline.
I employed a SwingWorker to off load the rendering of the backing buffer to another thread, allowing the UI to remain responsive while the backing buffer was rendered.
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.