I have some code that makes 273 black squires on the screen but yet they only show up for a second. I know its something wrong with the repaint but i can't find it.
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.*;
public class Start extends Applet implements Runnable, KeyListener
{
public boolean running = true;
int fall = 60;
int count = 0;
Thread thread;
private Image i;
private Graphics doubleG;
Brick b[] = new Brick[273];//abtsert class
public int[] x = {270,300,330,360,390,420,450,480,510,540,570,600,630};
public int[] y = {-10,20,50,80,110,140,170,200,230,260,290,320,350,380,410,440,470,500,530,560,590,620,650};
public boolean[] bl = {false,true};
public int[] color = {0,1,2,3,4};
public int xc = 0;//indx of x
public int yc = 0;//indx of y
public int indx = 0;//indx of b
public int start = 0;
public void init()
{
Arrays.fill(b,new Background());
addKeyListener(this);
setFocusable(true);
thread = new Thread(this);
thread.start();
}
public void run()
{
while(running)
{
try
{
thread.sleep(17);
}
catch(InterruptedException e)
{
}
repaint();
}
}
public void paint(Graphics g)
{
resize(700,700);
if(start == 0)
{
set(g);//sets fills b with objects
start = 1;
}
else//prints out the abjects stored in b[]
{
while(indx != 273)
{
b[indx].paint(g);
indx++;
}
indx=0;
}
g.drawRect(300,50,300,600);
}
public void update(Graphics g)
{
if(i == null)
{
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
}
doubleG.setColor(getBackground());
doubleG.fillRect(0,0,700,700);
doubleG.setColor(getForeground());
paint(doubleG);
g.drawImage(i,0,0,this);
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == e.VK_LEFT)
{
}
if(e.getKeyCode() == e.VK_RIGHT)
{
}
repaint();
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void set(Graphics g)
{
while(yc <= 22)
{
b[indx].start(g,x[xc],y[yc]);
if(xc <= 12)
{
xc++;
}
if(xc == 12)
{
yc++;
xc=0;
}
indx++;
}
yc=0;
indx=0;
}
}
this is the abstract class
import java.applet.*;
import java.util.*;
import java.awt.*;
public abstract class Brick
{
public int px;
public int py;
public abstract void paint(Graphics g);
public abstract void start(Graphics g ,int x ,int y);
}
this is the class that uses the abstract class
import java.applet.*;
import java.util.*;
import java.awt.*;
public class Background extends Brick//thing thats being painted
{
public int px;//where the x,y are stored
public int py;
public void paint(Graphics g)//used to repaint it
{
g.setColor(Color.BLACK);
g.fillRect(px,py,29,29);
}
public void start(Graphics g,int x, int y)//used to set the object
{
g.setColor(Color.BLACK);
g.fillRect(x,y,29,29);
px = x;
py = y;
}
}
Related
I want it so when my player goes off the platform, (in checkCollision() method PlatformerPanel class) it will fall and then do something when gone off the screen, i haven't set up an end game screen yet but that's what I'm planning to do. Anyway, the problem is that it goes way too fast for some reason and falls too early, and also when an arrow key is pressed while its falling it will go back up to the platform.
Please try to help me overcome this or think of a new, easy to understand, way to do this/make this work the way i am planning.
EDIT 1:
I fixed the thing where it falls too early so don't worry about that
```
public class PlatformerMain {
public static void main(String[] args) {
PlatformerGameFrame platformerGame = new PlatformerGameFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGameFrame extends JFrame{
PlatformerGamePanel panel;
PlatformerGameFrame() {
panel = new PlatformerGamePanel();
this.add(panel);
this.setTitle("Platformer Game");
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
this.getContentPane().setBackground(new Color(0,0,0));
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerGamePanel extends JPanel implements Runnable{
PlatformerPlayer player1;
PlatformerMap map1;
static final int SCREEN_WIDTH = 1000;
static final int SCREEN_HEIGHT = 600;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 60;
static final Dimension SCREEN_SIZE = new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT);
static boolean falling = false;
Image backgroundImage;
Thread gameThread;
Image image;
Graphics graphics;
PlatformerMap map;
public PlatformerGamePanel() {
java.net.URL imgIcon = Main.class.getResource(
"/Resources/spaceImage.jpg");
backgroundImage = new ImageIcon(imgIcon).getImage();
newPlayer();
newMap();
this.setFocusable(true);
this.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
player1.KeyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
player1.KeyReleased(e);
}
});
this.setPreferredSize(SCREEN_SIZE);
this.setOpaque(true);
gameThread = new Thread(this);
gameThread.start();
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
draw(graphics);
g.drawImage(image, 0,0, null);
}
public void draw(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(backgroundImage, 0,0, null);
player1.paint(g);
map.paint(g);
}
public void newPlayer() {
player1 = new PlatformerPlayer((SCREEN_WIDTH/2)-(PLAYER_WIDTH/2), (SCREEN_HEIGHT/2)-(PLAYER_WIDTH/2), PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void newMap() {
map = new PlatformerMap();
}
public void checkCollision() {
if(player1.x > SCREEN_WIDTH-PLAYER_WIDTH) {
player1.x = SCREEN_WIDTH-PLAYER_WIDTH;
}
else if(player1.x < 0) {
player1.x = 0;
}
if(!(player1.x >map.PLATFORM_WIDTH)) {
if(player1.y > SCREEN_HEIGHT-250) {
player1.y = SCREEN_HEIGHT-250;
}
} else if(player1.x > map.PLATFORM_WIDTH) {
gravity();
}
}
public void falling() {
}
public void gravity() {
player1.gravity();
}
public void move() {
player1.move();
}
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 120.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now - lastTime)/ns;
lastTime = now;
if(delta >= 1) {
move();
checkCollision();
gravity();
repaint();
delta--;
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerPlayer extends Rectangle {
/*static int playerPosX = 100;
static int playerPosY = 100;*/
static double velocityY = 0;
static double velocityX = 0;
static int vertical_position;
static final int TERMINAL_VELOCITY = 200;
static final int PLAYER_WIDTH = 50;
static final int PLAYER_HEIGHT = 50;
static int speed = 2;
protected boolean falling = true;
protected boolean jumping = false;
double gravity = 0.05;
public PlatformerPlayer(int x, int y, int PLAYERWIDTH, int PLAYERHEIGHT) {
super(x,y,PLAYERWIDTH,PLAYERHEIGHT);
}
public void KeyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(-speed);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(speed);
move();
}
}
public void KeyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT) {
setXDirection(0);
move();
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
setXDirection(0);
move();
}
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.red);
g2D.fillRect(x, y, PLAYER_WIDTH, PLAYER_HEIGHT);
}
public void setYDirection(int YDirection) {
velocityY = YDirection;
}
public void setXDirection(int XDirection) {
if(speed > 10) {
speed = 10;
}
velocityX = XDirection;
}
public void move() {
y += velocityY;
x += velocityX;
}
public void gravity() {
velocityY += gravity;
if (velocityY > TERMINAL_VELOCITY)
{
velocityY = TERMINAL_VELOCITY;
}
vertical_position -= velocityY;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PlatformerMap extends Rectangle {
int PLATFORM_WIDTH = 600;
int PLATFORM_HEIGHT = 150;
public PlatformerMap() {
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.gray);
g2D.fillRect(100,400,PLATFORM_WIDTH,PLATFORM_HEIGHT);
}
}
When I drag the shapes that I drew, I want to move.
but I do not know how to do it.
I have tried the make move method in GPanel but could not make it.
knowledge.
I have been working on this for almost 1 week and tried all the solutions that I could think of.
This is my first time posting a code question on stack overflow.
I do really want to learn.
. And love you all.
I hope one day I could be a savior for code newbies
Have to use affine transform
this is drawing page
package frame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Vector;
import javax.swing.JPanel;
import main.GConstants.EAnchorLocation;
import main.GConstants.EDrawingStyle;
import shapeTool.GShapeTool;
public class GPanel extends JPanel {
private static final long serialVersionUID = 1L;
private GShapeTool shapeTool;
private GShapeTool selectedShape;
private Vector<GShapeTool> shapes;
public GPanel() {
this.setBackground(Color.WHITE);
this.shapes = new Vector<GShapeTool>();
MouseHandler mouseHandler = new MouseHandler();
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
this.addMouseWheelListener(mouseHandler);
}
public void initialize() {}
public Vector<GShapeTool> getShapes() {
return this.shapes;
}
public void setShapes(Vector<GShapeTool> shapes){
this.shapes = shapes;
this.updateUI();
}
public void paint(Graphics graphics) {
super.paint(graphics);
for(GShapeTool shape: this.shapes) {
shape.draw((Graphics2D)graphics);
}
}
public void setShapeTool(GShapeTool shapeTool) {
this.shapeTool = shapeTool;
}
private boolean onShape(int x, int y) {
boolean shapeCheck = false;
for(GShapeTool shapeTool: this.shapes) {
if(shapeTool.contains(x, y)) {
this.selectedShape = shapeTool;
shapeCheck = true;
} else {
shapeTool.setSelected(false, (Graphics2D)getGraphics());
}
}
if(shapeCheck) {
this.selectedShape.setSelected(true, (Graphics2D)getGraphics());
}
return shapeCheck;
}
private void setInitialPoint(int x, int y) {
this.selectedShape = this.shapeTool.clone();
this.selectedShape.setInitialPoint(x, y);
}
private void setFinalPoint(int x, int y) {
for(GShapeTool shapeTool: this.shapes) {
shapeTool.setSelected(false, (Graphics2D)getGraphics());
}
// Graphics2D graphics2D = (Graphics2D) this.getGraphics();
//set xor mode;
// graphics2D.setXORMode(getBackground());
this.selectedShape.setFinalPoint(x, y);
this.selectedShape.setSelected(true, (Graphics2D)getGraphics());
this.shapes.add(this.selectedShape);
}
private void setIntermediatePoint(int x, int y) {
this.selectedShape.setIntermediatePoint(x, y);
}
private void animate(int x, int y) {
Graphics2D graphics2D = (Graphics2D) this.getGraphics();
//set xor mode;
graphics2D.setXORMode(getBackground());
this.selectedShape.animate(graphics2D, x, y);
}
private class MouseHandler
implements MouseListener, MouseMotionListener, MouseWheelListener {
private boolean isDrawing;
MouseHandler() {
this.isDrawing = false;
}
#Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
if(e.getClickCount() == 1) {
this.mouseLButton1Clicked(e);
} else if(e.getClickCount() == 2) {
this.mouseLButton2Clicked(e);
}
} else if(e.getButton() == MouseEvent.BUTTON2) {
if(e.getClickCount() == 1) {
this.mouseRButton1Clicked(e);
}
}
}
#Override
public void mouseMoved(MouseEvent e) {
if(isDrawing) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {
animate(e.getX(), e.getY());
}
}
}
private void mouseLButton1Clicked(MouseEvent e) {
if(!this.isDrawing) {
if(!onShape(e.getX(), e.getY())) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {
setInitialPoint(e.getX(), e.getY());
this.isDrawing = true;
}
}
else if(onShape(e.getX(), e.getY())) {
onShape(e.getX(), e.getY());
}
} else {
if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {
setIntermediatePoint(e.getX(),e.getY());
}
}
}
private void mouseLButton2Clicked(MouseEvent e) {
if(this.isDrawing) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {
setFinalPoint(e.getX(), e.getY());
this.isDrawing = false;
}
}
}
private void mouseRButton1Clicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
if(!this.isDrawing) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {
setInitialPoint(e.getX(), e.getY());
this.isDrawing = true;
}
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if(this.isDrawing) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {
animate(e.getX(), e.getY());
}
}
}
#Override
public void mouseReleased(MouseEvent e) {
if(this.isDrawing) {
if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {
setFinalPoint(e.getX(), e.getY());
this.isDrawing = false;
}
}
}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {}
}
}
this is abstract class for shapes
package shapeTool;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Ellipse2D.Double;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Vector;
import main.GConstants.EAnchorLocation;
import main.GConstants.EDrawingStyle;
public abstract class GShapeTool implements Serializable {
private static final long serialVersionUID = 1L;
public enum EAnchors {
x0y0,
x0y1,
x0y2,
x1y0,
x1y2,
x2y0,
x2y1,
x2y2,
RR;
}
public final static int wAnchor = 10;
public final static int hAnchor = 10;
private EDrawingStyle eDrawingStyle;
protected boolean isSelected;
protected Shape shape;
private Ellipse2D[] anchors;
public GShapeTool(EDrawingStyle eDrawingStyle) {
this.eDrawingStyle = eDrawingStyle;
this.isSelected = false;
this.anchors = new Ellipse2D.Double[EAnchors.values().length];
for(EAnchors eAnchor: EAnchors.values()) {
this.anchors[eAnchor.ordinal()] = new Ellipse2D.Double();
}
}
public EDrawingStyle getDrawingStyle() {
return this.eDrawingStyle;
}
public boolean contains(int x, int y) {
return this.shape.contains(x , y);
}
private void drawAnchors(Graphics2D graphics2D) {
// draw bounding rectangle
Rectangle rectangle = this.shape.getBounds();
int x0 = rectangle.x-wAnchor;
int x1 = rectangle.x + rectangle.width/2;
int x2 = rectangle.x + rectangle.width;
int y0 = rectangle.y-hAnchor;
int y1 = rectangle.y + rectangle.height/2;
int y2 = rectangle.y + rectangle.height;
this.anchors[EAnchors.x0y0.ordinal()].setFrame(x0,y0,wAnchor,hAnchor);
this.anchors[EAnchors.x0y1.ordinal()].setFrame(x0,y1,wAnchor,hAnchor);
this.anchors[EAnchors.x0y2.ordinal()].setFrame(x0,y2,wAnchor,hAnchor);
this.anchors[EAnchors.x1y0.ordinal()].setFrame(x1,y0,wAnchor,hAnchor);
this.anchors[EAnchors.x1y2.ordinal()].setFrame(x1,y2,wAnchor,hAnchor);
this.anchors[EAnchors.x2y0.ordinal()].setFrame(x2,y0,wAnchor,hAnchor);
this.anchors[EAnchors.x2y1.ordinal()].setFrame(x2,y1,wAnchor,hAnchor);
this.anchors[EAnchors.x2y2.ordinal()].setFrame(x2,y2,wAnchor,hAnchor);
this.anchors[EAnchors.RR.ordinal()].setFrame(x1,y0-50,wAnchor,hAnchor);
//draw anchors
graphics2D.setColor(Color.BLACK);
for(EAnchors eAnchor: EAnchors.values()) {
graphics2D.draw(this.anchors[eAnchor.ordinal()]);
}
}
private void eraseAnchors(Graphics2D graphics2D) {
graphics2D.setColor(Color.WHITE);
for(EAnchors eAnchor: EAnchors.values()) {
graphics2D.draw(this.anchors[eAnchor.ordinal()]);
}
}
public void setSelected(boolean isSelected, Graphics2D graphics2D) {
if(this.isSelected) {
if(!isSelected) {
//erase
this.eraseAnchors(graphics2D);
}
} else {
if(isSelected) {
//draw
this.drawAnchors(graphics2D);
}
}
this.isSelected = isSelected;
}
public void draw(Graphics2D graphics) {
graphics.draw(this.shape);
}
public void animate(Graphics2D graphics2d, int x, int y) {
//erase;
this.draw(graphics2d);
// //move point
this.movePoint(x,y);
// //draw;
this.draw(graphics2d);
}
//interface
public abstract GShapeTool clone();
public abstract void setInitialPoint(int x, int y);
public abstract void setFinalPoint(int x, int y);
public abstract void setIntermediatePoint(int x, int y);
public abstract void movePoint(int x, int y);
}
and this is shape class that extends GShapeTool
package shapeTool;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import main.GConstants.EDrawingStyle;
public class GRectangle extends GShapeTool {
//attributes
private static final long serialVersionUID = 1L;
//components
//constructor
public GRectangle() {
super(EDrawingStyle.e2PointDrawing);
this.shape = new Rectangle();
}
#Override
public GShapeTool clone() {
GShapeTool cloned = new GRectangle();
return cloned;
}
// methods
#Override
public void setInitialPoint(int x, int y) {
Rectangle rectangle = (Rectangle) this.shape;
rectangle.setLocation(x, y);
rectangle.setSize(0, 0);
}
#Override
public void setIntermediatePoint(int x, int y) {
// TODO Auto-generated method stub
}
#Override
public void setFinalPoint(int x, int y) {
}
#Override
public void movePoint(int x, int y) {
Rectangle rectangle = (Rectangle) this.shape;
rectangle.setSize(x-rectangle.x, y-rectangle.y);
}
}
You should get a dragstart event. That is when you save the mouse position and the selected object(s).
When you get a dragfinished event, again note the mouse positon and move the objects accordingly. The move might just happen on the screen, but e.g. in case the drop occurred on the trashcan you want to delete them.
Now while the drag is active you might get a number of more dragging events, which you should use to update the screen and give feedback to the user. This would most of the time just be to look at the mouse positon and the selected objects and draw them accordingly.
This question already has answers here:
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 5 years ago.
When VK_UP or VK_DOWN is pressed the Graphic g I created is not changing its position whatsoever. If someone could look and see if there is something wrong with my move method etc. Would really appreciate it.
Here is all my code so far:
package ping2;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ping2 extends Applet implements Runnable, KeyListener{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
UserPaddle user1;
public void init() {
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
user1 = new UserPaddle(1);
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
user1.draw(g);
}
public void update(Graphics g) {
paint(g);
}
public void run() {
for(;;) {
user1.move();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(true);
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(false);
}
}
public void keyTyped(KeyEvent arg0) {
}
}
package ping2;
import java.awt.*;
public class UserPaddle implements InterfaceBar{
double y, yVelocity;
boolean upAccel, downAccel;
int player1, x;
final double FRICTION = 0.90;
public UserPaddle(int player1) {
upAccel = false;
downAccel = false;
y = 210;
yVelocity = 0;
if(player1 == 1)
x = 20;
else
x = 660;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int)y, 20, 80);
}
public void move() {
if(upAccel) {
yVelocity -= 2;
}else if(downAccel) {
yVelocity += 2;
}
//Automatically slows bar down if key not being pressed.
else if(!upAccel && !downAccel) {
yVelocity *= FRICTION;
}
}
public void setUpAccel(boolean input) {
upAccel = input;
}
public void setDownAccel(boolean input) {
downAccel = input;
}
public int getY() {
return (int)y;
}
}
package ping2;
import java.awt.Graphics;
public interface InterfaceBar {
public void draw(Graphics g);
public void move();
public int getY();
}
I have modified your move() a bit give it a try
move()
public void move() {
if(upAccel) {
yVelocity -= 2;
y = yVelocity;
}else if(downAccel) {
yVelocity += 2;
y = yVelocity;
}
}
I have a project that a circle goes with random x and y values and with selected colors but when the user pressed the space bar the color of the circle must be changed. My circle moves both x and y coordinate and I want to change the color of the circle when I press the space button. But it does not work when I pressed it. It goes with its original color. So how can I make this code right?
public class c {
private int x,y,r;
private Color co;
private int Re,G,B;
private Random ran;
public c() {
// TODO Auto-generated constructor stub
ran= new Random();
x=100;
y=50;
r= ran.nextInt(200)+50;
Re=ran.nextInt(255);
G=ran.nextInt(255);
B=ran.nextInt(255);
co= new Color(Re,G,B);
}
public int getRe() {
return Re;
}
public int getG() {
return G;
}
public int getB() {
return B;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getR() {
return r;
}
public void setCo(int Re,int G,int B) {
co= new Color(Re,G,B);
}
public Color getCo() {
return co;
}
public Random getRan() {
return ran;
}
public void setX(int x) {
this.x=x;
}
public void setY(int y) {
this.y=y;
}
}
public class Circle extends JFrame implements ActionListener,KeyListener{
private Timer timer;
private int x,y,a=5,b=5;
private Random rand;
c circ = new c();
public Circle() {
setLayout(new BorderLayout());
x=circ.getX();
y=circ.getY();
timer=new Timer(50,this);
timer.start();
addKeyListener(this);
setSize(550,550);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x,y,100,100);
g.setColor(circ.getCo());
}
public static void main(String[]args) {
new Circle();
}
#Override
public void actionPerformed(ActionEvent e) {
moveWithTimer();
repaint();
}
public void moveWithTimer() {
x=x+b;
y=y+a;
if(x<0) {
b=5;
}
if(x+50>500) {
b=-5;
}
if(y<0){
a=5;
}
if(y+50>500) {
a=-5;
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==e.VK_SPACE) {
circ.setCo(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255));
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
But it does not work when I pressed it. It goes with its original color. So how can I make this code right?
KeyListener is fickle, better to use the Key Bindings API which overcomes the primary, focus related, issues of KeyListener
As a general rule of thumb, you shouldn't override paint of top level containers like JFrame, they are compound components and it's just a real mess.
Instead, start with a JPanel and override it's paintComponent method. It's generally more flexible. Have a look at Performing Custom Painting for more details.
Your movement code is wrong. You assign the x/y values of the circle class to some other variables, the problem here is, changing the values of these variables will have no affect on the variables in you circle class, instead, you need assign them back...
public void moveWithTimer() {
int x = circ.getX();
int y = circ.getY();
x = x + b;
y = y + a;
if (x < 0) {
b = 5;
}
if (x + 50 > 500) {
b = -5;
}
if (y < 0) {
a = 5;
}
if (y + 50 > 500) {
a = -5;
}
circ.setX(x);
circ.setY(y);
}
Your "circle" class could also use a couple of additional methods. One to randomise the color (it already has a Random object, might as well use it) and one to paint the object.
public class Circle {
//...
public void paint(Graphics2D g2d) {
g2d.setColor(co);
g2d.fillOval(x, y, r * 2, r * 2);
}
//...
public void randomColor() {
setCo(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255));
}
//...
}
If it was me, I'd be tempted to add a move method as well, but that's me ;)
As a runnable example...
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.util.Random;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Timer timer;
private int a = 5, b = 5;
private Random rand;
private Circle circ = new Circle();
public TestPane() {
timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
moveWithTimer();
repaint();
}
});
timer.start();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
am.put("spaced", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
circ.randomColor();
repaint();
}
});
}
public void moveWithTimer() {
int x = circ.getX();
int y = circ.getY();
x = x + b;
y = y + a;
if (x < 0) {
b = 5;
}
if (x + 50 > 500) {
b = -5;
}
if (y < 0) {
a = 5;
}
if (y + 50 > 500) {
a = -5;
}
circ.setX(x);
circ.setY(y);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
circ.paint(g2d);
g2d.dispose();
}
}
public class Circle {
private int x, y, r;
private Color co;
private int Re, G, B;
private Random ran;
public Circle() {
// TODO Auto-generated constructor stub
ran = new Random();
x = 100;
y = 50;
r = ran.nextInt(50) + 50;
Re = ran.nextInt(255);
G = ran.nextInt(255);
B = ran.nextInt(255);
co = new Color(Re, G, B);
}
public void paint(Graphics2D g2d) {
g2d.setColor(co);
g2d.fillOval(x, y, r * 2, r * 2);
}
public int getRe() {
return Re;
}
public int getG() {
return G;
}
public int getB() {
return B;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getR() {
return r;
}
public void randomColor() {
setCo(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255));
}
public void setCo(int Re, int G, int B) {
co = new Color(Re, G, B);
}
public Color getCo() {
return co;
}
public Random getRan() {
return ran;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
}
I suggest you should set the color of the graphics object within paint(g) before painting the circle.
public void paint(Graphics g) {
super.paint(g);
g.setColor(circ.getCo());
g.fillOval(x,y,100,100);
}
In general, you should not override the paint() method of the JFrame. Instead, create a JPanel, add it to your frame and override the paintComponent() method of the panel.
can you see the problem. the thread runs fine but the brick does not want to respond to the key listener. I try to test if the keylistener was at last getting an event but it does not even do the system.out.println
import java.awt.*;//imports
import java.util.*;
import java.applet.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class Start extends Applet implements Runnable, KeyListener// where i put the keylistener in
{
DrawBackground dbg = new DrawBackground();
Brick brick = new Brick();
Thread gameLoop;
public void init() {
addKeyListener(this);// i add the key listener
}
public void start() {
Thread gameLoop = new Thread(this);
gameLoop.start();
}
public void run() {
while (true) {
brick.update(1);
repaint();
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
}
}
}
public void stop() {
}
public void paint(Graphics g)// with out any paint it works if im changing
// somthing like a lable
{
dbg.paint(g, this);
brick.paint(g, this);
}
public void keyPressed(KeyEvent e)// test to see if it works
{
System.out.println("why");
if (e.getKeyCode() == 37) {
brick.left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
this is the Brick class the thing i'm trying to move
import java.awt.*;
import java.util.*;
import java.applet.*;
public class Brick {
public int dy = 40;
public int yStart = -20;
public int time = 0;
public int dx = 0;
public int xStart = 0;
public int start = 1;
public void paint(Graphics g, Start sp) {
Dimension screenSize = sp.getSize();
int sheight = screenSize.height;
int swidth = screenSize.width;
if (start == 1) {
xStart = swidth - (int) (swidth / 2.5);
start = 0;
}
int bWidth = swidth / 15;
int bHeight = swidth / 15;
int time = 0;
g.setColor(Color.red);
g.fillRect(xStart, yStart, bWidth, bHeight);
}
public void update(int x) {
if (time == 60) {
time = 0;
yStart += dy;
}
else {
time += x;
}
}
public void left() {
xStart -= dx;
}
}
It doesn't look like you have set the keyboard focus. See this question.
I've always used setFocusable(true) after adding the keyListener and its worked for me, but the answer to that question has a better solution.