adding squares to an animation - java

I'm trying to create a program that runs an animation similar to the one on this video but I'm having trouble adding more squares. I tried to add all the squares to an array list but I couldn't figure out where it goes.
so far this is my code:
public class Animation extends JFrame{
CrazySquares square = new CrazySquares();
Animation(){
add(new CrazySquares());
}
public static void main (String[] args){
Animation frame = new Animation();
frame.setTitle("AnimationDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}
class CrazySquares extends JPanel{
private final int numberOfRectangles=100;
Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
private int x=1;
private int y=1;
private Timer timer = new Timer(30, new TimerListener());
Random random= new Random();
int randomNumber=1+(random.nextInt(4)-2);
Random rand= new Random();
int rando=1+(rand.nextInt(4)-2);
CrazySquares(){
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width=getWidth();
int height=getHeight();
g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
}
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
x += rando;
y+= randomNumber;
repaint();
}
}
}

You've got code to paint out one rectangle, here:
int width=getWidth();
int height=getHeight();
g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
Now what I would recommend, would be that you port these values into a Square object. Or, better yet, use the Rectangle object. If you went with the custom approach:
public class Square
{
public Square(int x, int y, int height, int width)
{
// Store these values in some fields.
}
public void paintComponent(Graphics g)
{
g.fillRect() // Your code for painting out squares.
}
}
Then, all you need to do, is call each object's paintComponent method in some list. Let's assume you have some List:
List<Square> squares = new ArrayList<Square>();
for(Square sq : squares)
{
sq.paintComponent(g);
}

this is the code so far. I know its nasty but its because i've been trying different things a none of them work. i really appreciate your help. thanks. #ChrisCooney
public class SquaresAnimation extends JFrame{
SquaresAnimation(){
add(new CrazySquares());
}
public static void main (String[] args){
SquaresAnimation frame = new SquaresAnimation();
frame.setTitle("AnimationDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}
class Square{
private int x;
private int y;
public int height;
public int width;
Square(int x, int y, int height, int width)
{
// Store these values in some fields.
this.x=x;
this.y=y;
this.height=height;
this.width=width;
}
public void paintComponent(Graphics g)
{
g.setColor(Color.CYAN);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
}
}
class CrazySquares extends JPanel {
private final int numberOfRectangles=100;
Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
private int x=1;
private int y=1;
Random random= new Random();
int randomNumber=1+(random.nextInt(4)-2);
Random rand= new Random();
int rando=1+(rand.nextInt(4)-2);
private Timer timer = new Timer(30, new TimerListener());
List<Square> squares = new ArrayList<Square>();
CrazySquares(Graphics g){
timer.start();
for(Square sq : squares){
sq.paintComponent(g);
}
}
}
//protected void paintComponent(Graphics g) {
//super.paintComponent(g);
// }
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}

Related

Drawing ovals on JButton

I'm writing minesweeper and I want to put ovals on mine cells after a mine is clicked. But for now, I just want to put ovals on all cells just to check. I have written the code below. But when I run the program there is no ovals on buttons. I can not see the reason. I would be grateful if I get some suggestions.
public class Cell extends JButton{
...
public void painComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.drawOval(0,0,25,25);
}
public void draw() {
repaint();
}
...
}
public class Grid extends JPanel implements MouseListener{
...
public Grid(){
this.setLayout(new GridLayout(20,20));
cells = new Cell[20][20];
for(int i=0; i<20; i++) {
for(int j=0; j<20; j++) {
cells[i][j] = new Cell(i,j);
cells[i][j].addMouseListener(this);
cells[i][j].draw();
this.add(cells[i][j]);
}
}
plantMines();
setVisible(true);
}
...
}
but when I run the program there is no ovals on buttons.
public void painComponent(Graphics g) {
You made a typo. You spelt "paint" wrong.
When you override a method you should use:
#Override
protected void paintComponent(Graphics g)
This way if you make a typo the compiler will tell you that you are not overriding a method of the class.
Also, don't attempt to draw the oval by using custom painting. Instead you should be adding an Icon to the button. Then you can just change the Icon as required.
You can easily create an simple Icon to use. Here is an example of creating a square Icon:
import java.awt.*;
import javax.swing.*;
public class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JPanel panel = new JPanel( new GridLayout(2, 2) );
for (int i = 0; i < 4; i++)
{
Icon icon = new ColorIcon(Color.RED, 50, 50);
JLabel label = new JLabel( icon );
label.setText("" + i);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
panel.add(label);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}

Issue in Painting JComponents added to JComponent

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

Drawing on a canvas declared in another function

I have an application which has a swing user interface class, which has buttons that send variables to a canvas class like so;
public class createWindow extends JFrame implements ActionListener
{
createCanvas canvas = new createCanvas(10, 10);
JPanel mainPanel = new JPanel();
public createWindow()
{
mainPanel.add(canvas, BorderLayout.CENTER);
}
}
createCanvas is a class which declares a paintComponent;
public class createCanvas extends JPanel
{
int xValue;
int yValue;
int xCoordinate;
int yCoordinate;
public createCanvas(int x, int y)
{
xValue = x;
yValue = y;
}
public void setXCoordinate(int x)
{
xCoordinate = x;
}
public void setYCoordinate(int y)
{
yCoordinate = y;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawGrid(g, this.xValue, this.yValue);
g.fillArc(xCoordinate, yCoordinate, 6, 6, 0, 360);
}
public drawGrid(Graphics g, int xLength, int yLength)
{
//creates a grid that is xLength x yLength
}
}
However, I also have a selection of Objects which I want to have a .draw() function, which can use the paintComponent in createCanvas.
The problem is, of course, when I need to draw the node on the grid, I can set the coordinates, but how do I display the node on the canvas I declared in createWindow?
public class Node()
{
int xCoordinate;
int yCoordinate;
//Suitable constructors, sets, gets
public void draw()
{
createCanvas canvas = new createCanvas();
canvas.setXCoordinate(this.xCoordinate);
canvas.setYCoordinate(this.yCoordinate);
canvas.repaint();
}
}
So, I am wondering if there is a way for me to keep what I have drawn on the canvas in createWindow, as well as what I draw in my Object class.
Thanks.
What you want to do is have the draw method in your object take a Graphics argument. This Graphics object will be the same Graphics context in your paintComponent method. You can create the object in your JPanel class. Something like this
public class Circle {
int x, y;
public Circle(int x, int y) {
this.x = x;
this.y = y;
}
public void drawCirlce(Graphics g) {
g.fillRect(x, y, 50, 50);
}
}
Then in you JPanel class
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
You can have a setter for the x and y in your Circle class. You should change them somewhere in your JPanel class then call repaint() afterwards. You could move it with the press of a key or you can animate it with a java.util.Timer. For example
With a Timer
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
Timer timer = new Timer(50, new ActionListener(){
#Override
public void actionPerfomed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
With a key binding
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED_IN_WINDOW);
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "moveRight");
getActionMap().put("moveRight", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}
With a button press
public class CirclePanel extends JPanel {
Circle circle = new Circle(100, 100);
public CirclePanel() {
JButton button = new JButton("Move Right");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
circle.x += 10;
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
circle.drawCircle(g);
}
}

Why is my method not clearing the ArrayList?

NOTE: The problem with my code was simply that I created the method to clear the rects and everything but the only thing I was doing wrong was instantiating DrawPanel class's myDraw object inside of the go() method. And so I had to instantiate DrawPanel again with Stop and that created a whole new object. So I ended up calling the clearRects method on a different DrawPanel object than the one rects were being added to. Anyway, I decided to go with code suggestions by MadProgrammer because his code was exactly how Java: A Beginner's Guide teaches it and was much cleaner.
Well, I have been running around StackOverflow since this morning and have been able to fix a lot of problems with my code but I am still stuck with this problem with ArrayLists.
I have the following piece of code that does not seem to do what I intend for it to do. Now I am aware that I am the one making a mistake somewhere but not really sure how to correct it.
The way it is set up is that when I hit the stop button, the ArrayList should clear so I have a blank JPanel so to speak, here's the code snippets. I can post the whole program if you want me to though but I am only pasting the snippet here because I'm assuming I'm making a pretty simple and dumb mistake on my part:
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
addRect();
for(MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
frame.repaint();
System.out.println("I was called");
}
}
And here's the part where the button calls it in its actionPerformed method:
class StopListener implements ActionListener {
DrawPanel draw = new DrawPanel();
public void actionPerformed(ActionEvent e) {
timer.stop();
draw.clearEvent(e);
}
}
EDIT: I understand that the arraylist object that my clearEvent method refers to is not the same one that addRect()'s adding stuff to. What I am asking, I guess, is how to make it "connect" so I can wipe things clean using the JButton.
EDIT: Here's the full program:
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.*;
public class TwoButtonsRandomRec {
JFrame frame;
Timer timer;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TwoButtonsRandomRec test = new TwoButtonsRandomRec();
test.go();
}
});
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton startButton = new JButton("Start");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
final DrawPanel myDraw = new DrawPanel();
timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
myDraw.repaint();
}
});
frame.add(startButton, BorderLayout.NORTH);
frame.add(stopButton, BorderLayout.SOUTH);
frame.add(myDraw, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
class StartListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
timer.start();
}
}
class StopListener implements ActionListener {
DrawPanel draw = new DrawPanel();
public void actionPerformed(ActionEvent e) {
timer.stop();
draw.clearEvent(e);
}
}
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
addRect();
for(MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
repaint();
System.out.println("I was called");
}
}
}
class MyRectangle extends Rectangle {
Color color;
public MyRectangle(int x, int y, int w, int h, Color c) {
super(x, y, w, h);
this.color = c;
}
public Color getColor() {
return color;
}
}
Here's the previous relevant question I asked here in case anyone's interested.
Strange JFrame Behavior
I see two immediate issues.
The first is, you're calling addRect within the paintComponent method, which means, even after you clear the List, on the next repaint, a new rectangle will be added to it.
Secondly, I would call repaint in the DrawPanel instead of using frame.repaint(), as you really only want to update the draw panel, not the entire frame
public class BadPaint05 {
public static void main(String[] args) {
new BadPaint05();
}
public BadPaint05() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
private DrawPanel drawPane;
private Timer timer;
public MasterPane() {
setLayout(new BorderLayout());
drawPane = new DrawPanel();
add(drawPane);
JButton stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
drawPane.clearEvent(e);
timer.stop();
}
});
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
drawPane.addRect();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
add(stop, BorderLayout.SOUTH);
}
}
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// addRect();
for (MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
repaint();
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
// frame.repaint();
repaint();
System.out.println("I was called");
}
}
public class MyRectangle {
private int x, y, width, height;
private Color color;
private MyRectangle(int x, int y, int wd, int ht, Color color) {
this.x = x;
this.y = y;
this.width = wd;
this.height = ht;
this.color = color;
}
public Color getColor() {
return color;
}
}
}

Java Racing game: JPanel component moves along when I repaint the car object

I created 2 car objects using my CarPanel. Then I used to keylistener to repaint the object so it will look like moving forward.
But the problem is the whole panel moves along, even though I just increased the distance to the 'x' coordinate.
If I were to resize the window, it sometimes doesn't even clear the component.
public class RacingCars extends JFrame {
CarPanel car1;
CarPanel car2;
//Constructor
public RacingCars(){
setLayout(new GridLayout(2,1));
car1 = new CarPanel('w',Color.RED);
car2 = new CarPanel('k',Color.blue);
car1.setBackground(Color.black);
this.add(car1, BorderLayout.NORTH);
this.add(car2, BorderLayout.SOUTH);
this.addKeyListener(new keyListener());
}
class keyListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyChar()=='w'){
car1.moveCar();
}
if(e.getKeyChar()=='k'){
car2.moveCar();
}
}
}
}
CarPanel::
public class CarPanel extends JPanel {
private char forwardKey = 'w';
private boolean reachedTarget = false;
private Color color = Color.blue;
private int x= 10;
private int y= 10;
private int panelWidth;
private int panelHeight;
//default Constructor
public CarPanel(){
}
//overloaded Constructor
public CarPanel(char key, Color color){
this.forwardKey=key;
this.color = color;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
panelWidth= getWidth();
panelHeight= getHeight();
//draw a Car
g.setColor(color);
//polygon points
int t_x[]= {x+10,x+20,x+30,x+40};
int t_y[]= {y+10,y,y,y+10};
g.fillPolygon(t_x,t_y,t_x.length);
g.fillRect(x, y+10, 50, 10);
g.fillArc(x+10, y+20, 10, 10, 0, 360);
g.fillArc(x+30, y+20, 10, 10, 0, 360);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(750,100);
}
public void moveCar(){
if(this.x < panelWidth){
this.x+=10;
repaint();
}
}
}
Solution
Because of this code, I always had that extra space. but no idea how it supposed to cause to this strange behavior.
/*
public int getX(){
return this.x;
}
*/
But the problem is the whole panel moves along, ..
No it doesn't. The 'green dot' proves that.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RacingCars extends JFrame {
CarPanel car1;
CarPanel car2;
//Constructor
public RacingCars(){
setLayout(new GridLayout(2,1));
car1 = new CarPanel('w',Color.RED);
car2 = new CarPanel('k',Color.blue);
car1.setBackground(Color.black);
this.add(car1, BorderLayout.NORTH);
this.add(car2, BorderLayout.SOUTH);
this.addKeyListener(new MyKeyListener());
}
class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyChar()=='w'){
car1.moveCar();
}
if(e.getKeyChar()=='k'){
car2.moveCar();
}
}
}
public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
RacingCars rc = new RacingCars();
rc.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rc.pack();
rc.setVisible(true);
}
});
}
}
class CarPanel extends JPanel {
private char forwardKey = 'w';
private boolean reachedTarget = false;
private Color color = Color.blue;
private int x= 10;
private int y= 10;
private int panelWidth;
private int panelHeight;
//default Constructor
public CarPanel(){
}
//overloaded Constructor
public CarPanel(char key, Color color){
this.forwardKey=key;
this.color = color;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval(0,0,25,25);
panelWidth= getWidth();
panelHeight= getHeight();
//draw a Car
g.setColor(color);
//polygon points
int t_x[]= {x+10,x+20,x+30,x+40};
int t_y[]= {y+10,y,y,y+10};
g.fillPolygon(t_x,t_y,t_x.length);
g.fillRect(x, y+10, 50, 10);
g.fillArc(x+10, y+20, 10, 10, 0, 360);
g.fillArc(x+30, y+20, 10, 10, 0, 360);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(750,100);
}
public void moveCar(){
if(this.x < panelWidth){
this.x+=10;
repaint();
}
}
}

Categories

Resources