How to modify pixels and use mouseclickedaction? - java

I am designing a picture lab project for school and I can't figure out how to modify the rgb of pixels. My project is an eye test game where players choose the one color that is different from the rest. Should I modify the pixels of the background or of a blank photo? Also, how do I implement mouseClickedAction (given method that runs when mouse is clicked)?
Here's some bare stuff I have so far:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.ImageObserver;
import java.util.ArrayList;
public class EagleEye extends FlexiblePictureExplorer {
public static Picture background = new Picture(1003,1003);
//settings
private int gameDimensions = 4;
private int difficulty = 30;
private final int statsHeight = 80;
public EagleEye(DigitalPicture Picture) {
super(background);
setTitle("Eagle Eye");
int xGrid = gameDimensions;
int yGrid = gameDimensions;
int r1 = (int)(Math.random() * gameDimensions + 1);
int r2 = (int)(Math.random() * gameDimensions + 1);
colorSetter(xGrid,yGrid);
}
private void colorSetter(int x,int y) {
for (int i=0;i<x;i++) {
for (int j=0;j<y;j++) {
fillBox(i,j);
}
}
}
private void fillBox(int x, int y) {
int r = (int)(Math.random() * 255 + 1);
int g = (int)(Math.random() * 255 + 1);
int b = (int)(Math.random() * 255 + 1);
int x1;
int x2;
if (x==0) {
x1 = 0;
x2 = 250;
}
else if (x==1) {
x1 = 252;
x2 = 501;
}
else if (x==2) {
x1 = 503;
x2 = 752;
}
else {
x1 = 754;
x2 = 1003;
}
int y1;
int y2;
if (y==0) {
y1 = 0;
y2 = 250;
}
else if (y==1) {
y1 = 252;
y2 = 501;
}
else if (y==2) {
y1 = 503;
y2 = 752;
}
else {
y1 = 754;
y2 = 1003;
}
int rgb = calculateColors(r,g,b);
for (int i=x1;i<=x2;i++) {
for (int j=y1;j<=y2;j++) {
background.setBasicPixel(x1,y1,rgb);
}
}
setImage(background);
}
private int calculateColors(int r, int g, int b) {
int r1 = r * 65536;
int g1 = g * 256;
int b1 = b;
return r1 + g1 + b1;
}
private void drawStats(Picture img){
Picture statsImg = new Picture(statsHeight, imageWidth);
Graphics g = statsImg.getGraphics();
g.setFont(new Font("Times New Roman", Font.PLAIN, 16));
g.setColor(Color.blue);
}
private void updateImage() {
}
public void mouseClickedAction(DigitalPicture pict, Pixel pix) {
}
private void endGame() {
}
public boolean imageUpdate(Image arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
// TODO Auto-generated method stub
return false;
}
public static void main(String[] args) {
Picture white = new Picture(100,100);
EagleEye game = new EagleEye(white);
}
}

I think the easiest way that you will find for drawing and graphics will not be drawing to an image, but instead drawing directly to the JPanel. If you have a class that extends JPanel, you can implement
public void paintComponent(Graphics g) {
//Code to draw whatever you like, e.g.
g.setColor(new Color(255, 255, 255));
g.drawRect(0, 0, width, height);
}
With this, you will not have to worry about handling images,
If you would still like to use images, you can use the BufferedImage, which has great docs explaining how to use it:
https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html
(You will still need to display these images, most likely using the paintComponent method above anyways, and if you want to draw in a loop, you will have to put that loop on another thread, be aware)
As for the mouseClicked, you will need to implement a MouseListener, which is quite simple:
Create a MouseListener object in your class, you will have to implement a number of methods inside it, most of which will likely go unused.
Somewhere in your code (probably the constructor) you will need to add the MouseListener to whatever component you want to wait for the clicks (probably the panel you are drawing on)
When that component is clicked on, the mouseClicked method will be called and from there you can do whatever you need to, like calling the other methods you have there to handle mouse clicks.
The MouseEvent object in the listener has all the useful information yu will need, like it's position (relative to the component you added the listener to)
public class YourClass {
public YourClass() {
this.addMouseListener(ml);
}
//code
private MouseListener ml = new MouseListener() {
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println(arg0.getX() + ", " + arg0.getY());
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
}

Related

Command line input

Is there any way to get only the initial press from the drag, because right now it keeps toggling between black and white when dragged over the same square. Also, I am trying to get from the command line the width and height of the rectangles that will make the grid, if the user screws up or nothing is input then they are set to 50 by default. I tried creating a method because I didn't really know how to put them in the main an then use it in the JPanel.
public class Clicky extends JFrame {
private static class Board extends JPanel {
public int BRICK_WIDTH = 50;
public int BRICK_HEIGHT = 50;
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public double width = screenSize.getWidth();
public double height = screenSize.getHeight();
public double bWidth;
public double bHeight;
private int COLS = (int) (width / bWidth);
private int ROWS = (int) (height / bHeight);
private Color CO = Color.BLACK;
private boolean[][] isWhite = new boolean[COLS + 1][ROWS + 1];
public Board() {
System.out.println("WIdth:" + COLS + "Height:" + ROWS);
setBackground(Color.BLACK);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.printf("X: %d Y: %d ", mx, my);
isWhite[(int) (mx / bWidth)][(int) (my
/ bHeight)] = !isWhite[(int) (mx / bWidth)][(int) (my / bHeight)];
repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
mx = e.getX();
my = e.getY();
isWhite[(int) (mx / bWidth)][(int) (my
/ bHeight)] = !isWhite[(int) (mx / bWidth)][(int) (my / bHeight)];
int gridx = e.getX();
int gridy = e.getY();
System.out.println(gridx);
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
#Override
protected void paintComponent(Graphics g,String[] args ) {
super.paintComponent(g);
drawBricks(g);
getValues(args);
}
private double x;
private double y;
public void getValues(String[] args){
try
{
bWidth = Integer.valueOf(args[0]);
}
catch (IndexOutOfBoundsException | NumberFormatException ex)
{
// If the argument was bad then use the default.
bWidth = BRICK_WIDTH;
}
try
{
bHeight = Integer.valueOf(args[1]);
}
catch (IndexOutOfBoundsException | NumberFormatException ex)
{
// If the argument was bad then use the default.
bHeight = BRICK_HEIGHT;
}
}
private void drawBricks(Graphics g) {
Graphics2D brick = (Graphics2D) g.create();
x = 0;
y = 0;
for (int j = 0; j <= ROWS; j++) {
for (int a = 0; a <= COLS; a++) {
if (isWhite[a][j]) {
brick.setColor(Color.WHITE);
} else {
brick.setColor(Color.BLACK);
}
Rectangle2D.Double rect = new Rectangle2D.Double(x, y, bWidth, bHeight);
brick.fill(rect);
brick.setColor(Color.gray);
brick.draw(rect);
x += bWidth;
}
repaint();
x = 0;
y += bHeight;
}
}
public int mx = -100;
public int my = -100;
}
public Clicky() {
setDefaultCloseOperation(EXIT_ON_CLOSE); // mai bine cu exit on close
setSize(800, 820);
add(new Board());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Clicky().setVisible(true);
}
});
}
}
There isn't an event you can listen for that will tell you when the drag event starts. You can write one yourself. You'll need to some kind of stateful variable that can be toggled on the first receipt of a mouse dragged event then used as a guard for subsequent mouse dragged events. You can reset the stateful variable on a mouse release event. See MouseEvent and MouseEventListener.
As for your other question - I'm not really sure what you're asking. Are you wondering how to get user-supplied data from the command line or trying to figure out how to make use of them once they are supplied?
For the former it's dead simple with command line arguments. For the latter, all you have to do is write a setter method that validates the input and overrides the default if caller-supplied values are valid.

how to show balls on screen in java swing

this is my board class and i try to call ball object in GameBoard class but i didn't and my problem is didn't show ball on screen.
Used to execute code after a given delay
The attribute is corePoolSize - the number of threads to keep in
the pool, even if they are idle
package test2;
public class Board extends JFrame{
public static int boardWidth = 800;
public static int boardHeight = 800;
public static void main(String[] args){
new Board();
}
public Board() {
this.setSize(boardWidth, boardHeight);
this.setTitle("Ball");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameBoard gb = new GameBoard();
this.add(gb, BorderLayout.CENTER);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
executor.scheduleAtFixedRate(new RepaintTheBoard(this), 0L, 20L, TimeUnit.MILLISECONDS);
this.setVisible(true);
}
}
class RepaintTheBoard implements Runnable{
Board theBoard;
public RepaintTheBoard(Board theBoard){
this.theBoard = theBoard;
}
#Override
public void run() {
// Redraws the game board
theBoard.repaint();
}
}
#SuppressWarnings("serial")
//GameDrawingPanel is what we are drawing on
class GameBoard extends JComponent {
Random rnd=new Random();
public ArrayList<Ball> balls = new ArrayList<Ball>();
int width = Board.boardWidth;
int height = Board.boardHeight;
public GameBoard(){
for(int i=0; i<50; i++){
int randomStartXPos = (int) (Math.random() * (Board.boardWidth - 40) + 1);
int randomStartYPos = (int) (Math.random() * (Board.boardHeight - 40) + 1);
balls.add(new Ball(randomStartXPos,randomStartYPos,30));
}
}
public void paint(Graphics g) {
// Allows me to make many settings changes in regards to graphics
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255)));
for(Ball ball : balls){
ball.move();
g2d.draw(ball);
}
}
}
this ball class and i think , i have problem in move() class
package test2;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
public class Ball extends Ellipse2D{
int uLeftXPos, uLeftYPos;
int xDirection = 1;
int yDirection = 1;
int diameter;
int width = Board.boardWidth;
int height = Board.boardHeight;
public Ball(int randomStartXPos, int randomStartYPos, int Diam) {
super();
this.xDirection = (int) (Math.random() * 4 + 1);
this.yDirection = (int) (Math.random() * 4 + 1);
// Holds the starting x & y position for the Rock
this.uLeftXPos = randomStartXPos;
this.uLeftYPos = randomStartYPos;
this.diameter = Diam;
}
public void move(){
if (uLeftXPos + xDirection < 0)
xDirection = 1;
if (uLeftXPos + xDirection > width - diameter)
xDirection = -1;
if (uLeftYPos + yDirection < 0)
yDirection = 1;
if (uLeftYPos + yDirection > height - diameter)
yDirection = -1;
uLeftXPos = uLeftXPos + xDirection;
uLeftYPos = uLeftYPos + yDirection;
}
#Override
public Rectangle2D getBounds2D() {
// TODO Auto-generated method stub
return null;
}
#Override
public double getX() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getY() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getWidth() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getHeight() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setFrame(double x, double y, double w, double h) {
// TODO Auto-generated method stub
}
}
Your main problem is that your Ball class extends a Shape object, Ellipse2D and does so incompletely, preventing full Ellipse2D/Shape behavior. I think that you'd be far better off not using inheritance but rather using composition -- have Ball contain a valid and complete Ellipse2D object, one that it uses to help it draw itself.
Other issues:
Your JComponent should have paintComponent overridden, not paint
You should always call the super's painting method within your override
It's not a good idea to have program logic within a painting method, as you can never fully control this method, nor do you want to. Better to have your move method separate and have the painting method do one thing -- paint the state of the component, and that's it.
Your code is skirting danger with Swing threading. Consider using a Swing Timer and not a scheduled executor service.
Start your GUI on the Swing thread using SwingUtilities.invokeLater(...)
Since your Ball object uses default overrides for most of the Ellipse2D methods, no movement will occur since its these method returns that determine the location of the Shape.
But again, you don't want to really override this object, but instead use composition.
Something like:
class Ball {
private static final double ELLIPSE_W = 20;
private static final double ELLIPSE_H = ELLIPSE_W;
private int x = 0;
private int y = 0;
private Ellipse2D ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
int uLeftXPos, uLeftYPos;
int xDirection = 1;
int yDirection = 1;
int diameter;
int width = Board.boardWidth;
int height = Board.boardHeight;
public Ball(int randomStartXPos, int randomStartYPos, int Diam) {
super();
this.xDirection = (int) (Math.random() * 4 + 1);
this.yDirection = (int) (Math.random() * 4 + 1);
// Holds the starting x & y position for the Rock
this.uLeftXPos = randomStartXPos;
this.uLeftYPos = randomStartYPos;
this.diameter = Diam;
x = uLeftXPos;
y = uLeftYPos;
ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
}
public Ellipse2D getEllipse() {
return ellipse;
}
public void move() {
if (uLeftXPos + xDirection < 0)
xDirection = 1;
if (uLeftXPos + xDirection > width - diameter)
xDirection = -1;
if (uLeftYPos + yDirection < 0)
yDirection = 1;
if (uLeftYPos + yDirection > height - diameter)
yDirection = -1;
uLeftXPos = uLeftXPos + xDirection;
uLeftYPos = uLeftYPos + yDirection;
x = uLeftXPos;
y = uLeftYPos;
ellipse = new Ellipse2D.Double(x, y, ELLIPSE_W, ELLIPSE_H);
}
}
And in the game board:
class GameBoard extends JComponent {
Random rnd = new Random();
public ArrayList<Ball> balls = new ArrayList<Ball>();
int width = Board.boardWidth;
int height = Board.boardHeight;
public GameBoard() {
for (int i = 0; i < 50; i++) {
int randomStartXPos = (int) (Math.random() * (Board.boardWidth - 40) + 1);
int randomStartYPos = (int) (Math.random() * (Board.boardHeight - 40) + 1);
balls.add(new Ball(randomStartXPos, randomStartYPos, 30));
}
}
public void move() {
for (Ball ball : balls) {
ball.move();
}
}
#Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)));
for (Ball ball : balls) {
// ball.move();
g2d.draw(ball.getEllipse());
}
}
}

Calling a graphics method inside a keylistener

So for my AP Comp. science class I have to make an applet where we have to use separate class files to make a building skyline-line thing. At the moment I have a window class that has a draw method and a method to turn the window object on. I would like to have the window turn on with a keyListener, but I'm semi-new to those.
this is the Window class I have
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JComponent;
public class windows {
private int x,y,height,width;
public windows(){
x=0;
y=0;
height = 0;
width = 0;
}//default constructor
public windows(int x, int y, int height, int width){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}//windows constructor
public void windowDraw(Graphics g){
Color window = new Color(0x05030D);
g.setColor(window);
g.fillRect(x, y, width, height);
}//windowDraw
public void windowOn(Graphics g){
Color on = new Color(0xFFD200);
g.setColor(on);
g.fillRect(x, y, width, height);
}//window on
}//class
Here is the client. I have some test prints inside that I used to play around with.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//Matteo Sabato
public class TeenTitans_Client extends Applet implements KeyListener {
private final int APPLET_WIDTH = 1000;
private final int APPLET_HEIGHT = 700;
private final int HEIGHT_MIN = 400;
private final int VARIANCE = 40;
Tower main,top;//(x, y, height, width)
backGround ground;//x,y,height,width
windows Right, middleTop, Left, Bottom, Middle, Tip;
boolean power = false;
Listener on;
int key;
public void init(){
addKeyListener(this);
Random gen = new Random();
Color back = new Color(0x37E2EA);
setBackground(back);
setSize(APPLET_WIDTH,APPLET_HEIGHT);
main = new Tower(550,180,460,150);
top = new Tower(370,40,150,505);
ground = new backGround(-200,500,400,1800);
Right = new windows(380,50,130,130);
Left = new windows(735,50,130,130);
middleTop = new windows(520,50,130,205);
Bottom = new windows(560,490,140,130);
Middle = new windows(560,340,140,130);
Tip = new windows(560,190,140,130);
}
public void paint(Graphics g){
ground.circleDraw(g);
main.towerDraw(g);
top.towerDraw(g);
Left.windowDraw(g);
Right.windowDraw(g);
Bottom.windowDraw(g);
middleTop.windowDraw(g);
Middle.windowDraw(g);
Tip.windowDraw(g);
if (power == true)
On(g);
}//paint
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub.
System.out.println(e.getKeyCode());
this.key = e.getKeyCode();
if (key==10){
power = true;
}
}//keyPressed
public void On(Graphics g){
Tip.windowOn(g);
}//On
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}//class
The problem I'm running into is that I don't know how to call my On method in the client because I need to have Graphics g as a parameter, which key event methods can't take. If I make a loop somewhere else, I won't be able to check for key presses. I tried laying it out a bunch of different ways, but I just can't figure it out.

How do I embed this into my website?

I am attempting to embed a game into my website that I programmed in java. I have no idea how to take my code from eclipse(which is what my JDE is) and put it into my website. I am using a weebly.com website. I do have several unfinished classes, I want to upload my incomplete games as well as complete just to show progress. so I ask you, how do I get this code from eclipse, to my website. Thanks for the help and the following is my code.
This is my Main class:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
public class Main extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
Thread th = new Thread(this);
boolean running = true;
public int Jweidth = 400, Jheight = 400;
Image dbImage;
Graphics dbGraphics;
Bullet b;
Player p;
Enemy e, e2, e3, e4, e5, e6, e7, e8;
HealthBar hb;
NameSign ns;
Restart r;
private boolean BFire;
public void init() {
//set window size
setSize(Jweidth, Jheight);
//calls player class
p = new Player(this);
//calls healthBar
hb = new HealthBar(this, p);
//calls enemy class
e = new Enemy(this);
e2 = new Enemy(42, 0, this);
e3 = new Enemy(84, 0, this);
e4 = new Enemy(126, 0, this);
e5 = new Enemy(0, 42, this);
e6 = new Enemy(42, 42, this);
e7 = new Enemy(84, 42, this);
e8 = new Enemy(126, 42, this);
//calls bullet class
b = new Bullet(this);
//calls nameSign class
ns = new NameSign(this);
//calls Restart class
r = new Restart(this);
}
public void start() {
//starts a new thread
th.start();
}
public void stop() {
running = false;
}
public void destroy() {
running = false;
}
public void run() {
while (running) {
setBFire(b.getFire());
//calls update method from player class
p.update(this);
//calls update method from enemy class
e.update(this, p);
e2.update(this, p);
e3.update(this, p);
e4.update(this, p);
e5.update(this, p);
e6.update(this, p);
e7.update(this, p);
e8.update(this, p);
//calls update method from fire class if BFire is true
if (setBFire(true)) {
b.update(this, p);
}
//calls update method from HealthBar class
hb.update(this, p);
//calls update method from NameSign class
ns.update(this);
//calls update method from Restart class
r.update(this, p);
repaint();
//sets Thread to repeat every 17 milliseconds
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//doublebuffer
public void update(Graphics g) {
dbImage = createImage(Jweidth, Jheight);
dbGraphics = dbImage.getGraphics();
paint(dbGraphics);
g.drawImage(dbImage, 0, 0, this);
}
//paint class
public void paint(Graphics g) {
//calls paint method from player class
p.paint(g, this);
//calls paint method from enemy class
e.paint(g, this);
e2.paint(g, this);
e3.paint(g, this);
e4.paint(g, this);
e5.paint(g, this);
e6.paint(g, this);
e7.paint(g, this);
e8.paint(g, this);
//calls paint method from bullet class
b.paint(g, this);
//calls paint method from healthBar class
hb.paint(g, this);
//calls paint method from nameSign class
ns.paint(g, this);
//calls paint method from Restart class
r.paint(g);
}
public int getJweidth() {
return Jweidth;
}
public int getJheight() {
return Jheight;
}
//ignore all boolean Bfire methods
public boolean isBFire() {
return BFire;
}
public boolean setBFire(boolean bFire) {
BFire = bFire;
return bFire;
}
}
This is my Enemy class:
import java.awt.*;
import java.net.URL;
public class Enemy {
//Enemy ints
private int x = 0, y = 0, speed = 2;
private URL url;
private Image Enemy;
//adds image
public Enemy(Main m){
url = m.getDocumentBase();
Enemy = m.getImage(url, "Enemy.png");
}
public Enemy(int i, int j, Main m) {
url = m.getDocumentBase();
Enemy = m.getImage(url, "Enemy.png");
x = i;
y = j;
}
//same as run method but just for the enemy
public void update(Main m, Player p){
x += speed;
if(x <= 0){
speed = 2;
y += 32;
}
else if(x > m.getJweidth() - 32){
speed = -2;
y += 32;
}
//calls collision method
collision(p);
}
//enemy player hitbox
private void collision(Player p) {
int Px = p.getX();
int Py = p.getY();
int Pr = p.getRadious();
if(Px - Pr <= x && Px + Pr >= x && Py - Pr <= y && Py + Pr >= y){
p.hit();
}
}
//Graphics for enemy
public void paint(Graphics g, Main m){
g.drawImage(Enemy, x, y, m);
}
}
This is my Bullet class (this game is a work in progress and this class isn't working, but that is just unfinished work that I will do soon)
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;
public class Enemy {
//Enemy ints
private int x = 0, y = 0, speed = 2;
private URL url;
private Image Enemy;
//adds image
public Enemy(Main m) {
url = m.getDocumentBase();
Enemy = m.getImage(url, "Enemy.png");
}
public Enemy(int i, int j, Main m) {
url = m.getDocumentBase();
Enemy = m.getImage(url, "Enemy.png");
x = i;
y = j;
}
//same as run method but just for the enemy
public void update(Main m, Player p) {
x += speed;
if (x <= 0) {
speed = 2;
y += 32;
} else if (x > m.getJweidth() - 32) {
speed = -2;
y += 32;
}
//calls collision method
collision(p);
}
//enemy player hitbox
private void collision(Player p) {
int Px = p.getX();
int Py = p.getY();
int Pr = p.getRadious();
if (Px - Pr <= x && Px + Pr >= x && Py - Pr <= y && Py + Pr >= y) {
p.hit();
}
}
//Graphics for enemy
public void paint(Graphics g, Main m) {
g.drawImage(Enemy, x, y, m);
}
}
This is my Restart class(once again unfinished but on the way)
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Restart implements KeyListener {
private int x, y;
private int pHealth;
private String string = "Would you like to play again?";
private boolean restart = false;
public Restart(Main m) {
x = 600;
y = 600;
}
public void update(Main m, Player p) {
//checks if players health = 0 and if restart is true
pHealth = p.getpHealth();
if (setRestart(true && pHealth <= 0)) {
System.out.println("Restart");
x = m.Jweidth / 2 - 75;
y = m.Jheight / 2;
}
//reset ints for player
//TODO
//reset ints for enemy
//TODO
//reset ints for bullet
//TODO
//reset ints for healthbar
//TODO
}
public void paint(Graphics g) {
g.drawString(string, x, y);
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_F1: {
setRestart(true);
break;
}
}
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_F1: {
setRestart(false);
break;
}
}
}
public void keyTyped(KeyEvent arg0) {
}
//ignore all boolean methods
public boolean isRestart() {
return restart;
}
public boolean setRestart(boolean restart) {
this.restart = restart;
return restart;
}
}
You will have to use Applets to embed your Java program in a browser, or Java Web Start if you just want to start it from the web in a new window.
Some security issues may apply depending on the Java version you are using.
Here are some examples on how to do it:
https://docs.oracle.com/javase/tutorial/deployment/applet/
http://www.javatpoint.com/java-applet
And here for the Java Web Start:
https://docs.oracle.com/javase/tutorial/deployment/webstart/
You're gonna need to make a .jar file and a compiled .class file, no .java file. To implement Java code in HTML, you can use the deprecated <applet> tag, or the new <object> tag.
<object codetype="application/java" classid="java:yourclass.class" archive="yourjar.jar" width="1000" height="1000"></object>
codetype="application/java" - The type of code, use application/java.
classid="?" - Java class to run, eg. java:MyApplet.class
archive="url" - Address or filename of the Java archive file (.jar) containing the class files.
width="?" - The width of the window, in pixels.
height="?" - The height of the window, in pixels.
Just telling you, I'm not sure that it'll work.

How to drop a ball when clicked with mouse?

I'm working on a game project. The aim is clicking the balls and drop them into the basket which is below in the JPanel. I created some ways to do that but I can't achieve it. In my opinion, when the user click the ball's center with a margin of error (because the program can't catch the real point of balls), the program understands the action and runs the function of this issue. After clicking the ball it should be dropped down straight but the other balls should be continued. I use MouseListener#mousePressed method, but it doesn't work or I'm missing some parts. In addition, I made some changes in my source code, but I want to listen your advices so I am writing this topic.
I wrote a method which finds the mouse and ball coordinates. So when I make some changes to it, I can achieve my project goal. You can see the editing in the picture.
This is my source code ;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Game {
public Game() {
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("MultipleBallApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BallControl());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BallControl extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private BallPanel ballPanel = new BallPanel();
private JButton Suspend = new JButton("Suspend");
private JButton Resume = new JButton("Resume");
private JButton Add = new JButton("+1");
private JButton Subtract = new JButton("-1");
private JScrollBar Delay = new JScrollBar();
public BallControl() {
// Group buttons in a panel
JPanel panel = new JPanel();
panel.add(Suspend);
panel.add(Resume);
panel.add(Add);
panel.add(Subtract);
// Add ball and buttons to the panel
ballPanel.setBorder(new javax.swing.border.LineBorder(Color.red));
Delay.setOrientation(JScrollBar.HORIZONTAL);
ballPanel.setDelay(Delay.getMaximum());
setLayout(new BorderLayout());
add(Delay, BorderLayout.NORTH);
add(ballPanel, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
this.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent clickEvent) {
// TODO Auto-generated method stub
System.out.println("X coordinate =" + clickEvent.getX());
System.out.println("Y coordinate = " + clickEvent.getY());
double radius1;
int x = 0;
double y = 0;
int radius = 15;
double xM = clickEvent.getX();
double yM = clickEvent.getY();
radius1 = Math.sqrt((xM - x) * (xM - x) + (yM - y)
* (yM - y));
System.out.println("Radius1 =" + radius1);
// ballPanel.list.get(0).setD
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
// Register listeners
Suspend.addActionListener(new Listener());
Resume.addActionListener(new Listener());
Add.addActionListener(new Listener());
Subtract.addActionListener(new Listener());
Delay.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
ballPanel.setDelay(Delay.getMaximum() - e.getValue());
}
});
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Suspend) {
ballPanel.suspend();
} else if (e.getSource() == Resume) {
ballPanel.resume();
} else if (e.getSource() == Add) {
ballPanel.add();
} else if (e.getSource() == Subtract) {
ballPanel.subtract();
}
}
}
}
class BallPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private int delay = 30;
public ArrayList<AnimatedShape> list = new ArrayList<AnimatedShape>();
private AnimatedRectange rectangle;
public BallPanel() {
this.rectangle = new AnimatedRectange(-25, 373, 50, 25, Color.BLACK);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
// Create a timer with the initial delay
protected Timer timer = new Timer(delay, new ActionListener() {
/**
* Handle the action event
*/
#Override
public void actionPerformed(ActionEvent e) {
for (AnimatedShape ball : list) {
ball.update(getBounds());
}
rectangle.update(getBounds());
repaint();
}
});
public void add() {
int radius = 15;
// Randomised position
int x = (int) (Math.random() * (getWidth() - (radius * 2)))
+ radius;
int y = (int) (Math.random() * (getHeight() - (radius * 2)))
+ radius;
Color color = new Color((int) (Math.random() * 256),
(int) (Math.random() * 256), (int) (Math.random() * 256));
AnimatedBall ball = new AnimatedBall(x, y, radius, color);
list.add(ball);
}
// public void formula(MouseEvent clickEvent) {
// double radius1;
// int x = 0;
// double y = 0;
// int radius = 15;
// double xM = clickEvent.getX();
// double yM = clickEvent.getY();
// radius1 = Math.sqrt((xM - x) * (xM - x) + (yM - y) * (yM - y));
// System.out.println("Radius1 =" + radius1);
// }
public void subtract() {
if (list.size() > 0) {
list.remove(list.size() - 1); // Remove the last ball
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (AnimatedShape ball : list) {
ball.paint(this, g2d);
}
rectangle.paint(this, g2d);
}
public void suspend() {
timer.stop();
}
public void resume() {
timer.start();
}
public void setDelay(int delay) {
this.delay = delay;
timer.setDelay(delay);
}
}
public interface AnimatedShape {
public void update(Rectangle bounds);
public void paint(JComponent parent, Graphics2D g2d);
}
public abstract class AbstractAnimatedShape implements AnimatedShape {
private Rectangle bounds;
private int dx, dy;
public AbstractAnimatedShape() {
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public Rectangle getBounds() {
return bounds;
}
public int getDx() {
return dx;
}
public int getDy() {
return dy;
}
public void setDx(int dx) {
this.dx = dx;
}
public void setDy(int dy) {
this.dy = dy;
}
#Override
public void update(Rectangle parentBounds) {// ball
Rectangle bounds = getBounds();
int dx = getDx();
int dy = getDy();
bounds.x += dx;
bounds.y += dy;
if (bounds.x < parentBounds.x) {
bounds.x = parentBounds.x;
setDx(dx *= -1);
} else if (bounds.x + bounds.width > parentBounds.x
+ parentBounds.width) {
bounds.x = parentBounds.x + (parentBounds.width - bounds.width);
setDx(dx *= -1);
}
if (bounds.y < parentBounds.y) {
bounds.y = parentBounds.y;
setDy(dy *= -1);
} else if (bounds.y + bounds.height > parentBounds.y
+ parentBounds.height) {
bounds.y = parentBounds.y
+ (parentBounds.height - bounds.height);
setDy(dy *= -1);
}
}
}
public class AnimatedBall extends AbstractAnimatedShape {
private Color color;
public AnimatedBall(int x, int y, int radius, Color color) {
setBounds(new Rectangle(x, y / 2, radius * 2, radius * 2));
this.color = color;
setDx(Math.random() > 0.5 ? 2 : -2);
// setDy(Math.random() > 0.5 ? 2 : -2);
}
public Color getColor() {
return color;
}
#Override
public void paint(JComponent parent, Graphics2D g2d) {
Rectangle bounds = getBounds();
g2d.setColor(getColor());
g2d.fillOval(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
public class AnimatedRectange extends AbstractAnimatedShape {
private Color color;
public AnimatedRectange(int x, int y, int width, int height, Color color) {
setBounds(new Rectangle(x, y, width, height));
this.color = color;
setDx(2);
}
// Don't want to adjust the vertical speed
#Override
public void setDy(int dy) {
}
#Override
public void paint(JComponent parent, Graphics2D g2d) {
Rectangle bounds = getBounds();
g2d.setColor(color);
g2d.fill(bounds);
}
}
/**
* Main method
*/
public static void main(String[] args) {
new Game();
}
}
At the end of your mousePressed method, you can go though all AnimatedShape objects, check whether they are an AnimatedBall. When the object is a ball, you can test whether the mouse click hits the ball. The mouse click hits the ball when the distance between the center of the ball and the mouse position is smaller than the ball radius. When the ball is hit, you can set its horizontal speed to 0, and the vertical speed to 5 or so.
for (AnimatedShape as : ballPanel.list)
{
if (as instanceof AnimatedBall)
{
AnimatedBall ball = (AnimatedBall)as;
Rectangle b = ball.getBounds();
int ballCenterX = b.x + b.width / 2;
int ballCenterY = b.y + b.height / 2;
Point p = new Point(ballCenterX, ballCenterY);
double d = p.distance(clickEvent.getPoint());
if (d < radius)
{
ball.setDx(0);
ball.setDy(5);
}
}
}
Note
In order to make this work properly, you have to attach this listener to the ballPanel. Originally, you had the line
this.addMouseListener(new MouseListener() {
in your code. You have to change this to
ballPanel.addMouseListener(new MouseListener() {
Otherwise, the mouse coordinates will refer to the wrong component!
Concerning the question from the comment
how can I stop and disapper clickedball's when they crash the bound
You may probably insert method to check this, and call this method in the actionPerformed method of your timer. Further explainations are probably beyond the scope of an anser on a Q&A site. Stackoverflow is not a homework-solution-generator.

Categories