I am trying to draw a circle like this: http://35.197.37.158/Circle/
using drawline function and animate it same as the attached link.
here is what I tried but it draw a line of circle and delete the previous one
This is the class that have my code for drawing a circle and animating it using swin Timer. anyone have better idea to animate the circle ?
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.GeneralPath;
import javax.swing.*;
public class CustomPanel extends JPanel implements ActionListener{
Point [] coordinates;
GeneralPath circle;
final int C = 10;
int j =0;
int i =j;
Point p;
Point p2 ;
Timer clock = new Timer(100, this);
public CustomPanel()
{
LinesCoordinates();
clock.setInitialDelay(50);
clock.start();
}
private void LinesCoordinates()
{
int numberOfLines = 360/C;
coordinates = new Point[numberOfLines];
double cx = 200.0;
double cy = 200.0;
double r = 75.0;
int count = 0;
for(int theta = 0; theta < 360; theta+=C)
{
int x = (int)(cx + r * Math.cos(Math.toRadians(theta)));
int y = (int)(cy + r * Math.sin(Math.toRadians(theta)));
coordinates[count++] = new Point(x, y);
}
}
#Override
public void actionPerformed(ActionEvent e) {
Redraw();
repaint();
}
public void Redraw(){
j=j+1;
p = p2;
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.red);
// while (j<=coordinates.length){
while(i<=j){
j--;
p2 = coordinates[j % coordinates.length];
g2.drawLine(p.x, p.y, p2.x , p2.y);
}}}
And this is my Main
public static void main(String[] args)
{
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
JFrame frame = new JFrame("Circle ");
CustomPanel co = new CustomPanel();
frame.add(co);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
Since I was not able to get your solution draw the circle I had to rewrite your code a bit. Here is my solution preserving your JPanel listening to Timer approach. Hopefully this will work for you. I can send the complete NetBeans project if you want.
package circleanimation;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CustomPanel extends JPanel implements ActionListener {
final int numberOfPoints = 20;
Point[] circleCoordinates = new Point[numberOfPoints];
int nextPointToAnimate = 1;
Timer clock = new Timer(100, this);
public CustomPanel() {
calculateCirclePoints();
clock.setInitialDelay(50);
clock.start();
}
private void calculateCirclePoints() {
int angle = 360 / numberOfPoints;
double cx = 150.0;
double cy = 150.0;
double r = 75.0;
int count = 0;
for (int totalAngle = 0; totalAngle < 360; totalAngle = totalAngle + angle) {
int x = (int) (cx + r * Math.cos(Math.toRadians(totalAngle)));
int y = (int) (cy + r * Math.sin(Math.toRadians(totalAngle)));
circleCoordinates[count++] = new Point(x, y);
}
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.red);
for (int i = 0; i < nextPointToAnimate; i++) {
Point firstPoint = circleCoordinates[i];
Point secondPoint;
if (i == numberOfPoints - 1) {
secondPoint = circleCoordinates[0];
} else {
secondPoint = circleCoordinates[i + 1];
}
g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
}
}
#Override
public void actionPerformed(ActionEvent e) {
nextPointToAnimate++;
if (nextPointToAnimate == numberOfPoints) {
clock.stop();
}
repaint();
}
}
I'm having issues drawing some circles to my JFrame. I originally had it using the default layout and realized this was only adding the most recent circle, so I changed the layout to null, and now nothing gets drawn. I've also tried frame.setLayout(new FlowLayout()) which also doesn't draw anything. Any help would be appreciated!
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* #author Christopher Nielson
*
*/
public class Main {
private static JFrame frame;
private static Random rand;
private static Jiggler jiggler;
private static ArrayList<JComponent> circles;
private static int fps;
public static void main(String[] args) {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setBounds(100, 100, 450, 450);
rand = new Random();
circles = new ArrayList<JComponent>();
int x = frame.getWidth();
int y = frame.getHeight();
for (int i = 0; i < Integer.parseInt(args[0]); i++) {
circles.add(new Circle(rand.nextInt(frame.getWidth()), rand.nextInt(frame.getHeight()),
rand.nextInt(frame.getWidth() / 10) + 100, rand.nextInt(frame.getHeight() / 10) + 100, null));
}
circles.forEach(current -> {
frame.add(current);
});
frame.setVisible(true);
jiggler = new Jiggler(circles, new JLabel("FPS: ")); // TODO add fps
jiggler.run();
}
}
And this is one reason you'll see us recommending time and time again to avoid using null layouts like the plague.
Having said that, your main problem is a design problem, not a layout problem, and that problem being that your Circle class shouldn't extend JComponent or any component for that matter, since if you want to draw multiple circles, you should have only one component, probably a JPanel doing the drawing, and the Circles should be logical classes, classes that have a public void draw(Graphics g) method, not component classes. You would pass the List of Circles to your drawing JPanel, and it would draw the Circles in its paintComponent method by calling the draw(g) methods of each Circle in the list.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class DrawChit extends JPanel {
private static final int PREF_W = 900;
private static final int PREF_H = 700;
private static final int MAX_SHAPES = 30;
private List<MyShape> shapes = new ArrayList<>();
public DrawChit() {
setBackground(Color.WHITE);
for (int i = 0; i < MAX_SHAPES; i++) {
double x = (PREF_W - 100) * Math.random();
double y = (PREF_H - 100) * Math.random();
double w = 100 + (Math.random() * PREF_W) / 10;
double h = 100 + (Math.random() * PREF_H) / 10;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
float hue = (float) Math.random();
double delta = 0.3;
float saturation = (float) (Math.random() * delta + (1 - delta));
float brightness = (float) (Math.random() * delta + (1 - delta));
Color color = Color.getHSBColor(hue, saturation, brightness);
shapes.add(new MyShape(ellipse, color));
}
// we'll throw a black square in the middle!
int rectW = 200;
int rectX = (PREF_W - rectW) / 2;
int rectY = (PREF_H - rectW) / 2;
shapes.add(new MyShape(new Rectangle(rectX, rectY, rectW, rectW), Color.BLACK));
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// use anti-aliasing to make graphics smooth
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// iterate through the shapes list, filling all
for (MyShape shape : shapes) {
shape.fill(g2);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
private Point p0 = null;
private MyShape shape = null;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
// iterate *backwards* so get top-most Shape
for (int i = shapes.size() - 1; i >= 0; i--) {
if (shapes.get(i).contains(e.getPoint())) {
p0 = e.getPoint();
shape = shapes.get(i);
// move selected shape to the top!
shapes.remove(shape);
shapes.add(shape);
repaint();
return;
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (p0 != null) {
moveShape(e.getPoint());
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (p0 != null) {
moveShape(e.getPoint());
p0 = null;
shape = null;
}
}
// translates the shape
private void moveShape(Point p1) {
int deltaX = p1.x - p0.x;
int deltaY = p1.y - p0.y;
shape.translate(deltaX, deltaY);
p0 = p1;
repaint();
}
}
private static void createAndShowGui() {
DrawChit mainPanel = new DrawChit();
JFrame frame = new JFrame("Draw Chit");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyShape {
private Path2D path = new Path2D.Double();
private Color color;
public MyShape(Shape shape, Color color) {
path.append(shape, true);
this.color = color;
}
public boolean contains(Point p) {
return path.contains(p);
}
public void draw(Graphics2D g2) {
g2.setColor(color);
g2.draw(path);
}
public void fill(Graphics2D g2) {
g2.setColor(color);
g2.fill(path);
}
public void translate(int deltaX, int deltaY) {
path.transform(AffineTransform.getTranslateInstance(deltaX, deltaY));
}
}
I'm very confused as to why my scoreboard isn't updating on screen. The scores are increasing (I checked with debugger, also the ball is being centered). But the scoreboard isn't updating at all it constantly says "0 : 0"
Pong Class
package com.dheraxysgames.pong;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Pong extends JFrame{
private static final long serialVersionUID = 1L;
//Set Resolution
public static final int width = 300,
height = width / 4 * 3,
scale = 3;
public Pong() {
Dimension size = new Dimension(width * scale, height * scale);
setSize(size);
setTitle("PONG");
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new GamePanel());
}
public static int getWindowWidth(){
return width * scale;
}
public static int getWindowHeight(){
return height * scale;
}
public static void main(String[] args) {
new Pong();
}
}
GamePanel Class
package com.dheraxysgames.pong;
import java.awt.Color;
import java.awt.Font;
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.JPanel;
import javax.swing.Timer;
public class GamePanel extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
Ball ball = new Ball();
Player player = new Player();
AI ai = new AI(this);
public GamePanel(){
Timer time = new Timer(50, this);
time.start();
this.addKeyListener(this);
this.setFocusable(true);
}
private void update(){
player.update();
ai.update();
ball.update();
ball.checkCollision(player);
ball.checkCollision(ai);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, Pong.getWindowWidth(), Pong.getWindowHeight());
g.setColor(Color.WHITE);
Font font = new Font("IMMORTAL", Font.BOLD, 50);
g.setFont(font);
g.drawString(player.score + " : " + ai.score, Pong.getWindowWidth() / 2 - 60, 50);
player.paint(g);
ai.paint(g);
ball.paint(g);
}
public Ball getBall(){
return ball;
}
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
//Keyboard
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) player.setYVelocity(-10);
if (e.getKeyCode() == KeyEvent.VK_DOWN) player.setYVelocity(10);
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) player.setYVelocity(0);
if (e.getKeyCode() == KeyEvent.VK_DOWN) player.setYVelocity(0);
}
public void keyTyped(KeyEvent e) {
}
}
Player Class
package com.dheraxysgames.pong;
import java.awt.Color;
import java.awt.Graphics;
public class Player {
public int score = 0;
private static int width = 50,
height = 150;
private int x = 800, y = (Pong.getWindowHeight() / 2) - (height / 2),
yV = 0;
public Player() {
}
public void update(){
y += yV;
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.fillRect(x, y, width, height);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public void setYVelocity(int speed){
yV = speed;
}
}
AI Class
package com.dheraxysgames.pong;
import java.awt.Color;
import java.awt.Graphics;
public class AI {
public int score = 0;
private static int width = 50,
height = 150;
private GamePanel field;
private int x = 50, y = (Pong.getWindowHeight() / 2) - (height / 2),
yV = 0;
public AI(GamePanel game) {
this.field = game;
}
public AI(){
}
public void update(){
if(field.getBall().getY() < this.y) yV = -8;
if(field.getBall().getY() > this.y) yV = 8;
y += yV;
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.fillRect(x, y, width, height);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public void setYVelocity(int speed){
yV = speed;
}
}
Ball Class
package com.dheraxysgames.pong;
import java.awt.Color;
import java.awt.Graphics;
public class Ball {
private int x = Pong.getWindowWidth() / 2, y = Pong.getWindowHeight() / 2,
xV = 10, yV = 10;
private static int size = 40;
Player player = new Player();
AI ai = new AI();
public void update() {
x += xV;
y += yV;
if (x < 0){
reverseXDirection();
player.score++;
x = Pong.getWindowWidth() / 2;
y = Pong.getWindowHeight() / 2;
}
if (x > Pong.getWindowWidth() - size){
reverseXDirection();
ai.score++;
x = Pong.getWindowWidth() / 2;
y = Pong.getWindowHeight() / 2;
}
if (y < 0 || y > Pong.getWindowHeight() - size - 38) reverseYDirection();
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.fillOval(x, y, size, size);
}
private void reverseXDirection(){
xV = -xV;
}
private void reverseYDirection(){
yV = -yV;
}
public void checkCollision(Player p) {
if (this.x + size > p.getX() && this.x + size < p.getX() + p.getWidth()){
if (this.y + size > p.getY() && this.y + size < p.getY() + p.getHeight()){
reverseXDirection();
}
}
}
public void checkCollision(AI ai) {
if (this.x > ai.getX() && this.x < ai.getX() + ai.getWidth()){
if (this.y > ai.getY() && this.y < ai.getY() + ai.getHeight()){
reverseXDirection();
}
}
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
In you're Ball class the score you're updating is not the same score that is being checked in the GamePanel class.
Notice how in both classes you are calling
Player player = new Player();
AI ai = new AI();
player and ai in Ball are seperate instances from the player and ai in GamePanel.
You will need to get the player and ai from the GamePanel class and pass them to the Ball class. The easiest way to do this would probably be to give Ball a constructor like so
Player player;
AI ai;
public Ball(Player player, AI ai) {
this.player = player;
this.ai = ai;
}
And in your GamePanel class change:
Ball ball = new Ball();
Player player = new Player();
AI ai = new AI(this);
To this:
Player player = new Player();
AI ai = new AI(this);
Ball ball = new Ball(player, ai);
It's been a while since I've used java so I'm probably forgetting a simpler way to do this, but this should solve the problem.
I need a on-screen virtual joystick solution to control external device - a cart. My program is written on Java/Swing and it works on windows rugged tablet with resistive touch screen. There's no x-y slider control in Swing, failed to find it thru Google, so probably I need to write it from scratch. Now the question: what is best approach to write such control? I was thinking to place two JSlider controls, one horizontal and second vertical, and make custom thumb, but i'm afraid this can bring me troubles because it's actually a hack. Maybe just write it from scratch? Maybe there's an existing solution?
I will use it with thumb dragging and touching final thumb position.
for example
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleJoystickDemo extends JFrame {
//I think that orginally made by #HFOE
private int displayWidth = 340;
private int displayHeight = 550;
private final Point position;
public SimpleJoystickDemo() {
super("SimpleJoystickDemo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(displayWidth, displayHeight);
setLocationRelativeTo(null);
position = new Point();
SimpleJoystick myJoystick = new SimpleJoystick(150, position, 100);
add(myJoystick, BorderLayout.PAGE_END);
Drawing drawing = new Drawing(position);
add(drawing);
}
public static void main(final String[] args) {
Runnable gui = new Runnable() {
#Override
public void run() {
new SimpleJoystickDemo().setVisible(true);
}
};
SwingUtilities.invokeLater(gui);
}
private class Drawing extends JPanel {
private static final long serialVersionUID = 1L;
private final Point position;
public Drawing(Point position) {
this.position = position;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
g2.fillOval(160 + position.x, 160 - position.y, 15, 15);
}
}
}
class SimpleJoystick extends JPanel {
private static final long serialVersionUID = 1L;
//Maximum value for full horiz or vert position where centered is 0:
private int joyOutputRange;
private float joySize; //joystick icon size
private float joyWidth, joyHeight;
private float joyCenterX, joyCenterY; //Joystick displayed Center
//Display positions for text feedback values:
private int textHorizPos, textVertPos;
private int fontSpace = 12;
private float curJoyAngle; //Current joystick angle
private float curJoySize; //Current joystick size
private boolean isMouseTracking;
private boolean leftMouseButton;
private int mouseX, mouseY;
private Stroke lineStroke = new BasicStroke(10, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND);
private final Point position;
public SimpleJoystick(final int joyOutputRange,
final Point position, final int joySize) {
this.joyOutputRange = joyOutputRange;
this.position = position;
this.joySize = joySize;
joyWidth = joySize;
joyHeight = joyWidth;
setPreferredSize(new Dimension((int) joyWidth + 250,
(int) joyHeight + 80));
joyCenterX = getPreferredSize().width / 2;
joyCenterY = getPreferredSize().height / 2;
this.joySize = joyWidth / 2;
setBackground(new Color(226, 226, 226));
MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mouseMoved(final MouseEvent e) {
mouseCheck(e);
}
#Override
public void mousePressed(final MouseEvent e) {
leftMouseButton = SwingUtilities.isLeftMouseButton(e);
mouseCheck(e);
}
};
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
private void mouseCheck(final MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
float dx = mouseX - joyCenterX;
float dy = mouseY - joyCenterY;
if (leftMouseButton) {
isMouseTracking = true;
} else {
isMouseTracking = false;
}
if (isMouseTracking) {
curJoyAngle = (float) Math.atan2(dy, dx);
curJoySize = (float) Point.distance(mouseX, mouseY,
joyCenterX, joyCenterY);
} else {
curJoySize = 0;
}
if (curJoySize > joySize) {
curJoySize = joySize;
}
position.x = (int) (joyOutputRange * (Math.cos(curJoyAngle)
* curJoySize) / joySize);
position.y = (int) (joyOutputRange * (-(Math.sin(curJoyAngle)
* curJoySize) / joySize));
SwingUtilities.getRoot(SimpleJoystick.this).repaint();
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.LIGHT_GRAY);
g2.fillOval((int) (joyCenterX - joyWidth / 2),
(int) (joyCenterY - joyHeight / 2),
(int) joyWidth, (int) joyHeight);
//rotate and draw joystick line segment:
Graphics2D g3 = (Graphics2D) g2.create();
g3.translate(joyCenterX, joyCenterY);
g3.rotate(curJoyAngle);
g3.setColor(Color.GRAY);
g3.setStroke(lineStroke);
g3.drawLine(0, 0, (int) curJoySize, 0);
g3.dispose();
//
g2.setColor(Color.GRAY);
g2.fillOval((int) joyCenterX - 10, (int) joyCenterY - 10, 20, 20);
textHorizPos = 50;
textVertPos = (int) (joyCenterY - 50);
g2.drawString("Horizont:", textHorizPos, textVertPos);
textHorizPos += (4 * fontSpace);
g2.drawString(String.valueOf(position.x), textHorizPos, textVertPos);
textHorizPos = 50;
textVertPos += 12;
g2.drawString("Vertical :", textHorizPos, textVertPos);
textHorizPos += (4 * fontSpace);
g2.drawString(String.valueOf(position.y), textHorizPos, textVertPos);
}
}
Reworked code from #tutejszy. Warnings removed and the missing PointChangeEvent added.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class VJoystick extends JPanel implements ChangeListener
{
private JLabel lblPosition;
private static final long serialVersionUID = 1L;
public VJoystick()
{
setLayout(new BorderLayout(0, 0));
SimpleJoystick myJoystick = new SimpleJoystick(150);
myJoystick.setPreferredSize(new Dimension(100,100));
myJoystick.addChangeListener(this);
add(myJoystick, BorderLayout.CENTER);
lblPosition = new JLabel("position");
add(lblPosition, BorderLayout.SOUTH);
}
#Override
public void stateChanged(ChangeEvent ev) {
Point p = null;
try {
p = ((PointChangeEvent)ev).p;
} catch (Exception e) {
return;
}
lblPosition.setText("x="+p.x+" y="+p.y);
}
}
class SimpleJoystick extends JPanel
{
private static final long serialVersionUID = 1L;
/** Maximum value for full horiz or vert position where centered is 0 */
private int joyOutputRange;
/** max x and y value, in pixels */
private int joyRadius;
/** Joystick displayed Center, in pixels */
private int joyCenterX, joyCenterY;
/** joystick output position scaled to given joyOutputRange */
private Point position = new Point();
/** joystick x axis value in pixels */
private int dx = 0;
/** joystick y axis value in pixels */
private int dy = 0;
/**
* #param joyOutputRange
*/
public SimpleJoystick(final int joyOutputRange) {
this.joyOutputRange = joyOutputRange;
setBackground(new Color(226, 226, 226));
MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && cursorChanged(e.getX(), e.getY())) {
SwingUtilities.getRoot(SimpleJoystick.this).repaint();
fireStateChanged();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && cursorChanged(e.getX(), e.getY())) {
SwingUtilities.getRoot(SimpleJoystick.this).repaint();
fireStateChanged();
}
}
};
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
private boolean cursorChanged(int mouseX, int mouseY) {
if (joyRadius == 0) return false;
dx = mouseX - joyCenterX;
dy = mouseY - joyCenterY;
if (dx > joyRadius) dx = joyRadius;
if (dy > joyRadius) dy = joyRadius;
if (dx < -joyRadius) dx = -joyRadius;
if (dy < -joyRadius) dy = -joyRadius;
position.x = joyOutputRange * dx / joyRadius;
position.y = -joyOutputRange * dy / joyRadius;
return true;
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
int joyWidth = getSize().width;
int joyHeight = getSize().height;
joyRadius = Math.min(joyWidth, joyHeight) / 2;
if (joyRadius == 0) return;
joyCenterX = joyWidth / 2;
joyCenterY = joyHeight / 2;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int diameter;
//background
g2.setColor(Color.LIGHT_GRAY);
diameter = joyRadius*2;
g2.fillOval(joyCenterX - diameter/2 , joyCenterY - diameter/2, diameter, diameter);
g2.setColor(Color.RED);
diameter = 40;
g2.fillOval(joyCenterX + dx - diameter/2 , joyCenterY + dy - diameter/2, diameter, diameter);
//thumb
g2.setColor(Color.GRAY);
diameter = 20;
g2.fillOval(joyCenterX - diameter/2 , joyCenterY - diameter/2, diameter, diameter);
}
void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
protected void fireStateChanged() {
ChangeEvent e = new PointChangeEvent(this, position);
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
((ChangeListener) listeners[i + 1]).stateChanged(e);
}
}
}
}
class PointChangeEvent extends ChangeEvent
{
private static final long serialVersionUID = 1L;
public Point p;
public PointChangeEvent(Object source, Point p)
{
super(source);
this.p=p;
}
}
This is reworked code from #mKorbel, it's event based and more swing-oriented, without floats:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class JoyDemo extends JPanel implements ChangeListener {
private JLabel lblPosition;
public JoyDemo() {
setLayout(new BorderLayout(0, 0));
SimpleJoystick myJoystick = new SimpleJoystick(150);
myJoystick.setPreferredSize(new Dimension(100,100));
myJoystick.addChangeListener(this);
add(myJoystick, BorderLayout.CENTER);
lblPosition = new JLabel("position");
add(lblPosition, BorderLayout.SOUTH);
}
#Override
public void stateChanged(ChangeEvent ev) {
Point p = null;
try {
p = ((PointChangeEvent)ev).p;
} catch (Exception e) {
return;
}
lblPosition.setText("x="+p.x+" y="+p.y);
}
}
class SimpleJoystick extends JPanel {
/** Maximum value for full horiz or vert position where centered is 0 */
private int joyOutputRange;
/** max x and y value, in pixels */
private int joyRadius;
/** Joystick displayed Center, in pixels */
private int joyCenterX, joyCenterY;
/** joystick output position scaled to given joyOutputRange */
private Point position = new Point();
/** joystick x axis value in pixels */
private int dx = 0;
/** joystick y axis value in pixels */
private int dy = 0;
/**
* #param joyOutputRange
*/
public SimpleJoystick(final int joyOutputRange) {
this.joyOutputRange = joyOutputRange;
setBackground(new Color(226, 226, 226));
MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && cursorChanged(e.getX(), e.getY())) {
SwingUtilities.getRoot(SimpleJoystick.this).repaint();
fireStateChanged();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && cursorChanged(e.getX(), e.getY())) {
SwingUtilities.getRoot(SimpleJoystick.this).repaint();
fireStateChanged();
}
}
};
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
private boolean cursorChanged(int mouseX, int mouseY) {
if (joyRadius == 0) return false;
dx = mouseX - joyCenterX;
dy = mouseY - joyCenterY;
if (dx > joyRadius) dx = joyRadius;
if (dy > joyRadius) dy = joyRadius;
if (dx < -joyRadius) dx = -joyRadius;
if (dy < -joyRadius) dy = -joyRadius;
position.x = joyOutputRange * dx / joyRadius;
position.y = -joyOutputRange * dy / joyRadius;
return true;
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
int joyWidth = getSize().width;
int joyHeight = getSize().height;
joyRadius = Math.min(joyWidth, joyHeight) / 2;
if (joyRadius == 0) return;
joyCenterX = joyWidth / 2;
joyCenterY = joyHeight / 2;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int diameter;
//background
g2.setColor(Color.LIGHT_GRAY);
diameter = joyRadius*2;
g2.fillOval(joyCenterX - diameter/2 , joyCenterY - diameter/2, diameter, diameter);
g2.setColor(Color.RED);
diameter = 40;
g2.fillOval(joyCenterX + dx - diameter/2 , joyCenterY + dy - diameter/2, diameter, diameter);
//thumb
g2.setColor(Color.GRAY);
diameter = 20;
g2.fillOval(joyCenterX - diameter/2 , joyCenterY - diameter/2, diameter, diameter);
}
void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
protected void fireStateChanged() {
ChangeEvent e = new PointChangeEvent(this, position);
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
((ChangeListener) listeners[i + 1]).stateChanged(e);
}
}
}
}
Here's my solution. Note, I reworked #Dark.Rider's answer, who reworked #tutejszy's answer, who reworked #mKorbel's answer...
I made 2 files. One called Joystick.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.SwingUtilities;
public class Joystick extends javax.swing.JPanel {
private final int outputMax;
private final int thumbDiameter;
private final int thumbRadius;
private final int panelWidth;
private final int arrowRadius;
private final int BORDER_THICKNESS = 2;
private final Point thumbPos = new Point();
protected SwingPropertyChangeSupport propertySupporter = new SwingPropertyChangeSupport(this);
/**
* #param output_max The maximum value to scale output to. If this value was
* 5 and the joystick thumb was dragged to the top-left corner, the output
* would be (-5,5)
* #param panel_width how big the JPanel will be. The sizes of the joystick's
* visual components are proportional to this value
*/
public Joystick(int output_max, int panel_width) {
assert output_max > 0;
assert panel_width > 0;
outputMax = output_max;
panelWidth = panel_width;
thumbDiameter = panel_width/4;
thumbRadius = thumbDiameter/2;
arrowRadius = panel_width/24;
MouseAdapter mouseAdapter = new MouseAdapter() {
private void repaintAndTriggerListeners(){
SwingUtilities.getRoot(Joystick.this).repaint();
propertySupporter.firePropertyChange(null, null, getOutputPos());
}
#Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
updateThumbPos(e.getX(), e.getY());
repaintAndTriggerListeners();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
updateThumbPos(e.getX(), e.getY());
repaintAndTriggerListeners();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
centerThumbPad();
repaintAndTriggerListeners();
}
}
};
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
setPreferredSize(new java.awt.Dimension(panel_width, panel_width));
setOpaque(false);
centerThumbPad();
}
private void centerThumbPad(){
thumbPos.x = panelWidth/2;
thumbPos.y = panelWidth/2;
}
/**
* update both thumbPos
* #param mouseX the x position of cursor that has clicked in the joystick panel
* #param mouseY the y position of cursor that has clicked in the joystick panel
* #return
*/
private void updateThumbPos(int mouseX, int mouseY) {
// if the cursor is clicked out of bounds, we'll modify the position
// to be the closest point where we can draw the thumb pad completely
if (mouseX < thumbRadius)
mouseX = thumbRadius;
else if(mouseX > panelWidth - thumbRadius)
mouseX = panelWidth - thumbRadius;
if (mouseY < thumbRadius)
mouseY = thumbRadius;
else if(mouseY > panelWidth - thumbRadius)
mouseY = panelWidth - thumbRadius;
thumbPos.x = mouseX;
thumbPos.y = mouseY;
}
/**
* #return the scaled position of the joystick thumb pad
*/
Point getOutputPos(){
Point result = new Point();
result.x = outputMax * (thumbPos.x - panelWidth/2) / (panelWidth/2-thumbDiameter/2);
result.y = -outputMax * (thumbPos.y - panelWidth/2) / (panelWidth/2-thumbDiameter/2);
return result;
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
//joystick background border
g.setColor(Color.BLACK);
g.fillOval(thumbRadius, thumbRadius, panelWidth-thumbDiameter, panelWidth-thumbDiameter);
//joystick background color
g.setColor(Color.GRAY);
g.fillOval(thumbRadius+BORDER_THICKNESS, thumbRadius+BORDER_THICKNESS, panelWidth-thumbDiameter-BORDER_THICKNESS*2, panelWidth-thumbDiameter-BORDER_THICKNESS*2);
//joystick background arrows
g.setColor(Color.BLACK);
int[] left_x = {thumbDiameter-arrowRadius,thumbDiameter+arrowRadius,thumbDiameter+arrowRadius};
int[] left_y = {panelWidth/2,panelWidth/2+arrowRadius,panelWidth/2-arrowRadius};
g.fillPolygon(left_x, left_y,3);
int[] right_x = {panelWidth-thumbDiameter+arrowRadius,panelWidth-thumbDiameter-arrowRadius,panelWidth-thumbDiameter-arrowRadius};
int[] right_y = {panelWidth/2,panelWidth/2+arrowRadius,panelWidth/2-arrowRadius};
g.fillPolygon(right_x, right_y,3);
int[] up_x = left_y;
int[] up_y = left_x;
g.fillPolygon(up_x, up_y,3);
int[] down_x = right_y;
int[] down_y = right_x;
g.fillPolygon(down_x, down_y,3);
//thumb pad border
g.setColor(Color.BLACK);
g.fillOval(thumbPos.x - thumbRadius - BORDER_THICKNESS, thumbPos.y - thumbRadius - BORDER_THICKNESS, thumbRadius*2+BORDER_THICKNESS*2, thumbRadius*2+BORDER_THICKNESS*2);
//thumb pad color
g.setColor(Color.GRAY);
g.fillOval(thumbPos.x - thumbRadius, thumbPos.y - thumbRadius, thumbRadius*2, thumbRadius*2);
}
#Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupporter.addPropertyChangeListener(listener);
}
#Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupporter.removePropertyChangeListener(listener);
}
}
and one called JoystickOutputContainer.java (used to make example pictures)
import java.awt.BorderLayout;
import java.awt.Point;
import java.beans.PropertyChangeListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JoystickOutputContainer extends JPanel {
private Joystick myJoystick = new Joystick(100, 140);
private JLabel lblPosition = new JLabel("x=0 y=0");
public JoystickOutputContainer() {
setLayout(new BorderLayout(0, 0));
add(myJoystick, BorderLayout.CENTER);
add(lblPosition, BorderLayout.SOUTH);
myJoystick.addPropertyChangeListener(updateConsoleListener);
}
private final PropertyChangeListener updateConsoleListener = (evt) -> {
updateConsoleCallback( (Point) evt.getNewValue() );
};
private void updateConsoleCallback(Point p){
lblPosition.setText("x="+p.x+" y="+p.y);
}
}
I'm building a little "pong" game in Java.
I'm trying to add a scorekeeper up top that shows the updated score (+1) everytime the player saves the ball with the paddle.
I'm trying to use a JLabel but the problem is that I can't think of a way to continuously update the JLabel each time the paddle is hit.
Any ideas?
My code:
MainPanel Class (the one with the Paddle and Ball and Label)
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.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
//import swing.graphics.BounceFrame;
//import swing.graphics.Circle;
public class MainPanel extends JPanel implements ActionListener, KeyListener, Runnable{
public Paddle paddle;
public Ball ball;
public MainPanel(){
ball = new Ball(50, 50, 10); //centerX, centerY, radius
setSize(300, 300);
paddle = new Paddle();
JLabel scoreKeeper = new JLabel("Score" + ball.getScore());
add(scoreKeeper);
Thread thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
paddle.draw(g2);
ball.draw(g2);
}
public void actionPerformed(ActionEvent e) {
String direction = e.getActionCommand();
switch(direction){
case "left": Paddle.movePaddleLeft(); break;
case "right": Paddle.movePaddleRight(); break;
}
this.repaint();
}
public void run() {
try {
while(true){
ball.move(getBounds());
repaint();
Thread.sleep(500/30);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37){
Paddle.movePaddleLeft();
}
if (e.getKeyCode() == 39){
Paddle.movePaddleRight();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And my Ball class:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.Random;
public class Ball {
private Ellipse2D ball;
private double radius;
private double ballCircumference;
private Color color;
private double x;
private double y;
private double dx = 5;
private double dy = 5;
private int score = 0;
public int getScore() {
return score;
}
//Boundaries to determine if ball is hit by paddle
private double criticalBoundaryX;
private double criticalBoundaryY1;
private double criticalBoundaryY2;
private double paddleHalfwayPoint;
private boolean inGame = true;
public void recalculateCriticals(){
criticalBoundaryX = Paddle.getYPosition() - ballCircumference;
criticalBoundaryY1 = Paddle.getXPosition()- ballCircumference; //Left boundary
criticalBoundaryY2 = Paddle.getXPosition()+Paddle.getPaddleWidth()+ballCircumference; //Right Boundary
paddleHalfwayPoint = (Paddle.getXPosition()+Paddle.getPaddleWidth())/2;
}
public Ball(int centerX, int centerY, int radius) {
this.x = centerX - radius;
this.y = centerY - radius;
this.radius = radius;
ballCircumference = 2*radius;
Random randomRGB = new Random();
color = new Color(randomRGB.nextInt(255), randomRGB.nextInt(255), randomRGB.nextInt(255));
this.ball = new Ellipse2D.Double(x, y, 2*radius, 2*radius);
}
public void move(Rectangle2D bounds) {
recalculateCriticals();
x += dx;
y += dy;
if (x < bounds.getMinX()) {
x = bounds.getMinX();
dx = -dx;
}
if (x + 2*radius >= bounds.getMaxX()) {
//System.out.println(bounds.getMaxX());
x = bounds.getMaxX() - 2*radius;
dx = -dx;
}
if (y < bounds.getMinY()) {
y = bounds.getMinY();
dy = -dy;
}
if (y > criticalBoundaryX){
if (x < criticalBoundaryY1 || x > criticalBoundaryY2){
inGame = false;
}
if (!inGame && hittingEdge(x))
dx = -dx;
}
if (y > criticalBoundaryX && inGame){ //When it hits the paddle
changeColor();
score++;
y = criticalBoundaryX;
dy = -dy;
}
if (y > bounds.getMaxY()){
System.out.println("Game Over");
System.exit(0);
}
recalculateCriticals();
ball.setFrame(x, y, 2*radius, 2*radius);
}
public boolean onPaddle(double x){
return ((x > Paddle.getXPosition()) && (x < Paddle.getXPosition()+Paddle.getPaddleWidth()) && (y > Paddle.getYPosition()-10));
}
public boolean hittingEdge(double x){
return ((x >= criticalBoundaryY1 && x < paddleHalfwayPoint)
||
(x <= criticalBoundaryY1 && x > paddleHalfwayPoint)); //Return true if x is hitting the side edge of the paddle
}
public void changeColor(){
Random randomColor = new Random();
color = new Color(randomColor.nextInt(255), randomColor.nextInt(255), randomColor.nextInt(255));
}
public void draw(Graphics2D g2) {
g2.setColor(color);
g2.fill(ball);
}
}
The "Java way" of doing this would be to define a listener interface, for example:
public interface BallListener {
void paddleHit();
}
In the Ball class, you should add a field
private List<BallListener> listeners;
as well as methods
public void addBallListener(BallListener l) { listeners.add(l); }
public void removeBallListener(BallListener l) { listeners.remove(l); }
When the paddle is hit, you go:
for (BallListener l : listeners)
l.paddleHit();
The main class should implement the BallListener interface, and register itself with the ball (ball.addBallListener(this)).
This approach also enables you to, when needed, inform other parts of your program about different events that happen to the ball (i.e. add a new method to BallListener for each event you'd like to signal).