I (A novice programmer) am trying to paint an oval over a JPanel. I am trying to use the method paint. However, it requires a Graphics argument. I get a NullPointerException when I include my Graphics as a argument because it is null, but I do not know how else to paint the oval. I tried repaint instead but nothing happened. Any help would be appreciated. Here is my main class:
public class Checkers extends JPanel{
public static final int BOARDSQUARES = 8;
public static final int BOARDSIZE = 75;
private JPanel[][] board;
private final Point point1;
private final LineBorder border1;
public JFrame frame;
checkerPiece piece = new checkerPiece(this);
Graphics g;
public Checkers(){
board = new JPanel[BOARDSQUARES][BOARDSQUARES];
point1 = new Point (BOARDSIZE,BOARDSIZE);
border1=new LineBorder(Color.BLACK, 1);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Checkers checkers = new Checkers();
checkers.frame=checkers.createJFrame();
checkers.board =checkers.createBoard(checkers.board, checkers.point1, checkers.border1);
for (int y=0;y<BOARDSQUARES;y++){
for (int x = 0;x<BOARDSQUARES;x++){
checkers.frame.getContentPane().add(checkers.board[y][x]);
}
}
checkers.paint(checkers.g);
}
private JPanel[][] createBoard (JPanel[][] board, Point point, LineBorder border1){
for (int row = 0; row<BOARDSQUARES;row++){
point.y=BOARDSIZE;
for (int col = 0; col <BOARDSQUARES;col++){
board[row][col] = new JPanel();
board[row][col].setLocation(point);
board[row][col].setVisible(true);
board[row][col].setSize(BOARDSIZE,BOARDSIZE);
board[row][col].setOpaque(true);
if ((row%2==0&&col%2==0)||(row%2==1&&col%2==1)){
board[row][col].setBackground(new Color (230,200,150));
} else if ((row%2==0&&col%2==1)||(row%2==1&&col%2==0)) {
board[row][col].setBackground(new Color (165, 42,42) );
}
board[row][col].setBorder(border1);
point.y = point.y+BOARDSIZE;
}
point.x=point.x+BOARDSIZE;
}
return board;
}
private JFrame createJFrame (){
JFrame mainFrame = new JFrame("Checkers");
mainFrame.setSize(1000,1000);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new Checkers());
return mainFrame;
}
#Override
public void paint (Graphics g){
System.out.println("hi");
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
piece.paint(g2d,board[0][0].getLocation().x,board[0][0].getLocation().y,Color.BLACK);
}
}
A necessary snippet from my other class (cherkerPiece piece):
public void paint (Graphics2D g, int x, int y, Color color){
g.setColor(color);
g.fillOval(x, y, DIAMETER, DIAMETER);
}
Thank you for your help
To create something as complex as a checkers game, you should follow the model / view / controller pattern when creating your Java Swing GUI.
I created a model class for a checker board square and another model class for a checker piece. I created a model class for the checker board and another model class to hold all of the checker pieces.
I created a view class to draw the checker board. I created another view class to create the main window.
I did not create any controller classes. This code just shows you how to draw a checker board. I put all of the classes together to make it easier to paste the code. You should separate the classes into separate Java files.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckerBoard implements Runnable {
private Board board;
private CheckerBoardPanel checkerBoardPanel;
private JFrame frame;
private Pieces pieces;
public static void main(String[] args) {
SwingUtilities.invokeLater(new CheckerBoard());
}
public CheckerBoard() {
this.board = new Board();
this.pieces = new Pieces();
}
#Override
public void run() {
frame = new JFrame("Checker Board");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
checkerBoardPanel = new CheckerBoardPanel(board, pieces);
frame.add(checkerBoardPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class CheckerBoardPanel extends JPanel {
private static final long serialVersionUID = 3770663347384271771L;
private Board board;
private Pieces pieces;
public CheckerBoardPanel(Board board, Pieces pieces) {
this.board = board;
this.pieces = pieces;
this.setPreferredSize(board.getPreferredSize());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Square[][] checkerBoard = board.getBoard();
for (int row = 0; row < checkerBoard.length; row++) {
for (int column = 0; column < checkerBoard[row].length; column++) {
Square square = checkerBoard[row][column];
Rectangle drawingRectangle = square.getDrawingRectangle();
g.setColor(square.getColor());
g.fillRect(drawingRectangle.x, drawingRectangle.y,
drawingRectangle.width, drawingRectangle.height);
}
}
List<Piece> checkerPieces = pieces.getPieces();
for (Piece checkerPiece : checkerPieces) {
Point coordinate = checkerPiece.getCoordinate();
Rectangle drawingRectangle = checkerBoard[coordinate.x][coordinate.y]
.getDrawingRectangle();
int x = drawingRectangle.x + drawingRectangle.width / 2;
int y = drawingRectangle.y + drawingRectangle.height / 2;
int radius = board.getSquareWidth() * 2 / 6;
g.setColor(checkerPiece.getColor());
g.fillOval(x - radius, y - radius, radius + radius, radius
+ radius);
}
}
}
public class Board {
private static final int BOARD_WIDTH = 8;
private static final int SQUARE_WIDTH = 64;
private Square[][] board;
public Board() {
this.board = initalizeBoard(BOARD_WIDTH, SQUARE_WIDTH);
}
private Square[][] initalizeBoard(int boardWidth, int squareWidth) {
Square[][] board = new Square[boardWidth][boardWidth];
int x = 0;
int y = 0;
for (int row = 0; row < boardWidth; row++) {
for (int column = 0; column < boardWidth; column++) {
Square square = new Square();
if (isLightSquare(row, column)) {
square.setColor(Color.WHITE);
} else {
square.setColor(Color.LIGHT_GRAY);
}
square.setCoordinate(new Point(row, column));
square.setDrawingRectangle(new Rectangle(x, y, squareWidth,
squareWidth));
board[row][column] = square;
x += squareWidth;
}
x = 0;
y += squareWidth;
}
return board;
}
public boolean isLightSquare(int row, int column) {
if (row % 2 == 0) {
if (column % 2 == 0) {
return true;
} else {
return false;
}
} else {
if (column % 2 == 0) {
return false;
} else {
return true;
}
}
}
public Dimension getPreferredSize() {
int width = SQUARE_WIDTH * 8 + 1;
return new Dimension(width, width);
}
public Square[][] getBoard() {
return board;
}
public int getSquareWidth() {
return SQUARE_WIDTH;
}
}
public class Square {
private Color color;
private Point coordinate;
private Rectangle drawingRectangle;
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
public Rectangle getDrawingRectangle() {
return drawingRectangle;
}
public void setDrawingRectangle(Rectangle drawingRectangle) {
this.drawingRectangle = drawingRectangle;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
public class Pieces {
private List<Piece> pieces;
public Pieces() {
this.pieces = addPieces();
}
private List<Piece> addPieces() {
List<Piece> pieces = new ArrayList<Piece>();
Piece piece = new Piece();
piece.setColor(Color.RED);
piece.setCoordinate(new Point(2, 1));
pieces.add(piece);
piece = new Piece();
piece.setColor(Color.BLACK);
piece.setCoordinate(new Point(5, 0));
pieces.add(piece);
// Add the rest of the red and black pieces here
return pieces;
}
public List<Piece> getPieces() {
return pieces;
}
public void addPiece(Piece piece) {
this.pieces.add(piece);
}
}
public class Piece {
private Color color;
private Point coordinate;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
}
}
you need to add a class that extends Canvas and do all your painting in that class. like this
public class FirstWindow extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public FirstWindow()
{
super("Kayte does not go to water parks");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
}
public class Start extends Canvas implements Runnable
public class Main
{
public static void main(String arg[])
{
FirstWindow fw = new FirstWindow();
Start game = new Start(500, 500);
fw.add(game);
fw.setVisible(true);
new Thread(game).start();
}
}
Related
I know there are super many questions here on stack overflow about JElements not showing up, all because someone forgot to add a setVisible(true) at the end of the constructor. But at least I belive my problem is something different. I am currently creating a chess-game for college, and for that I have the
Game class: here it all comes together
the abstract Piece class extending JButton in package Pieces
and a class for Each Piece (Rook, Bishop, ...) each extending Piece and being located in the Pieces package
before I write much more and it is a dumb error again, here the code:
import javax.swing.*;
import Pieces.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game extends JFrame {
private static final int width = 8;
private static final int height = 8;
private static Piece clicked;
private static Piece[][] fields = new Piece[width][height];
private JPanel main = new JPanel();
public static void init(JPanel g) {
for (int y = 0; y < fields.length; y++) {
for (int x = 0; x < fields[y].length; x++) {
if (y == 1) fields[y][x] = new Pawn(x, y, true); //2nd or 7th row is filled with pawns
else if (y == 6) fields[y][x] = new Pawn(x, y, false);
else {
fields[y][x] = new Empty(x,y,true);
}
fields[y][x].addActionListener(e -> {
var p = (Piece) e.getSource();
System.out.println(p.getX() + p.getY());
});
g.add(fields[y][x]);
}
}
}
public Game() {
main.setBackground(Color.blue.darker());
main.setLayout(new GridLayout(8,8));
this.setSize(800,800);
init(main);
this.add(main);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
var g = new Game();
}
}
package Pieces;
import javax.swing.*;
public abstract class Piece extends JButton {
private int x;
private int y;
private final boolean isWhite;
public Piece(int x, int y, boolean isWhite) {
this.x = x;
this.y = y;
this.isWhite = isWhite;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isWhite() {
return isWhite;
}
public boolean canMoveTo(int toX, int toY) {
return true;
}
}
each Piece-extending class is setup exactly like this:
package Pieces;
import java.awt.*;
public class Pawn extends Piece{
public Pawn(int x, int y, boolean isWhite) {
super(x, y, isWhite);
this.setText(isWhite ? "Pawn" : "pawn");
}
}
Expected behavior:
open a window with 64 JButtons in it, displaying the name of the Piece they represent (there is indeed an Empty-class for non-used fields)
Actual behavior:
opens a window with one button at the top left but first when I go over the fields with my cursor the buttons start appearing
state 1: state 1
state 2: state 2
You can't override getX and getY like this, these properties are used by the layout managers to layout the components.
Instead, maybe make use of Point to store the virtual or "cell" position
public static abstract class Piece extends JButton {
private final boolean isWhite;
private Point cell;
public Piece(int x, int y, boolean isWhite) {
cell = new Point(x, y);
this.isWhite = isWhite;
}
public Point getCell() {
return cell;
}
public boolean isWhite() {
return isWhite;
}
public boolean canMoveTo(int toX, int toY) {
return true;
}
}
Runnable example...
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new BoardPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BoardPane extends JPanel {
private static final int width = 8;
private static final int height = 8;
private Piece clicked;
private Piece[][] fields = new Piece[width][height];
public BoardPane() {
setBackground(Color.blue.darker());
setLayout(new GridLayout(8, 8));
buildBoard();
}
protected void buildBoard() {
for (int y = 0; y < fields.length; y++) {
for (int x = 0; x < fields[y].length; x++) {
if (y == 1) {
fields[y][x] = new Pawn(x, y, true); //2nd or 7th row is filled with pawns
} else if (y == 6) {
fields[y][x] = new Pawn(x, y, false);
} else {
fields[y][x] = new Empty(x,y,true);
}
fields[y][x].addActionListener(e -> {
var p = (Piece) e.getSource();
System.out.println(p.getCell());
});
add(fields[y][x]);
}
}
}
}
public static abstract class Piece extends JButton {
private final boolean isWhite;
private Point cell;
public Piece(int x, int y, boolean isWhite) {
cell = new Point(x, y);
this.isWhite = isWhite;
}
public Point getCell() {
return cell;
}
public boolean isWhite() {
return isWhite;
}
public boolean canMoveTo(int toX, int toY) {
return true;
}
}
public static class Pawn extends Piece {
public Pawn(int x, int y, boolean isWhite) {
super(x, y, isWhite);
this.setText(isWhite ? "Pawn" : "pawn");
}
}
public static class Empty extends Piece {
public Empty(int x, int y, boolean isWhite) {
super(x, y, isWhite);
this.setText("X");
}
}
}
So I created a simple simple simulation where squares are spawned randomly with random vectors and bounce of the edges of the window.
I wanted it to take into account the window being resized. So that if I change the dimensions of the window from 600x600 to 1200x600 the squares will bounce of the new border rather than 600x600.
I tried doing getWidth() getHeight() but it would return 0.
So I put it in the pain() (since it gets called on window resize) method and saved the return values as local variables. But I cannot call getjpWidth() from the Rect class.
So basically what I need is to get new window dimension into the move() method in the Rect class.
Please feel free to point out any other mistakes and things that can be done better. I'm new to 2D programming (studying Computer Science)
Application
import javax.swing.*;
public class Application {
private Application(){
//create a JFrame window
JFrame frame = new JFrame("Moving Squares");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add a JPanel
GamePanel gamePanel = new GamePanel();
frame.add(gamePanel);
//pack the window around the content
frame.pack();
//center
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]){
new Application();
}
}
GamePanel
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
public class GamePanel extends JPanel implements Runnable{
private int jpWidth=0, jpHeight=0;
//set JPanel size
private static final Dimension DESIRED_SIZE = new Dimension(600,600);
#Override
public Dimension getPreferredSize(){
return DESIRED_SIZE;
}
//constructor
GamePanel(){
Thread t = new Thread(this);
t.start();
}
private ArrayList <Rect> rect=new ArrayList<>();
public void run(){
for(int i=0; i<15; i++){
rect.add(new Rect());
}
while(true){
for(Rect rect:rect){
rect.move();
}
//repaint still image for better frames
//should be 100fps instead it's >144fps
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){/**/};
}
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
jpWidth=getWidth();
jpHeight=getHeight();
g2d.setColor(Color.white);
g2d.fillRect(0,0,jpWidth,jpHeight);
for(Rect rect:rect) {
g2d.setColor(Color.black);
g2d.fillRect(rect.getXcord()-1, rect.getYcord()-1, rect.getWidth()+2, rect.getHeight()+2);
g2d.setColor(Color.getHSBColor(rect.getR(), rect.getG(), rect.getB()));
g2d.fillRect(rect.getXcord(), rect.getYcord(), rect.getWidth(), rect.getHeight());
}
}
public int getJpWidth() {
return jpWidth;
}
public int getJpHeight() {
return jpHeight;
}
}
Rect
import java.util.Random;
public class Rect {
//properties
private int width=30, height=30;
private int R, G, B;
//movement
private int xCord, yCord;
private int xVector, yVector;
private int xSlope, ySlope;
public Rect(){
Random rand = new Random();
//random color
R=rand.nextInt(255);
G=rand.nextInt(255);
B=rand.nextInt(255);
//random spawn position
xCord=rand.nextInt(600-width);
yCord=rand.nextInt(600-height);
//direction
do{
xVector=rand.nextInt(3) - 1;
yVector=rand.nextInt(3) - 1;
}while(xVector==0 || yVector==0);
//slope
do{
xSlope=rand.nextInt(3);
ySlope=rand.nextInt(3);
}while(xSlope==0 || ySlope==0);
xVector*=xSlope;
yVector*=ySlope;
}
public void move(){
//if(xCord>=//how to get screen width ? ){}
if((xCord>=600-width) || (xCord<=0)){
bounceX();
}
if((yCord>=600-height) || (yCord<=0)) {
bounceY();
}
xCord+=xVector;
yCord+=yVector;
}
public void bounceX(){
xVector*=-1;
}
public void bounceY(){
yVector*=-1;
}
public int getR() {
return R;
}
public int getG() {
return G;
}
public int getB() {
return B;
}
public int getXcord() {
return xCord;
}
public int getYcord() {
return yCord;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
}
So basically what I need is to get new window dimension into the move() method in the Rect class.
Don't know if it is the best design but I pass the "panel" as a parameter to the "move()" method so its width/height can be used.
Here is some old code I have lying around that shows this approach:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class BallAnimation4
{
private static void createAndShowUI()
{
BallPanel panel = new BallPanel();
JFrame frame = new JFrame("BallAnimation4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.pack();
frame.setLocationRelativeTo( null );
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible( true );
panel.addBalls(5);
panel.startAnimation();
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
class BallPanel extends JPanel implements ActionListener
{
private ArrayList<Ball> balls = new ArrayList<Ball>();
public BallPanel()
{
setLayout( null );
// setBackground( Color.BLACK );
}
public void addBalls(int ballCount)
{
Random random = new Random();
for (int i = 0; i < ballCount; i++)
{
Ball ball = new Ball();
ball.setRandomColor(true);
ball.setLocation(random.nextInt(getWidth()), random.nextInt(getHeight()));
// ball.setMoveRate(32, 32, 1, 1, true);
ball.setMoveRate(16, 16, 1, 1, true);
// ball.setSize(32, 32);
ball.setSize(64, 64);
balls.add( ball );
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Ball ball: balls)
{
ball.draw(g);
}
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(800, 600);
}
public void startAnimation()
{
Timer timer = new Timer(1000/60, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
move();
repaint();
}
private void move()
{
for (Ball ball : balls)
{
ball.move(this);
}
}
class Ball
{
public Color color = Color.BLACK;
public int x = 0;
public int y = 0;
public int width = 1;
public int height = 1;
private int moveX = 1;
private int moveY = 1;
private int directionX = 1;
private int directionY = 1;
private int xScale = moveX;
private int yScale = moveY;
private boolean randomMove = false;
private boolean randomColor = false;
private Random myRand = null;
public Ball()
{
myRand = new Random();
setRandomColor(randomColor);
}
public void move(JPanel parent)
{
int iRight = parent.getSize().width;
int iBottom = parent.getSize().height;
x += 5 + (xScale * directionX);
y += 5 + (yScale * directionY);
if (x <= 0)
{
x = 0;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (x >= iRight - width)
{
x = iRight - width;
directionX *= (-1);
xScale = randomMove ? myRand.nextInt(moveX) : moveX;
if (randomColor) setRandomColor(randomColor);
}
if (y <= 0)
{
y = 0;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
if (y >= iBottom - height)
{
y = iBottom - height;
directionY *= (-1);
yScale = randomMove ? myRand.nextInt(moveY) : moveY;
if (randomColor) setRandomColor(randomColor);
}
}
public void draw(Graphics g)
{
g.setColor(color);
g.fillOval(x, y, width, height);
}
public void setColor(Color c)
{
color = c;
}
public void setLocation(int x, int y)
{
this.x = x;
this.y = y;
}
public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove)
{
this.moveX = xMove;
this.moveY = yMove;
directionX = xDir;
directionY = yDir;
randomMove = randMove;
}
public void setRandomColor(boolean randomColor)
{
this.randomColor = randomColor;
switch (myRand.nextInt(3))
{
case 0: color = Color.BLUE;
break;
case 1: color = Color.GREEN;
break;
case 2: color = Color.RED;
break;
default: color = Color.BLACK;
break;
}
}
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
}
}
Also, note that for animation you should be using a Swing Timer to schedule the animation. Updates to Swing components should be done on the Event Dispatch Thread (EDT). While not likely to cause a problem with this simple application it is a good habit to make sure this basic rule is followed otherwise you can have random problems and it is never easy to debug a random problem.
I am trying to draw two circle on a panel with a line joining them, all after a button is pressed. So far (apart from tweaking locations of the line) this is ok. However, I would like to animate it using a timer. The first circle should appear, then gradually the line will be revealed, and finally the second circle.
I have looked at many examples of timers, but I can't seem to get it to work for me. I must be misunderstanding something.
here is the ball class (for each circle):
package twoBalls;
import java.awt.Color;
import java.awt.Point;
public class Ball {
private int x;
private int y;
private int r;
private Color color;
private Point location;
private Ball parent;
public Ball(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
Point p = new Point(x, y);
setLocation(p);
}
public void setParent(Ball b) {
parent = b;
}
public Ball getParent() {
return parent;
}
public void setx(int x) {
this.x = x;
}
public void sety(int y) {
this.y = y;
}
public int getx() {
return x;
}
public int gety() {
return y;
}
public int getr() {
return r;
}
public void setPreferedSize() {
}
public void setLocation(Point p) {
setx(p.x);
sety(p.y);
location = p;
}
public Point getLocation() {
return location;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
then the class that will store balls in an arrayList. And I think that this is where the actual drawing should take place, along with the timer.
I am trying to set the start and end point of the line to be the same, and increment the end point until it is where it should be, using the timer. I'm probably way of track, but that was the intention!
I have change this class, the if statements in the while loop can now be entered, as I am now comparing different point. But the line doesn't get drawn at all still.
package twoBalls;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
public class BallsArray extends JPanel implements ActionListener {
private ArrayList<Ball> balls;
private Timer timer;
private final int DELAY = 25;
private int xDest;
private int yDest;
private Point dest;
private Point starts;
private int xStart;
private int yStart;
public BallsArray() {
balls = new ArrayList<Ball>();
timer = new Timer(DELAY, this);
yDest = 0;
xDest = 0;
dest = new Point(xDest, yDest);
starts = new Point(xStart, yStart);
}
public void setDestXY(int x, int y) {
xDest = x;
yDest = y;
dest = new Point(xDest, yDest);
setDest(dest);
}
public void setDest(Point p) {
dest = p;
}
public Point getDest() {
return dest;
}
public void setStartsXY(int x, int y) {
xStart = x;
yStart = y;
starts = new Point(xStart, yStart);
setStarts(starts);
}
public void setStarts(Point p) {
starts = p;
}
public Point getStarts() {
return starts;
}
public void addBall(Ball b) {
balls.add(b);
}
public void addBall(int x, int y, int r) {
balls.add(new Ball(x, y, r));
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < balls.size(); i++) {
if (i == 0) {
paintBall(balls.get(0), g2);
}
if (i != 0) {
int j = i - 1;
Ball bp = balls.get(j);
Ball bc = balls.get(i);
bc.setParent(bp);
paintLine(bc, g2);
paintBall(bc, g2);
}
}
}
public void paintBall(Ball b, Graphics2D g2d) {
Ellipse2D circ = new Ellipse2D.Float(b.getx(), b.gety(), b.getr(),
b.getr());
g2d.draw(circ);
}
public void paintLine(Ball b, Graphics2D g2d) {
timer.start();
if (b != null && b.getLocation() != null) {
Ball parent = b.getParent();
if (parent != null) {
g2d.setColor(Color.GRAY);
if (parent.getLocation() != null && b.getLocation() != null) {
setDest(parent.getLocation());
setStarts(parent.getLocation());
g2d.draw(new Line2D.Float(starts, dest));
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// Not sure what I need to do here
// increment second location somehow
// Point s = getStarts();
Point p = getDest();
Point t = this.getLocation();
while (p != t) {
if (p.x != t.x && p.y != t.y) {
System.out.println("hello");
int x = dest.x;
int y = dest.y;
x++;
y++;
setDestXY(x, y);
p = getDest();
repaint();
} else if (p.x == t.x && p.y != t.y) {
System.out.println("part 2");
int y = dest.y;
y++;
setDestXY(dest.x, y);
p = getDest();
repaint();
} else if (p.x != t.x && p.y == t.y) {
System.out.println("part 3");
int x = dest.x;
x++;
setDestXY(x, dest.y);
p = getDest();
repaint();
}
repaint();
}
}
}
I have had a lot of help online getting this far, I worry I am just beyond my depth now!. I am unsure about the EventQueue/run part below. Here is the class to set it all up:
package twoBalls;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Display implements ActionListener {
private JFrame frame;
private JButton button;
private BallsArray b;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Display ex = new Display();
}
});
}
public Display() {
b = new BallsArray();
frame = new JFrame();
frame.setSize(800, 500);
frame.setTitle("Show balls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
button = new JButton("New Ball");
frame.add(button, BorderLayout.SOUTH);
frame.setVisible(true);
button.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Ball ball1 = new Ball(100, 100, 50);
b.addBall(ball1);
b.addBall(200, 200, 50);
frame.add(b, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
}
At the moment it draws the two circles, but not the line at all.
When you make an animation, it helps to use the model / view / controller pattern.
Here's the GUI I created from your code.
I simplified your Ball class. This is all you need to define a ball.
package twoBalls;
import java.awt.Color;
import java.awt.Point;
public class Ball {
private final int radius;
private final Color color;
private final Point center;
public Ball(int x, int y, int radius, Color color) {
this(new Point(x, y), radius, color);
}
public Ball(Point center, int radius, Color color) {
this.center = center;
this.radius = radius;
this.color = color;
}
public int getRadius() {
return radius;
}
public Color getColor() {
return color;
}
public Point getCenter() {
return center;
}
}
I created the GUIModel class to hold all of the information your GUI needs. This separates the model from the view.
package twoBalls;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class GUIModel {
private double direction;
private double distance;
private List<Ball> balls;
private Point lineStartPoint;
private Point lineEndPoint;
public GUIModel() {
this.balls = new ArrayList<>();
}
public void addBall(Ball ball) {
this.balls.add(ball);
}
public List<Ball> getBalls() {
return balls;
}
public void calculatePoints() {
this.lineStartPoint = balls.get(0).getCenter();
this.lineEndPoint = balls.get(1).getCenter();
this.distance = Point.distance(lineStartPoint.x, lineStartPoint.y,
lineEndPoint.x, lineEndPoint.y);
this.direction = Math.atan2(lineEndPoint.y - lineStartPoint.y,
lineEndPoint.x - lineStartPoint.x);
}
public Point getCurrentPoint(int pos, int total) {
double increment = distance / total;
double length = increment * pos;
double x = lineStartPoint.x + Math.cos(direction) * length;
double y = lineStartPoint.y - Math.sin(direction) * length;
x = Math.round(x);
y = Math.round(y);
return new Point((int) x, (int) y);
}
public Point getLineStartPoint() {
return lineStartPoint;
}
}
This class holds the two Ball instances, and calculates the length and direction of the line, divided into total increments.
Now that we've defined the model classes, let's look at the view classes. The first is your Display class.
package twoBalls;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Display implements Runnable {
private GUIModel guiModel;
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Display());
}
public Display() {
this.guiModel = new GUIModel();
Ball ball1 = new Ball(150, 200, 50, Color.BLUE);
Ball ball2 = new Ball(450, 200, 50, Color.GREEN);
guiModel.addBall(ball1);
guiModel.addBall(ball2);
guiModel.calculatePoints();
}
#Override
public void run() {
frame = new JFrame();
frame.setTitle("Show Balls Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
DrawingPanel drawingPanel = new DrawingPanel(guiModel);
panel.add(drawingPanel, BorderLayout.CENTER);
panel.add(createButtonPanel(drawingPanel), BorderLayout.SOUTH);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private JPanel createButtonPanel(DrawingPanel drawingPanel) {
JPanel panel = new JPanel();
JButton startButton = new JButton("Start Animation");
startButton.addActionListener(new StartAnimation(drawingPanel));
panel.add(startButton);
return panel;
}
public class StartAnimation implements ActionListener {
private DrawingPanel drawingPanel;
public StartAnimation(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
LineRunnable runnable = new LineRunnable(drawingPanel);
new Thread(runnable).start();
}
}
}
The constructor of the Display class sets up the GUI model.
The run method of the Display class constructs the GUI, and starts the animation.
See how I've separated the model and view.
The StartAnimation class is your controller. It starts the animation when you left click on the JButton. I'll discuss the LineRunnable class later.
Next, let's take a look at the DrawingPanel class.
package twoBalls;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.swing.JPanel;
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = -3709678584255542338L;
private boolean drawLine;
private int pos;
private int total;
private GUIModel guiModel;
public DrawingPanel(GUIModel guiModel) {
this.guiModel = guiModel;
this.drawLine = false;
this.setPreferredSize(new Dimension(600, 400));
}
public boolean isDrawLine() {
return drawLine;
}
public void setDrawLine(boolean drawLine) {
this.drawLine = drawLine;
}
public void setPos(int pos) {
this.pos = pos;
repaint();
}
public void setTotal(int total) {
this.total = total;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Ball ball : guiModel.getBalls()) {
g2d.setColor(ball.getColor());
Point center = ball.getCenter();
int radius = ball.getRadius();
g2d.fillOval(center.x - radius, center.y - radius, radius + radius,
radius + radius);
}
if (isDrawLine()) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(5.0F));
Point a = guiModel.getLineStartPoint();
Point b = guiModel.getCurrentPoint(pos, total);
g2d.drawLine(a.x, a.y, b.x, b.y);
}
}
}
The only thing this view class does is draw the balls and the line. The responsibility for calculating the length of the line belongs in the model.
I set the preferred size here, and use the pack method in the Display class to get the size of the JFrame. You usually want to know the dimensions of the drawing area, rather than the entire window.
Finally, let's look at the LineRunnable class. This is the class that controls the animation.
package twoBalls;
import java.awt.EventQueue;
public class LineRunnable implements Runnable {
private int total;
private DrawingPanel drawingPanel;
public LineRunnable(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
this.total = 240;
}
#Override
public void run() {
setDrawLine();
for (int pos = 0; pos <= total; pos++) {
setPos(pos);
sleep(50L);
}
}
private void setDrawLine() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
drawingPanel.setDrawLine(true);
drawingPanel.setTotal(total);
}
});
}
private void setPos(final int pos) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
drawingPanel.setPos(pos);
}
});
}
private void sleep(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
In the run method, we divide the line into 240 segments, and draw a segment every 50 milliseconds. It takes the GUI 12 seconds to draw the line. You can play with these numbers if you wish.
The for loop is a classic animation loop. First you update the model, which I'm doing through the drawing panel. Then you sleep.
This animation loop is running on a different thread from the GUI thread. This keeps the GUI responsive. Since the loop is running on a different thread, we have to use the invokeLater method to draw on the Event Dispatch thread.
I hope this was helpful to you. Divide and conquer. Don't let a class do more than one thing.
I have a problem in my application using line primitives and JLables. I try to explain it:
I have to draw a vehicle route using lines to represent roads and JLabels to represent cities. I need the use of JLabels because each JLabel has a Listener that shows a dialog with information about the city.
I redefine paint() method of my main JPanel. In that method I first in invoke the super.paint(), then I draw the lines and finally I add the Labels to the JPanel.
The problem is that the lines overlap the labels regardless the matter the order of painting them. Is there any suggestion?
You can also override paintComponent() or paintChildren() methods of the JPanel.
In the paintChildren() call your lines drawing and then super to draw JLabels.
anothe way should be
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class AddVertexDemo {
public AddVertexDemo() {
}
private static void createAndShowUI() {
JFrame frame = new JFrame("AddVertexDemo");
frame.getContentPane().add(new Gui().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
class DrawingPanel extends JPanel {
private static final int RADIUS = 6;
private static final long serialVersionUID = 1L;
private List<Shape> vertexList = new ArrayList<Shape>();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (vertexList.size() > 1) {
Shape s0 = vertexList.get(0);
Shape s1 = null;
for (int i = 0; i < vertexList.size(); i++) {
s1 = vertexList.get(i);
drawConnectingLine(g, s0, s1);
s0 = s1;
}
s1 = vertexList.get(0);
//drawConnectingLine(g2, s0, s1);
}
for (Shape shape : vertexList) {
g2.setColor(Color.blue);
g2.fill(shape);
g2.setColor(Color.blue.darker().darker());
g2.draw(shape);
}
}
private void drawConnectingLine(Graphics g, Shape s0, Shape s1) {
Rectangle r0 = s0.getBounds();
Rectangle r1 = s1.getBounds();
int x0 = r0.x + r0.width / 2;
int y0 = r0.y + r0.height / 2;
int x1 = r1.x + r1.width / 2;
int y1 = r1.y + r1.height / 2;
g.drawLine(x0, y0, x1, y1);
}
public void addVertex(Point p) {
int x = p.x - RADIUS;
int y = p.y - RADIUS;
int w = 2 * RADIUS;
int h = w;
vertexList.add(new Ellipse2D.Double(x, y, w, h));
repaint();
}
public void removeVertex(Point p) {
if (vertexList.size() > 0) {
for (int i = vertexList.size() - 1; i >= 0; i--) {
if (vertexList.get(i).contains(p)) {
vertexList.remove(i);
repaint();
return;
}
}
}
}
}
class Gui {
private static final Dimension DRAWING_PANEL_SIZE = new Dimension(600, 500);
private JPanel mainPanel = new JPanel(new BorderLayout());
private DrawingPanel drawingPanel = new DrawingPanel();
private JToggleButton addVertexBtn = new JToggleButton("Add Vertex");
private JToggleButton removeVertexBtn = new JToggleButton("Remove Vertex");
Gui() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(addVertexBtn);
buttonPanel.add(removeVertexBtn);
DrawPanelMouseListener mouseListener = new DrawPanelMouseListener();
mouseListener.setDrawingPanel(drawingPanel);
mouseListener.setGui(this);
drawingPanel.addMouseListener(mouseListener);
drawingPanel.setPreferredSize(DRAWING_PANEL_SIZE);
drawingPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(drawingPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
public JPanel getMainPanel() {
return mainPanel;
}
public boolean isAddingVertex() {
return addVertexBtn.isSelected();
}
public boolean isRemovingVertex() {
return removeVertexBtn.isSelected();
}
public void setAddingVertex(boolean addingVertex) {
addVertexBtn.setSelected(addingVertex);
}
public void setRemovingVertex(boolean removingVertex) {
removeVertexBtn.setSelected(removingVertex);
}
}
class DrawPanelMouseListener extends MouseAdapter {
private DrawingPanel drawingPanel;
private Gui gui;
public DrawPanelMouseListener() {
}
public void setGui(Gui gui) {
this.gui = gui;
}
public void setDrawingPanel(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
}
#Override
public void mousePressed(MouseEvent me) {
if (gui.isAddingVertex() && gui.isRemovingVertex()) {
gui.setAddingVertex(false);
gui.setRemovingVertex(false);
return;
}
if (gui.isAddingVertex()) {
drawingPanel.addVertex(me.getPoint());
gui.setAddingVertex(false);
}
if (gui.isRemovingVertex()) {
drawingPanel.removeVertex(me.getPoint());
gui.setRemovingVertex(false);
}
}
}
I'm not sure that this is the right way to do this but you can try this:
Create 2 panels. One for drawing lines and another for drawing buildings(labels).
Add both panels in LayeredPane of JFrame. Add panel with line in lower layer then panel with labels.
You can use LayeredPanes in other ways also to solve your problem. Learn more here: How to use Layered Panes in java
This is an excerise i have to complete for a uni course, its not a marked assignment and i could do with a bit of help. I can get the ball to appear on the screen and bounce of the sides, it doesnt matter at the moment if it falls through the bottom of the screen and i can get the paddle to appear on the screen at different times but i cant get them both to appear at the same time. Help please
Here are my classes
MainClass
package movingball;
public class Main
{
public static void main (String []args)
{
MovingBall world = new MovingBall("Moving Ball");
world.setVisible(true);
world.move();
}
}
BallClass
package movingball;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
public class Ball
{
private final int RADIUS = 10;
private Point pos;
private Color ballColour;
private int yChange = 2;
private int xChange = 1;
private int height, width;
private int change;
public Ball (int frameWidth, int frameHeight)
{
change = 3;
ballColour = Color.RED;
width = frameWidth;
height = frameHeight;
pos = new Point();
pos.x = (int)(Math.random() * (width - RADIUS)) + RADIUS;
pos.y = (int)(Math.random() * (height/2 - RADIUS)) + RADIUS;
}
//There are lots of ways you can updateBallState
//Note that the menu bar occupies some of the visible space
public void move()
{
if(pos.y < RADIUS)
{
yChange = - yChange;
}
if(pos.x < RADIUS)
{
xChange = -xChange;
}
if(pos.x > width - RADIUS)
{
xChange = -xChange;
}
if(pos.y < height - RADIUS)
{
pos.translate(xChange, yChange);
}
if(pos.x < width - RADIUS)
{
pos.translate(xChange, yChange);
}
}
public void updateBallState()
{
if (pos.y + change < height - 3*RADIUS)
{
pos.translate(0, change);
// change++; //accelerate
}
}
//This method can be called with a provided graphics context
//to draw the ball in its current state
public void draw(Graphics g)
{
g.setColor(ballColour);
g.fillOval(pos.x - RADIUS, pos.y - RADIUS, 2*RADIUS, 2*RADIUS);
}
public void bounce()
{
yChange = -yChange;
pos.translate(xChange, yChange);
}
public Point getPosition()
{
return pos;
}
}
BallGame
package movingball;
import java.awt.Graphics;
import java.awt.event.*;
public class BallGame extends MovingBall
{
private Paddle myPaddle = new Paddle(FRAME_WIDTH, FRAME_HEIGHT);
public BallGame(String title)
{
super(title);
addKeyListener(new KeyList());
}
public void paint(Graphics g)
{
super.paint(g);
myPaddle.paint(g);
if(isContact())
{
myBall.bounce();
}
else
{
myPaddle.paint(g);
}
}
public boolean isContact()
{
if (myPaddle.area().contains(myBall.getPosition()))
{
return true;
}
else
{
return false;
}
}
public class KeyList extends KeyAdapter
{
public void keyPressed(KeyEvent k)
{
if(k.getKeyCode() == KeyEvent.VK_LEFT)
{
myPaddle.moveLeft();
}
if(k.getKeyCode() == KeyEvent.VK_RIGHT)
{
myPaddle.moveRight();
}
}
}
}
MovingBall class
package movingball;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingBall extends JFrame
{
protected final int FRAME_WIDTH = 240;
protected final int FRAME_HEIGHT = 320;
protected Ball myBall = new Ball(FRAME_WIDTH, FRAME_HEIGHT);
public MovingBall (String title)
{
super(title);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
super.paint(g);
myBall.draw(g);
}
public void move()
{
while(true)
{
myBall.move();
repaint();
try
{
Thread.sleep(50);
}
catch(InterruptedException e)
{
System.exit(0);
}
}
}
}
Paddle class
package movingball;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Paddle
{
private Color paddleColour = Color.GREEN;
private int x,y;
private int paddleWidth = 20;
private int paddleHeight = 10;
private int move = 5;
/** Creates a new instance of Paddle */
public Paddle(int frameWidth, int frameHeight)
{
x =(int)(Math.random()*(frameWidth - paddleWidth));
y = frameHeight - paddleHeight;
}
public void moveRight()
{
x = x + move;
}
public void moveLeft()
{
x = x - move;
}
public Rectangle area()
{
return new Rectangle(x,y, paddleWidth, paddleHeight);
}
public void paint(Graphics g)
{
g.setColor(paddleColour);
g.fillRect(x,y,paddleWidth, paddleHeight);
}
}
Here are a couple of pointers to get you started. I have a lot of things to suggest but I'll just say this to get you further than you are now. You want your JFrame to be double-buffered. That's the first step. To do this, create a new buffer strategy for your JFrame after making it visible:
world.setVisible(true);
world.createBufferStrategy(2);
As for why your Paddle isn't painting? You're going to kick yourself. Look at this line:
MovingBall world = new MovingBall("Moving Ball");
You're not actually creating a BallGame, which is where the logic for painting the paddle is contained! (BallGame.paint()) Try:
BallGame world = new BallGame("Moving Ball");