Putting a border for moving square - java

So basically im just playing around with movement systems for different purposes and having trouble making square stop right at the edge. Square moves off the side of screen by around 50% of the square it self and i cannot figure out why it is like that.
package SnakeMovement;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SnakeMovement extends Canvas implements ActionListener, KeyListener {
Timer timer = new Timer(5, this);
int width, height;
int xSize = 50, ySize = 50;
int yPos = 0, xPos = 0, yVel = 0, xVel = 0;
public SnakeMovement(int w, int h) {
timer.start();
width = w;
height = h;
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
setFocusable(true);
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(xPos, yPos, xSize, ySize);
}
public void actionPerformed(ActionEvent e) {
xPos += xVel;
yPos += yVel;
if (xPos >= width - xSize) {
xPos = width - xSize;
xVel = 0;
}
repaint();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yVel = -10;
xVel = 0;
}
if (key == KeyEvent.VK_S) {
yVel = 10;
xVel = 0;
}
if (key == KeyEvent.VK_A) {
xVel = -10;
yVel = 0;
}
if (key == KeyEvent.VK_D) {
xVel = 10;
yVel = 0;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
I just want so square stops at each side of screen perfectly on the edge.

Try:
private static final int BORDER_SIZE = 1;
private static final Color RECT_COLOR = Color.BLUE, BORDER_COLOR = Color.RED;
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BORDER_COLOR);
g.fillRect(xPos, yPos, xSize, ySize);
g.setColor(RECT_COLOR);
g.fillRect(xPos+BORDER_SIZE, yPos+BORDER_SIZE, xSize-2*BORDER_SIZE, ySize-2*BORDER_SIZE);
}
The idea is to paint a full size rectangular using the border color.
Then painting a smaller one (smaller by 2*BORDER_SIZE) using the rectangular color.
The following is mre of the above:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class SnakeMovement extends Canvas implements ActionListener, KeyListener {
private static final int BORDER_SIZE = 1, DELAY = 100;
private static final Color RECT_COLOR = Color.BLUE, BORDER_COLOR = Color.RED;
private final int xSize = 50, ySize = 50;
private int yPos = 0, xPos = 0, yVel = 5, xVel = 5;
private final Timer timer = new Timer(DELAY, this);
public SnakeMovement(int width, int height) {
timer.start();
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
setFocusable(true);
setPreferredSize(new Dimension(width, height));
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BORDER_COLOR);
g.fillRect(xPos, yPos, xSize, ySize);
g.setColor(RECT_COLOR);
g.fillRect(xPos+BORDER_SIZE, yPos+BORDER_SIZE, xSize-2*BORDER_SIZE, ySize-2*BORDER_SIZE);
}
#Override
public void actionPerformed(ActionEvent e) {
xPos += xVel;
yPos += yVel;
checkLimits();
repaint();
}
//when canvas edge is reached emerge from the opposite edge
void checkLimits(){
//check x and y limits
if (xPos >= getWidth()) {
xPos = -xSize;
}
if (xPos < -xSize ) {
xPos = getWidth();
}
if (yPos >= getHeight() ) {
yPos = -ySize;
}
if (yPos < -ySize ) {
yPos = getHeight();
}
}
//two other behaviors when hitting a limit. uncomment the desired behavior
/*
//when canvas edge is reached change direction
void checkLimits(){
//check x and y limits
if ( xPos >= getWidth() - xSize || xPos <= 0) {
xVel = - xVel;
}
if ( yPos >= getHeight() - ySize || yPos <= 0) {
yVel = - yVel;
}
}
*/
/*
//when canvas edge is reached stop movement
void checkLimits(){
//check x and y limits
if ( xPos >= getWidth() - xSize || xPos <= 0 || yPos >= getHeight() - ySize || yPos <= 0) {
timer.stop();
}
}
*/
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yVel = -10;
xVel = 0;
}
if (key == KeyEvent.VK_S) {
yVel = 10;
xVel = 0;
}
if (key == KeyEvent.VK_A) {
xVel = -10;
yVel = 0;
}
if (key == KeyEvent.VK_D) {
xVel = 10;
yVel = 0;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args0) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SnakeMovement(500, 500));
frame.pack();
frame.setVisible(true);
}
}

Related

Better way to repaint the jframe

I'm building a project for college and I have several shapes in my frame and I need to do some operations with those objects. for example:
Figure fig = figs.get(figs.size() -1);
fig.mov(dx,dy);
figs.set(figs.size() -1, fig);
repaint();
I have a array of figures and every time I drag/move 1 figure, I have to update that array and also do repaint() and this is going to happen when one of the keyboard arrows get pressed.
My problem here is that despite the repaint() function being fast, when I make several moves of 1 object, the screen goes white several times, making it difficult to see. I don't know a lot of java and I don't have any ideas of how to solve this. I was wondering if anyone has any ideas to help me out, please.
Example:
figurestest/Figure.java
package figurestest;
import java.awt.Graphics;
public abstract class Figure {
public int x, y;
public int w, h;
public Figure (int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public abstract void paint (Graphics g);
public abstract void mov (int dx, int dy);
}
figurestest/rect.java
package figurestest;
import java.awt.*;
public class Rect extends Figure {
public Rect (int x, int y, int w, int h) {
super(x, y, w, h);
}
public void paint (Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(this.x, this.y, this.w, this.h);
g2d.drawRect(this.x,this.y, this.w,this.h);
}
public void mov (int dx, int dy){
this.x += dx;
this.y += dy;
}
}
testapp.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Random;
import figurestest.*;
class TestApp {
public static void main (String[] args) {
ListFrame frame = new ListFrame();
frame.setVisible(true);
}
}
class ListFrame extends JFrame {
ArrayList<Figure> figs = new ArrayList<Figure>();
Random rand = new Random();
ListFrame () {
this.addWindowListener (
new WindowAdapter() {
public void windowClosing (WindowEvent e) {
System.exit(0);
}
}
);
this.addKeyListener (
new KeyAdapter() {
public void keyPressed (KeyEvent evt) {
Dimension size = getContentPane().getSize();
int x = rand.nextInt(size.width);
int y = rand.nextInt(size.height);
int w = 5+ rand.nextInt(50);
int h = 5+ rand.nextInt(50);
if (evt.getKeyChar() == 'r') {
figs.add(new Rect(x,y, w,h));
}
else if (evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_LEFT || evt.getKeyCode() == KeyEvent.VK_RIGHT || evt.getKeyCode() == KeyEvent.VK_UP ) {
if (figs.size() > 0){
int dx = 0;
int dy = 0;
if(evt.getKeyCode() == KeyEvent.VK_DOWN) dy = 2;
else if (evt.getKeyCode() == KeyEvent.VK_UP){ dy = -2;}
else if (evt.getKeyCode() == KeyEvent.VK_RIGHT) dx = 2;
else if (evt.getKeyCode() == KeyEvent.VK_LEFT) dx = -2;
Figure fig = figs.get(figs.size() -1);
fig.mov(dx,dy);
figs.set(figs.size() -1, fig);
}
}
repaint();
}
}
);
this.setTitle("Figures");
this.setSize(350, 350);
}
public void paint (Graphics g) {
super.paint(g);
for (Figure fig: this.figs) {
fig.paint(g);
}
}
}
You're making some strange mistakes. Don't extend JFrame it is pointless in this case.
Here is a start. You should probably use something other than a key listener, and make an action instead for the input map instead.
class ListFrame {
ArrayList<Figure> figs = new ArrayList<Figure>();
Random rand = new Random();
ListFrame () {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel custom = new JPanel(){
#Override
public void paintComponent(Graphics g) {
super.paint(g);
for (Figure fig: figs) {
fig.paint(g);
}
}
#Override
public Dimension getPreferredSize(){
//you custom component should know it's preferred size.
return new Dimension(350, 350);
}
};
frame.addKeyListener (
new KeyAdapter() {
public void keyPressed (KeyEvent evt) {
Dimension size = custom.getSize();
int x = rand.nextInt(size.width);
int y = rand.nextInt(size.height);
int w = 5+ rand.nextInt(50);
int h = 5+ rand.nextInt(50);
if (evt.getKeyChar() == 'r') {
figs.add(new Rect(x,y, w,h));
}
else if (evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_LEFT || evt.getKeyCode() == KeyEvent.VK_RIGHT || evt.getKeyCode() == KeyEvent.VK_UP ) {
if (figs.size() > 0){
int dx = 0;
int dy = 0;
if(evt.getKeyCode() == KeyEvent.VK_DOWN) dy = 2;
else if (evt.getKeyCode() == KeyEvent.VK_UP){ dy = -2;}
else if (evt.getKeyCode() == KeyEvent.VK_RIGHT) dx = 2;
else if (evt.getKeyCode() == KeyEvent.VK_LEFT) dx = -2;
Figure fig = figs.get(figs.size() -1);
fig.mov(dx,dy);
//You don't need to set the value. You modified it.
//figs.set(figs.size() -1, fig);
}
}
custom.repaint();
}
}
);
frame.setContentPane(custom);
frame.pack();
frame.setTitle("Figures");
frame.setVisible(true);
}
}

How to move circle with arrow keys?

I want to move a white circle on a black background using left and right arrow keys. The KeyListener is working (using System.out.print) but the circle does not move when keys are pressed. I think it has to do with the x & y positions (xPos, yPos).
private static final int SPEED = 50, BALL_SIZE = 50;
private int dx;
private int xPos, yPos;
public Background() {
addKeyListener(this);
setBackground(Color.BLACK);
// the starting point of ball
xPos = 100;
yPos = 700;
dx = SPEED;
}
#Override
public void actionPerformed(ActionEvent e) {
// screen size
int width = getWidth();
xPos += dx;
// boundaries
if (xPos < 100) {
xPos = 100;
dx = SPEED;
}
else if (xPos > width - BALL_SIZE) {
xPos = width - BALL_SIZE;
dx = -SPEED;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) { // right arrow key
dx++;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) { // left arrow key
dx--;
}
else if (e.getKeyCode() == KeyEvent.VK_SPACE) { // space bar
// shoot laser!
}
System.out.println("After");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillOval(xPos, yPos, BALL_SIZE, BALL_SIZE);
}

Keylistener not running

This is my code, I have a key listener however it does do what it is supposed to do when the key is pressed. The shape moves as it should in the ActionListener however when I press one of the keys it does nothing.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class Snake extends JPanel implements ActionListener {
Timer t = new Timer(5, this);
double x = 0 , y = 0, xVel = 2, yVel = 2;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
g2.fill(circle);
t.start();
}
public void actionPerformed(ActionEvent e){
if(x < 0 || x >460)
{
xVel = -xVel;
}
if(y < 0 || y > 459)
{
yVel = -yVel;
}
x += xVel;
y += yVel;
repaint();
}
public void keyPressed(KeyEvent e) //This part of the Code Doesnt seem to be running
{
int key = e.getKeyCode();
if( key == KeyEvent.VK_DOWN)
{
yVel = yVel; //There may be something wrong with the way i wrote this
xVel = 0;
}
if(key == KeyEvent.VK_UP)
{
yVel = -yVel;
xVel = 0;
}
if(key == KeyEvent.VK_RIGHT)
{
xVel = xVel;
yVel = 0;
}
if(key == KeyEvent.VK_LEFT)
{
xVel = -xVel;
yVel =0;
}
x+= xVel;
y+= yVel;
repaint();
}
}
It appears as though you haven't implemented the KeyListener interface. You're going to want to add that to your implements ActionListener, KeyListener and then register the the class for the KeyListener as well as implement the methods provided by the KeyListener interface.
For more information on KeyListener look at this link
I'm currently working on a similar project, how I do it:
1) Implement KeyListener (can't recall if that is the exact name*)
2) addKeylistener(this)
3) Write the method which you have already done.
*Might be KeyboardListener
You need to .addKeyListener to your frame. So where ever you created your frame you need to add this:
JFrame frame = new JFrame();
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if( key == KeyEvent.VK_DOWN)
{
yVel = 2;
xVel = 0;
}
if(key == KeyEvent.VK_UP)
{
yVel = -2;
xVel = 0;
}
if(key == KeyEvent.VK_RIGHT)
{
xVel = 2;
yVel = 0;
}
if(key == KeyEvent.VK_LEFT)
{
xVel = -2;
yVel =0;
}
x+= xVel;
y+= yVel;
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
});
Snake snake = new Snake();
frame.add(snake);
frame.setSize(500, 500);
frame.setVisible(true);

Java Applet MouseListener not working

I thought I programmed it so that when I click on the 'Start' button that appears when it is not level 1 or higher, it would go to level 1. But nothing happens when I click it.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.awt.Font;
public class Move extends Applet implements KeyListener, MouseListener {
private Rectangle rect;
private ArrayList<Integer> keysDown;
Random randomGenerator = new Random();
int speed = 4;
int level = 0;
int xpos;
int ypos;
boolean startClicked;
Image block;
Image start;
URL base;
MediaTracker mt;
int randomx = randomGenerator.nextInt(560);
int randomy = randomGenerator.nextInt(360);
public void init() {
this.addKeyListener(this);
this.addMouseListener(this);
keysDown = new ArrayList<Integer>();
rect = new Rectangle(0, 0, 50, 50); ///////////////////////////////////you can use rect.getX();
mt = new MediaTracker(this);
try {
base = getDocumentBase();
}
catch (Exception e) {}
block = getImage(base, "block.gif");
start = getImage(base, "start_button.png");
mt.addImage(block, 1);
try {
mt.waitForAll();
}
catch (InterruptedException e) {}
}
public void paint(Graphics g) {
setSize(600, 400);
Graphics2D g2 = (Graphics2D)g;
if (level != 0) {
g2.fill(rect);
//g.drawImage(block, randomx, randomy, this); ###############################fhjvhfjvkjerhgvgf
Font font = new Font("Arial", Font.BOLD, 18);
g.setFont(font);
String text = "Speed: " + speed;
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = (getHeight() - fm.getHeight()) + fm.getAscent();
g.drawString(text, x, y);
}
else { // start menu
g.drawImage(start, 160, 160, this);
}
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
moveRect();
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void moveRect() {
if (level != 0) {
int x = rect.x;
int y = rect.y;
if (keysDown.contains(KeyEvent.VK_UP)) {
y -= speed;
}
if (keysDown.contains(KeyEvent.VK_DOWN)) {
y += speed;
}
if (keysDown.contains(KeyEvent.VK_LEFT)) {
x -= speed;
}
if (keysDown.contains(KeyEvent.VK_RIGHT)) {
x += speed;
}
rect.setLocation(x, y);
repaint();
if (x-32 > randomx-72 && y+64 > randomy && x-32 < randomx+72 && y-64 < randomy) { /// will be flag
randomx = randomGenerator.nextInt(560);
randomy = randomGenerator.nextInt(360);
speed += 4;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void mouseClicked(MouseEvent me) {
if (level == 0) {
xpos = me.getX();
ypos = me.getY();
if (xpos > 160 && ypos > 96 && xpos < 400 && ypos < 160) {
level = 1;
}
}
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
}
Thanks again for all the help! This will HOPEFULLY turn out to be a maze game...
PS: ignore the pointless comments.
You are drawing at
g.drawImage(start, 160, 160, this);
But checking for
if (xpos > 160 && ypos > 96 && xpos < 400 && ypos < 160) {
Change that to
if (xpos >= 160 && ypos > 159 && xpos < 400 && ypos < 190) {
Better yet make constants of these numbers or use an ImageIcon and add a listener to it.
public static final int START_X_POS = 160;
public static final int START_Y_POS = 160;
public static final int START_WIDTH = 30;
public static final int START_HEIGHT = 150;
//...
if (xpos >= (START_X_POS ) && ypos >= START_Y_POS && xpos <= ( START_X_POS + START_WIDTH) && ypos <= (START_X_POS + START_HEIGHT )) {

how to space out random circles across a JPanel when using an array

I am trying to draw 7 random circles across a JPanel using an array. I managed to get the array to work but now I am having trouble spacing out the circles. When i run the program i see multiple circles being drawn but they are all on the same spot. All the circles are of different size and color. The other problem i have is making the circles move towards the bottom of the screen.
public class keyExample extends JPanel implements ActionListener, KeyListener{
private Circle[] circles = new Circle[7];
Timer t = new Timer(5,this);
//current x and y
double x = 150, y = 200;
double changeX = 0, changeY = 0;
private int circlex = 0,circley = 0; // makes initial starting point of circles 0
private javax.swing.Timer timer2;
public keyExample(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
NewCircle();
timer2 = new javax.swing.Timer(33,new MoveListener());
timer2.start();
}
public void NewCircle(){
Random colors = new Random();
Color color = new Color(colors.nextInt(256),colors.nextInt(256),colors.nextInt(256));
Random num= new Random();
int radius = num.nextInt(45);
for (int i = 0; i < circles.length; i++)
circles[i] = new Circle(circlex,circley,radius,color);
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,y,40,40));
for (int i = 0; i < circles.length; i++)
circles[i].fill(g);
}
public void actionPerformed(ActionEvent e){
repaint();
x += changeX;
y += changeY;
changeX = 0;
changeY = 0;
}
public void up() {
if (y != 0){
changeY = -3.5;
changeX = 0;
}
}
public void down() {
if (y <= 350){
changeY = 3.5;
changeX = 0;
}
}
public void left() {
if (x >= 0) {
changeX = -3.5;
changeY = 0;
}
}
public void right() {
if (x <= 550) {
changeX = 3.5;
changeY = 0;
}
}
private class MoveListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
Random speed = new Random();
int s = speed.nextInt(8);
}
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
if (code == KeyEvent.VK_LEFT){
left();
}
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
}
Circle class
import java.awt.*;
public class Circle{
private int centerX, centerY, radius, coord;
private Color color;
public Circle(int x, int y, int r, Color c){
centerX = x;
centerY = y;
radius = r;
color = c;
}
public void draw(Graphics g){
Color oldColor = g.getColor();
g.setColor(color);
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
g.setColor(oldColor);
}
public void fill(Graphics g){
Color oldColor = g.getColor();
g.setColor(color);
g.fillOval(centerX - radius, centerY - radius, radius *2, radius * 2);
g.setColor(oldColor);
}
public boolean containsPoint(int x, int y){
int xSquared = (x - centerX) * (x - centerX);
int ySquared = (y - centerY) * (y - centerY);
int RadiusSquared = radius * radius;
return xSquared + ySquared - RadiusSquared <=0;
}
public void move(int xAmount, int yAmount){
centerX = centerX + xAmount;
centerY = centerY + yAmount;
}
}
This is one of the problems with relying on borrowed code that you don't understand...
Basically, all you need to do is change the creation of the circles, for example...
for (int i = 0; i < circles.length; i++) {
circles[i] = new Circle(circlex, circley, radius, color);
circlex += radius;
}
You may wish to re-consider the use of KeyListener, in favour of Key Bindings before you discover that KeyListener doesn't work the way you expect it to...
For some strange reason, you're calling NewCirlces from within the MoveListener's actionPerfomed method, meaning that the circles are simply being re-created on each trigger of the Timer...instead, call it first in the constructor
You're also calling within your paintComponent method...this should mean that the circles never move and instead, random change size...
Updated with runnable example...
I modified your paint code NewCircle and the MoveListener a little...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CircleExample extends JPanel implements ActionListener, KeyListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CircleExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Circle[] circles = new Circle[7];
Timer t = new Timer(5, this);
//current x and y
double x = 150, y = 200;
double changeX = 0, changeY = 0;
private int circlex = 0, circley = 0; // makes initial starting point of circles 0
private javax.swing.Timer timer2;
public CircleExample() {
NewCircle();
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer2 = new javax.swing.Timer(33, new MoveListener());
timer2.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public void NewCircle() {
for (int i = 0; i < circles.length; i++) {
Random colors = new Random();
Color color = new Color(colors.nextInt(256), colors.nextInt(256), colors.nextInt(256));
Random num = new Random();
int radius = num.nextInt(90);
circles[i] = new Circle(circlex, circley, radius, color);
circlex += radius;
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(new Rectangle2D.Double(x, y, 40, 40));
for (int i = 0; i < circles.length; i++) {
circles[i].fill(g);
}
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
x += changeX;
y += changeY;
changeX = 0;
changeY = 0;
}
public void up() {
if (y != 0) {
changeY = -3.5;
changeX = 0;
}
}
public void down() {
if (y <= 350) {
changeY = 3.5;
changeX = 0;
}
}
public void left() {
if (x >= 0) {
changeX = -3.5;
changeY = 0;
}
}
public void right() {
if (x <= 550) {
changeX = 3.5;
changeY = 0;
}
}
private class MoveListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Random speed = new Random();
for (Circle circle : circles) {
int s = speed.nextInt(8);
circle.move(0, s);
}
repaint();
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
up();
}
if (code == KeyEvent.VK_DOWN) {
down();
}
if (code == KeyEvent.VK_RIGHT) {
right();
}
if (code == KeyEvent.VK_LEFT) {
left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public class Circle {
private int centerX, centerY, radius, coord;
private Color color;
public Circle(int x, int y, int r, Color c) {
centerX = x;
centerY = y;
radius = r;
color = c;
}
public void draw(Graphics g) {
Color oldColor = g.getColor();
g.setColor(color);
g.drawOval(centerX, centerY, radius, radius);
g.setColor(oldColor);
}
public void fill(Graphics g) {
Color oldColor = g.getColor();
g.setColor(color);
g.fillOval(centerX, centerY, radius, radius);
g.setColor(oldColor);
}
public boolean containsPoint(int x, int y) {
int xSquared = (x - centerX) * (x - centerX);
int ySquared = (y - centerY) * (y - centerY);
int RadiusSquared = radius * radius;
return xSquared + ySquared - RadiusSquared <= 0;
}
public void move(int xAmount, int yAmount) {
centerX = centerX + xAmount;
centerY = centerY + yAmount;
}
}
}

Categories

Resources