This picture is edited with photoshop to show what I want to do:
Basically, what I want to do is to move the black-stick-man by clicking on it and move to available positions(gray boxes).
This is what I've done so far:
Arena.java
public class Arena extends JFrame{
JPanel a = new JPanel();
Player players[][] = new Player[10][10];
private ImageIcon player = new ImageIcon("player.jpg");
private ImageIcon player2 = new ImageIcon("player2.jpg");
private ImageIcon poop = new ImageIcon("poop.jpg");
private ImageIcon moves = new ImageIcon("moves.jpg");
public static void main(String args[]){
new Arena();
}
public Arena(){
setTitle("The Arena");
setSize(500,500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
a.setLayout(new GridLayout(10,10));
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
players[i][j] = new Player();
a.add(players[i][j]);
}
}
//player position
players[9][4].setIcon(player);
//player 2 position
players[9][7].setIcon(player2);
//poop
players[7][2].setIcon(poop);
players[5][7].setIcon(poop);
add(a);
setVisible(true);
}
}
Player.java
public class Player extends JButton{
private int xPos;
private int yPos;
public Player(){
}
public int getXPos(){
return xPos;
}
public int getYPos(){
return yPos;
}
public void setXPos(){
this.xPos = x;
}
public void setYPos(){
this.yPos = y;
}
}
Thanks!
Related
I am having problem getting my horse position to update within my swing application. I have tried multiple methods to update the xPosition of the horses as they refresh across the swing panel that represents the racetrack.
public class HorseModel{
/*Horse dimensions*/
private int x;
private int y;
private final int horsePerimeter = 20;
public HorseModel(int xT, int yT){
/*Constructor*/
x = xT;
y = yT;
}
public void setDimensions(int dimX, int dimY){
/*Sets program dimensions*/
x = dimX;
y = dimY;
}
public void createHorse(Graphics2D h){
/*Paints HorseModel on screen as 2 dimensional object*/
Ellipse2D.Double horseModel = new Ellipse2D.Double(x, y, horsePerimeter, horsePerimeter);
h.setColor(Color.RED);
h.fill(horseModel);
h.setColor(Color.YELLOW);
h.draw(horseModel);
}
}
public class HorseMovement implements Runnable{
public final int xStartPos = 10; //change
public final int yStartPos = 20;
private RaceTrack hRaceTrack;
private HorseModel Horse2D;
private int xPos, yPos;
public HorseMovement(RaceTrack r, int yPos_Spacing){
/*Constructor*/
xPos = xStartPos;
yPos = yStartPos * yPos_Spacing;
Horse2D = new HorseModel(xPos, yPos);
hRaceTrack = r;
}
public HorseModel moveHorse(HorseModel horseObject){
/*Updates horse positon*/
horseObject = new HorseModel(xPos++, yPos);
return horseObject;
}
public void paintComponent(Graphics h){
/*paints the new horse after movement*/
this.Horse2D = moveHorse(Horse2D);
Graphics2D hMod = (Graphics2D) h;
Horse2D.createHorse(hMod);
}
public void run(){
/*Repaints the horse models as they increment movement across the screen*/
hRaceTrack.repaint();
hRaceTrack.revalidate();
}
}
public class RacePanel extends JFrame{
/*Frame Buttons*/
private JPanel mPanel;
private JButton startRace = new JButton("Start Race");
private JButton stopRace = new JButton("Stop Race");
private JButton startOver = new JButton("Start Over");
/*Panel to fill with HorseModels for race*/
private RaceTrack rTrack;
/*Window dimensions*/
public int Window_Height = 1024;
public int Window_Width = 768;
public RacePanel(){
/*Constructor*/
initGui();
initRace();
initQuit();
setSize(Window_Width, Window_Height);
}
public void initGui(){
/*Initializes the main race panel and sets button positions and layouts*/
mPanel = new JPanel(new BorderLayout());
rTrack = new RaceTrack();
JPanel horsePanel = new JPanel(); //panel to house horse objects before running across screen
horsePanel.setLayout(new GridLayout(1, 3));
positionJPanels(horsePanel, mPanel);
}
public void initRace(){
/*implements action listener for start race button*/
class StartRace implements ActionListener{
public void actionPerformed(ActionEvent e){
startRace.setEnabled(true);
rTrack.initTrack();
}
}
ActionListener event = new StartRace();
stopRace.addActionListener(event);
}
public void initQuit(){
/*Implements the action listener for stop race button*/
class StopRace implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);//exits program if race is stopped
}
}
ActionListener event = new StopRace();
stopRace.addActionListener(event);
}
public void positionJPanels(JPanel h, JPanel p){
/*Handles adding buttons to a JPanel*/
h.add(startRace);
h.add(startOver);
h.add(stopRace);
p.add(h, BorderLayout.NORTH); //sets the horse panel buttons to the top of the layout
p.add(rTrack, BorderLayout.CENTER); //sets
add(p);
}
}
public class RaceController {
public static void main(String[] args){
new RaceController();
}
public RaceController(){
/*Constructor*/
JFrame mFrame = new RacePanel();
mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mFrame.setVisible(true);
}
}
public class RaceTrack extends JPanel{
/*Sets horses within race track*/
private int numOfHorseObjects = 5;// change this to a dynamic
private int numOfThreads = 25;
/*Holds horse thread from HorseObject class*/
private ArrayList<HorseMovement> horses = new ArrayList<>();
private ArrayList<Thread> threads = new ArrayList(numOfThreads);
public RaceTrack(){
/*Constructor*/
setBackground(Color.black);
reset();
}
public void initTrack(){
/*Starts the RaceTrack simulation*/
threads.clear(); //clears the thread arraylist still residing
for(int i = 0; i < horses.size(); i++){
Thread T = new Thread(horses.get(i));
T.start();
threads.add(T);
}
}
public void reset(){
/*resets horse position within screen*/
horses.clear();
for(int i = 0; i < numOfHorseObjects; i++){
horses.add(new HorseMovement(this, i + 1));
}
}
public void paintComponent(Graphics g){
/*overrides graphics paint method in order to paint the horse movements
* through the arraylist of HorseMovements*/
super.paintComponent(g);
for(HorseMovement h : horses){
h.paintComponent(g);
}
}
}
Issues with your code:
You never give the startRace JButton an ActionListener, so how is button going to have any affect, and how is the race ever going to start? Note that you're adding the StartRace ActionListener object to the stopRace JButton, and I'm guessing that this was done in error.
Even if you added that Listener to the startRace button, the action listener will only advance all the horses one "step" and no more -- there are no loops in within your background threads to perform actions repetitively.
You seem to be creating new Horse2D objects needlessly. Why not simply advance the location of the existing Horse2D object?
Myself, I'd use a single Swing Timer rather than a bunch of Threads in order to simplify the code.
I (A novice programmer) am trying to paint an oval over a JPanel. I am trying to use the method paint. However, it requires a Graphics argument. I get a NullPointerException when I include my Graphics as a argument because it is null, but I do not know how else to paint the oval. I tried repaint instead but nothing happened. Any help would be appreciated. Here is my main class:
public class Checkers extends JPanel{
public static final int BOARDSQUARES = 8;
public static final int BOARDSIZE = 75;
private JPanel[][] board;
private final Point point1;
private final LineBorder border1;
public JFrame frame;
checkerPiece piece = new checkerPiece(this);
Graphics g;
public Checkers(){
board = new JPanel[BOARDSQUARES][BOARDSQUARES];
point1 = new Point (BOARDSIZE,BOARDSIZE);
border1=new LineBorder(Color.BLACK, 1);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Checkers checkers = new Checkers();
checkers.frame=checkers.createJFrame();
checkers.board =checkers.createBoard(checkers.board, checkers.point1, checkers.border1);
for (int y=0;y<BOARDSQUARES;y++){
for (int x = 0;x<BOARDSQUARES;x++){
checkers.frame.getContentPane().add(checkers.board[y][x]);
}
}
checkers.paint(checkers.g);
}
private JPanel[][] createBoard (JPanel[][] board, Point point, LineBorder border1){
for (int row = 0; row<BOARDSQUARES;row++){
point.y=BOARDSIZE;
for (int col = 0; col <BOARDSQUARES;col++){
board[row][col] = new JPanel();
board[row][col].setLocation(point);
board[row][col].setVisible(true);
board[row][col].setSize(BOARDSIZE,BOARDSIZE);
board[row][col].setOpaque(true);
if ((row%2==0&&col%2==0)||(row%2==1&&col%2==1)){
board[row][col].setBackground(new Color (230,200,150));
} else if ((row%2==0&&col%2==1)||(row%2==1&&col%2==0)) {
board[row][col].setBackground(new Color (165, 42,42) );
}
board[row][col].setBorder(border1);
point.y = point.y+BOARDSIZE;
}
point.x=point.x+BOARDSIZE;
}
return board;
}
private JFrame createJFrame (){
JFrame mainFrame = new JFrame("Checkers");
mainFrame.setSize(1000,1000);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new Checkers());
return mainFrame;
}
#Override
public void paint (Graphics g){
System.out.println("hi");
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
piece.paint(g2d,board[0][0].getLocation().x,board[0][0].getLocation().y,Color.BLACK);
}
}
A necessary snippet from my other class (cherkerPiece piece):
public void paint (Graphics2D g, int x, int y, Color color){
g.setColor(color);
g.fillOval(x, y, DIAMETER, DIAMETER);
}
Thank you for your help
To create something as complex as a checkers game, you should follow the model / view / controller pattern when creating your Java Swing GUI.
I created a model class for a checker board square and another model class for a checker piece. I created a model class for the checker board and another model class to hold all of the checker pieces.
I created a view class to draw the checker board. I created another view class to create the main window.
I did not create any controller classes. This code just shows you how to draw a checker board. I put all of the classes together to make it easier to paste the code. You should separate the classes into separate Java files.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckerBoard implements Runnable {
private Board board;
private CheckerBoardPanel checkerBoardPanel;
private JFrame frame;
private Pieces pieces;
public static void main(String[] args) {
SwingUtilities.invokeLater(new CheckerBoard());
}
public CheckerBoard() {
this.board = new Board();
this.pieces = new Pieces();
}
#Override
public void run() {
frame = new JFrame("Checker Board");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
checkerBoardPanel = new CheckerBoardPanel(board, pieces);
frame.add(checkerBoardPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class CheckerBoardPanel extends JPanel {
private static final long serialVersionUID = 3770663347384271771L;
private Board board;
private Pieces pieces;
public CheckerBoardPanel(Board board, Pieces pieces) {
this.board = board;
this.pieces = pieces;
this.setPreferredSize(board.getPreferredSize());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Square[][] checkerBoard = board.getBoard();
for (int row = 0; row < checkerBoard.length; row++) {
for (int column = 0; column < checkerBoard[row].length; column++) {
Square square = checkerBoard[row][column];
Rectangle drawingRectangle = square.getDrawingRectangle();
g.setColor(square.getColor());
g.fillRect(drawingRectangle.x, drawingRectangle.y,
drawingRectangle.width, drawingRectangle.height);
}
}
List<Piece> checkerPieces = pieces.getPieces();
for (Piece checkerPiece : checkerPieces) {
Point coordinate = checkerPiece.getCoordinate();
Rectangle drawingRectangle = checkerBoard[coordinate.x][coordinate.y]
.getDrawingRectangle();
int x = drawingRectangle.x + drawingRectangle.width / 2;
int y = drawingRectangle.y + drawingRectangle.height / 2;
int radius = board.getSquareWidth() * 2 / 6;
g.setColor(checkerPiece.getColor());
g.fillOval(x - radius, y - radius, radius + radius, radius
+ radius);
}
}
}
public class Board {
private static final int BOARD_WIDTH = 8;
private static final int SQUARE_WIDTH = 64;
private Square[][] board;
public Board() {
this.board = initalizeBoard(BOARD_WIDTH, SQUARE_WIDTH);
}
private Square[][] initalizeBoard(int boardWidth, int squareWidth) {
Square[][] board = new Square[boardWidth][boardWidth];
int x = 0;
int y = 0;
for (int row = 0; row < boardWidth; row++) {
for (int column = 0; column < boardWidth; column++) {
Square square = new Square();
if (isLightSquare(row, column)) {
square.setColor(Color.WHITE);
} else {
square.setColor(Color.LIGHT_GRAY);
}
square.setCoordinate(new Point(row, column));
square.setDrawingRectangle(new Rectangle(x, y, squareWidth,
squareWidth));
board[row][column] = square;
x += squareWidth;
}
x = 0;
y += squareWidth;
}
return board;
}
public boolean isLightSquare(int row, int column) {
if (row % 2 == 0) {
if (column % 2 == 0) {
return true;
} else {
return false;
}
} else {
if (column % 2 == 0) {
return false;
} else {
return true;
}
}
}
public Dimension getPreferredSize() {
int width = SQUARE_WIDTH * 8 + 1;
return new Dimension(width, width);
}
public Square[][] getBoard() {
return board;
}
public int getSquareWidth() {
return SQUARE_WIDTH;
}
}
public class Square {
private Color color;
private Point coordinate;
private Rectangle drawingRectangle;
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
public Rectangle getDrawingRectangle() {
return drawingRectangle;
}
public void setDrawingRectangle(Rectangle drawingRectangle) {
this.drawingRectangle = drawingRectangle;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
public class Pieces {
private List<Piece> pieces;
public Pieces() {
this.pieces = addPieces();
}
private List<Piece> addPieces() {
List<Piece> pieces = new ArrayList<Piece>();
Piece piece = new Piece();
piece.setColor(Color.RED);
piece.setCoordinate(new Point(2, 1));
pieces.add(piece);
piece = new Piece();
piece.setColor(Color.BLACK);
piece.setCoordinate(new Point(5, 0));
pieces.add(piece);
// Add the rest of the red and black pieces here
return pieces;
}
public List<Piece> getPieces() {
return pieces;
}
public void addPiece(Piece piece) {
this.pieces.add(piece);
}
}
public class Piece {
private Color color;
private Point coordinate;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
}
}
you need to add a class that extends Canvas and do all your painting in that class. like this
public class FirstWindow extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public FirstWindow()
{
super("Kayte does not go to water parks");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
}
public class Start extends Canvas implements Runnable
public class Main
{
public static void main(String arg[])
{
FirstWindow fw = new FirstWindow();
Start game = new Start(500, 500);
fw.add(game);
fw.setVisible(true);
new Thread(game).start();
}
}
I am trying to create a simple Tic-Tac-Toe game using GUI. I have one button, which shows the player's turn (when pressed the button itself changes its text to 0 or 1 (drawing X or O)).
However I am stuck with a problem here, I have no idea why my test within the MouseListener is applied to every single Jcomponent object (my class TicTacToe extends it) and all of the 9 Panels, which are within GridLayout(3,3) are filled with the same drawing...
Here is my TicTacToe class
public class TicTacToe extends JComponent{
private int ovalOrX = 0;
public TicTacToe(){
super.setPreferredSize(new Dimension(300,300));
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.drawLine(0, 0, getWidth(), 0);//top line
g.drawLine(0, 0, 0, getHeight());//left line
g.drawLine(0, 300, getWidth(), getHeight());//botton line
g.drawLine(getWidth(),getHeight(), getWidth(), 0);//right line
if(ovalOrX == 1){
g.setColor(Color.RED);
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);
}
if(ovalOrX == 2){
g.setColor(Color.BLUE);
g.drawOval(0,0,100,100);
}
}
public void drawX(){
ovalOrX = 1;
repaint();
}
public void drawCircle(){
ovalOrX = 2;
repaint();
}
}
And here is my JFrame class:
public class TicTacToeFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 300;
private JPanel mainPanel;
private TicTacToe scene;
private TicTacToe s00;
private TicTacToe s01;
private TicTacToe s02;
//finish top raw
private TicTacToe s10;
private TicTacToe s11;
private TicTacToe s12;
//finish middle raw
private TicTacToe s20;
private TicTacToe s21;
private TicTacToe s22;
private int buttonInt = 0;
private JButton OX;
class AddButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
if(buttonInt == 0){
buttonInt++;
}
else if(buttonInt == 1){
buttonInt = 0;
}
OX.setText("Player: " + buttonInt);
}
}
class MyMouseListener extends MouseAdapter{
public void mouseClicked(MouseEvent event){
TicTacToe[] myPanelArray = {s00,s01,s02,s10,s11,s12,s20,s21,s22};
if(buttonInt == 0){
for(int i = 0; i < myPanelArray.length;i++){
if(myPanelArray[i].contains(event.getPoint())){
myPanelArray[i].drawCircle();
}
}
}
}
}
public TicTacToeFrame(){
scene = new TicTacToe();
scene.setPreferredSize(new Dimension(300,300));
add(scene,BorderLayout.CENTER);
OX = new JButton("Player: " + buttonInt);
OX.addActionListener(new AddButtonListener());
add(OX,BorderLayout.NORTH);
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(3,3));
fillScene();
add(mainPanel,BorderLayout.CENTER);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
}
private void fillScene(){
s00 = new TicTacToe();
s00.addMouseListener(new MyMouseListener());
s01 = new TicTacToe();
//s01.addMouseListener(new MyMouseListener());
s02 = new TicTacToe();
s10 = new TicTacToe();
s11 = new TicTacToe();
s12 = new TicTacToe();
s20 = new TicTacToe();
s21 = new TicTacToe();
s22 = new TicTacToe();
//finish bottom raw
mainPanel.add(s00);
mainPanel.add(s01);
mainPanel.add(s02);
mainPanel.add(s10);
mainPanel.add(s11);
mainPanel.add(s12);
mainPanel.add(s20);
mainPanel.add(s21);
mainPanel.add(s22);
}
}
The return value of event.getPoint() is relative to the source component, a TicTacToe in this case, no the entire frame. Therefore, it will always be true for all the TictacToe's since they are all the same size.
Istead, use the Event.getSource() to determine the source object.
Also, it advisable to put all you TicTacToe objects into a TicTacToe[][] instead of listed separately.
I am making a simple program to paint a graph and some points in it. The points should be made with methods while changing coordinates of the g.fillOval but actually its painting only the last point.
Here is the code:
import javax.swing.*;
import java.awt.*;
public class PointGraphWriter extends JPanel
{
JFrame korniza = new JFrame();
private int x;
private int y;
private int length;
private String OX;
private String OY;
private String emri;
private int y_height;
private int x_num;
public PointGraphWriter()
{
int width= 500;
korniza.setSize(width,width);
korniza.setVisible(true);
korniza.setTitle(emri);
korniza.getContentPane().add(this);
}
public void paintComponent(Graphics g)
{
g.drawLine(x,y,x+length,y);
g.drawLine(x,y,x,y-length);
g.drawString(OX,x+length, y+15);
g.drawString(OY,x-15,y-length);
g.drawString("0", x -15,y);
g.drawString("0", x,y+15);
g.fillOval(x_num,y-y_height-2, 4 ,4);
}
public void setTitle(String name)
{
emri= name;
this.repaint();
}
public void setAxes(int x_pos, int y_pos, int axis_length, String x_label, String y_label)
{
x= x_pos;
y=y_pos;
length= axis_length;
OX = x_label;
OY = y_label;
}
public void setPoint1(int height)
{
y_height=height;
x_num = x-2;
this.repaint();
}
public void setPoint2(int height)
{
y_height=height;
x_num = x + length/5-2;
this.repaint();
}
}
and here is the main method:
public class TestPlot
{
public static void main(String[] a)
{
PointGraphWriter e = new PointGraphWriter();
e.setTitle("Graph of y = x*x");
e.setAxes(50, 110, 90, "5", "30");
int scale_factor = 3;
e.setPoint1(0 * scale_factor);
e.setPoint2(1 * scale_factor);
}
}
Please have a look at this example. Something in lines of this, you might have to incorporate in your example, to make it work. Simply use a Collection to store what you have previously painted, and when the new thingy comes along, simply add that thingy to the list, and repaint the whole Collection again. As shown below :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class RectangleExample {
private DrawingBoard customPanel;
private JButton button;
private Random random;
private java.util.List<Rectangle2D.Double> rectangles;
private ActionListener buttonActions =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Rectangle2D.Double rectangle = new Rectangle2D.Double(
(double) random.nextInt(100), (double) random.nextInt(100),
(double) random.nextInt(100), (double) random.nextInt(100));
rectangles.add(rectangle);
customPanel.setValues(rectangles);
}
};
public RectangleExample() {
rectangles = new ArrayList<Rectangle2D.Double>();
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Rectangle Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
customPanel = new DrawingBoard();
contentPane.add(customPanel, BorderLayout.CENTER);
button = new JButton("Create Rectangle");
button.addActionListener(buttonActions);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new RectangleExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawingBoard extends JPanel {
private java.util.List<Rectangle2D.Double> rectangles =
new ArrayList<Rectangle2D.Double>();
public DrawingBoard() {
setOpaque(true);
setBackground(Color.WHITE);
}
public void setValues(java.util.List<Rectangle2D.Double> rectangles) {
this.rectangles = rectangles;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rectangle2D.Double rectangle : rectangles) {
g.drawRect((int)rectangle.getX(), (int)rectangle.getY(),
(int)rectangle.getWidth(), (int)rectangle.getHeight());
}
System.out.println("WORKING");
}
}
See Custom Painting Approaches for examples of the two common ways to do painting:
Keep a List of the objects to be painted
Paint onto a BufferedImage
The approach you choose will depend on your exact requirement.
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();
}
}