Java - How to Create a MultiThreaded Game using SwingWorker - java

I want to Create a [1 Player vs PC] Game with Threads.
we have 10*10 two Colors Shapes in our board like this :
when the Player clicks on BLUE Circles , Their color turns into Gray.
at the other side PC should turn all RED Rectangles into Gray.
the WINNER is who Clears all his/her own Shapes Earlier.
Code for The Player works fine but,
My Problem is in Implementing The PC side of the Game, as i read in this article i should use SwingWorker to Implement Threading in GUI.
it's my first time using SwingWorkers and i don't know how it should be to works properly.
Here is my Codes :
The Main Class
public class BubblePopGame {
public static final Color DEFAULT_COLOR1 = Color.BLUE;
public static final Color DEFAULT_COLOR2 = Color.RED;
public BubblePopGame() {
List<ShapeItem> shapes = new ArrayList<ShapeItem>();
int Total = 10;
for (int i = 1; i <= Total; i++) {
for (int j = 1; j <= Total; j++) {
if ((i + j) % 2 == 0) {
shapes.add(new ShapeItem(new Ellipse2D.Double(i * 25, j * 25, 20, 20),
DEFAULT_COLOR1));
} else {
shapes.add(new ShapeItem(new Rectangle2D.Double(i * 25, j * 25, 20, 20),
DEFAULT_COLOR2));
}
}
}
JFrame frame = new JFrame("Bubble Pop Quest!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ShapesPanel panel = new ShapesPanel(shapes);
frame.add(panel);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BubblePopGame();
}
});
}
}
Shape Item Class
public class ShapeItem {
private Shape shape;
private Color color;
public ShapeItem(Shape shape, Color color) {
super();
this.shape = shape;
this.color = color;
}
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape = shape;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
ShapesPanel Class
public class ShapesPanel extends JPanel {
private List<ShapeItem> shapes;
private Random rand = new Random();
private SwingWorker<Boolean, Integer> worker;
public ShapesPanel(List<ShapeItem> shapesList) {
this.shapes = shapesList;
worker = new SwingWorker<Boolean, Integer>() {
#Override
protected Boolean doInBackground() throws Exception {
while (true) {
Thread.sleep(200);
int dim = rand.nextInt(300);
publish(dim);
return true;
}
}
#Override
protected void done() {
Boolean Status;
try {
Status = get();
System.out.println(Status);
super.done(); //To change body of generated methods, choose Tools | Templates.
} catch (InterruptedException ex) {
Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(ShapesPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void process(List<Integer> chunks) {
int mostRecentValue = chunks.get(chunks.size()-1);
System.out.println(mostRecentValue);
Color color2 = Color.LIGHT_GRAY;
ShapeItem tmpShape = shapes.get(mostRecentValue);
if(tmpShape.getColor()==Color.RED){
tmpShape.setColor(color2);
}
repaint();
}
};
worker.execute ();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Color color1 = Color.LIGHT_GRAY;
for (ShapeItem item : shapes) {
if (item.getColor() == Color.BLUE) {
if (item.getShape().contains(e.getPoint())) {
item.setColor(color1);
}
}
}
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
for (ShapeItem item : shapes) {
g2.setColor(item.getColor());
g2.fill(item.getShape());
}
g2.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private Color getRandomColor() {
return new Color(rand.nextFloat(), rand.nextFloat(),
rand.nextFloat());
}
}

If I understood your code correctly, you are making a game where the human player has to click as fast as possible on all of his shapes while the PC is randomly clicking on shapes as well. The first one to clear all of his shapes win.
If that is correct, you probably want to adjust your SwingWorker to
loop until the game is finished. Currently your loop exit the first time the end of the loop is reached due to the return statement
Since you are not doing anything with the boolean return value of the SwingWorker, you might as well let it return void
No need to call get in the done method. The moment that method is called, the SwingWorker has finished. You only seem interested in the intermediate results
In the process method, you might want to loop over all values. Note that the process method is not called each time you publish something. The values you publish are grouped and passed in bulk to the process method when the EDT (Event Dispatch Thread) is available

Related

Whole Colors change when I change Colors in my Java Paint Program

I created a program in Java using JPanel and Graphics. This is simple Paint Panel program in which things draw when we drag mouse and when we want to make line with different color simply just press the button in a panel but the problem is that when I press a button in panel and drag the mouse whole components present in a panel turns into that color (Button' Color).
Code:
public class PaintAssign extends JPanel {
private ArrayList<Point> points= new ArrayList<>();
private ArrayList<Point> points2= new ArrayList<>();
public final JButton[] panelButton=new JButton[5];
public String[] colors={"RED","BLUE","GREEN","YELLOW","CYAN"};
int x=0;
public PaintAssign()
{ addMouseMotionListener(
new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e)
{
points.add(e.getPoint());
repaint();
}
});
addMouseListener(
new MouseAdapter(){
});
for (int i = 0; i < 5; i++) {
Rectangle r = new Rectangle(22, 22);
panelButton[i] = new JButton();
panelButton[i].setText(colors[i]);
panelButton[i].setOpaque(true);
panelButton[i].setBounds(r);
this.add(panelButton[i]);
this.setVisible(true);
}
mouseAction handle=new mouseAction();
panelButton[0].addActionListener(handle);
panelButton[1].addActionListener(handle);
panelButton[2].addActionListener(handle);
panelButton[3].addActionListener(handle);
panelButton[4].addActionListener(handle);
}
private class mouseAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==panelButton[0])
{
x=1;
}
else if(e.getSource()==panelButton[1])
{
x=2;
}
else if(e.getSource()==panelButton[2])
{
x=3;
}
else if(e.getSource()==panelButton[3])
{
x=4;
}
else if(e.getSource()==panelButton[4])
{
x=5;
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(x==0)
{
g.setColor(Color.BLACK);
}
else if(x==1)
{
g.setColor(Color.RED);
}
else if(x==2)
{
g.setColor(Color.BLUE);
}
else if(x==3)
{
g.setColor(Color.GREEN);
}
else if(x==4)
{
g.setColor(Color.YELLOW);
}else if(x==5)
{
g.setColor(Color.CYAN);
}
for(Point i:points)
{
g.fillOval(i.x,i.y,15,15);
}
}
The paintComponent method is called everytime the panel redraw itself and that happens quite often. Then when you set the color, all the points will be redrawn with the new color.
To avoid this behavior you must save not only the coordinates of your points but also their color.
public class PaintAssign extends JPanel {
private ArrayList<Point> points= new ArrayList<>();
private ArrayList<Color> colors = new ArrayList<>();
//....
public PaintAssign(){
addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e) {
points.add(e.getPoint());
if(x==0) {
colors.add(Color.BLACK);
} else if(x==1) {
colors.add(Color.RED);
} else if(x==2) {
colors.add(Color.BLUE);
} else if(x==3) {
colors.add(Color.GREEN);
} else if(x==4) {
colors.add(Color.YELLOW);
}else if(x==5) {
colors.add(Color.CYAN);
}
repaint();
}
});
// ...
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < points.size(); i++) {
g.setColor(colors.get(i));
g.fillOval(points.get(i).x, points.get(i).y, 15, 15);
}
}
}
Consider creating a new class Point containing the coordinates and the color of the point.
You didn' provide the repaint() method, but my guess is, since you record all your points to the same list, all points are redrawn in the same color. What you need are separate lists for every component you draw, managed in a way that you can access that list when the component is selected.
I'm not sure if I understood your problem correctly though, maybe you could provide more details.

Adding a JButton to a class extended by JPanel is not displaying a button

When I use normal JPanel initialized inside main instead of extended class. The button is added to a panel without problem and after launch is displayed in a center of a frame (default layout).
I would like to be able to add buttons inside an extended class. This problem occurs in Screen class aswell, where I need a Play Again button or Next Level button. The Screen is class extended by a JPanel too and JButtons are initialized inside the constructor aswell.
I'm not sure if the wrong part is in way of adding the components or in writing a code for a JPanel.
Here is the code:
Main:
public static void main(String[] args) {
// window - class JFrame
theFrame = new JFrame("Brick Breaker");
// game panel initialization
GamePanel gamePanel = new GamePanel(1);
theFrame.getContentPane().add(gamePanel);
// base settings
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setLocationRelativeTo(null);
theFrame.setResizable(false);
theFrame.setSize(WIDTH, HEIGHT);
theFrame.setVisible(true);
}
GamePanel Class:
public class GamePanel extends JPanel {
// Fields
boolean running;
boolean clicked = false;
private int rows = 8, colms = 11, N = rows * colms, level; // numbers of rows and columns
private int colmsC, rowsC;
private BufferedImage image;
private Graphics2D g;
private MyMouseMotionListener theMouseListener;
private MouseListener mouseListener;
private int counter = 0;
// entities
Ball theBall;
Paddle thePaddle;
Bricle[] theBricks;
Screen finalScreen;
public GamePanel(int level) {
// buttons
JButton pause = new JButton(" P ");
add(pause);
this.level = level;
init(level);
}
public void init(int level) {
// level logic
this.rowsC = level + rows;
this.colmsC = level + colms;
int count = rowsC * colmsC;
thePaddle = new Paddle();
theBall = new Ball();
theBall.setY(thePaddle.YPOS - thePaddle.getHeight() + 2);
theBall.setX(thePaddle.getX() + thePaddle.getWidth() / 2 - 5);
theBricks = new Bricle[count];
theMouseListener = new MyMouseMotionListener();
addMouseMotionListener(theMouseListener);
mouseListener = new MyMouseListener();
addMouseListener(mouseListener);
// make a canvas
image = new BufferedImage(BBMain.WIDTH, BBMain.HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// specific Bricks initialized
int k = 0;
for (int row = 0; row < rowsC; row++) {
for (int col = 0; col < colmsC; col++) {
theBricks[k] = new Bricle(row, col);
k++;
}
}
running = true;
}
public void playGame() {
while (running) {
//update
if (clicked) {
update();
}
// draw
draw();
// display
repaint();
// sleep
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// update loop ( like playGame )
public void update() {
// ball moving
checkCollisions();
theBall.update();
}
public void draw() {
// background
g.setColor(Color.WHITE);
g.fillRect(0,0, BBMain.WIDTH, BBMain.HEIGHT-20);
// the bricks
int k = 0;
for (int row = 0; row < rowsC; row++) {
for (int col = 0; col < colmsC; col++) {
theBricks[k].draw(g, row, col);
k++;
}
}
// the ball and the paddle
theBall.draw(g);
thePaddle.draw(g);
// counter
String countString = new Integer(this.counter).toString();
g.drawString(countString, 20, 20);
// WIN / LOOSE SCREEN
if (this.counter == this.N * 20) {
win();
}
if (theBall.getRect().getY() + theBall.getRect().getHeight() >= BBMain.HEIGHT) {
loose();
}
}
public void paintComponent(Graphics g) {
// retype
Graphics2D g2 = (Graphics2D) g;
// draw image
g2.drawImage(image, 0, 0, BBMain.WIDTH, BBMain.HEIGHT, null);
// dispose
g2.dispose();
}
public void pause() {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"GAME PAUSED");
}
public void win() {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"YOU WIN");
}
public void loose () {
this.running = false;
finalScreen = new Screen(this.level, counter);
finalScreen.draw(g,"YOU LOOSE");
}
public void addScore() {
this.counter += 20;
theBall.setDY(theBall.getDY() - 0.001);
}
// Mouse Listeners
private class MyMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
clicked = true;
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
private class MyMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
if (clicked)
thePaddle.mouseMoved(e.getX());
}
}
}

On scrolling dynamically generated graphics using JPanel in JScrollPane, the scrolled portion graphics disappears

outputImage
Everything works fine but when i scroll while the graphics is being generated, the scrolled portion graphics disappears
MainApp.java
public abstract class MainApp implements ActionListener{
//Just Listing the method that triggers Canvas(extends JPanel and starts painting)
public void startGeneration(){
String rule = (String) cb.getSelectedItem();
Jexception.setVisible(false);
Jexception1.setVisible(false);
if(genNum > 0){
cgs = new CAGenerationSet(genNum, rule);
cAGenList = new ArrayList<>();
cAGenList = cgs.run(cgs);
if(sp!= null) {
frame.remove(sp);
if(canvas!=null) sp.remove(canvas);
}
//initializing canvas and adding it to the JScrollPane
canvas = new Canvas(cAGenList);
sp = new JScrollPane();
splitPane.setDividerLocation(80);
splitPane.setRightComponent(sp);
sp.setVisible(true);
EventQueue.invokeLater(new Runnable() {
public void run() {
sp.setViewportView(canvas);
sp.revalidate();
}
});
}
else {
Jexception.setVisible(false);
Jexception1.setVisible(true);
}
}
}
Canvas extends JPanel. Here I am overriding the paintComponent() and calling the draw method that triggers the SwingWorker to draw the graphics.
Canvas.java
public class Canvas extends JPanel {
ArrayList<CAGeneration> cAGenList;
private int y,x;
private Thread t;
public static SwingWorker<Void, Void> worker;
private int count = 0;
private boolean check = false;
public CACanvas(ArrayList<CAGeneration> cAGenList) {
this.cAGenList = cAGenList;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
revalidate();
if(!check){
drawCA(g, this.cAGenList);
}
}
private void drawCA(Graphics g, ArrayList<CAGeneration> cAGenList ) {
worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
Graphics2D g2d = (Graphics2D) g;
check = true;
y= 10;
count = 0;
synchronized (cAGenList) {
for(CAGeneration cg: cAGenList){
count++;
y = y+10;
x = 0;
if(!isCancelled()){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
for(int i=0; i<cg.getcACell().length; i++){
x = x+10;
if (cg.getcACell()[i] == 0) {
paintRect(g2d, x, y, 9, Color.WHITE);
}
if (cg.getcACell()[i] == 1) {
paintRect(g2d, x, y, 9, Color.GRAY);
}
if (cg.getcACell()[i] == 2) {
paintRect(g2d, x, y, 9, Color.BLACK);
}
}
}
}
}
check = false;
return null;
}
};
ExecutorService threadPool = Executors.newSingleThreadExecutor();
threadPool.submit(worker);
}
private void paintRect(Graphics2D g2D, int x, int y, int size, Color color){
if(g2D!=null) g2D = (Graphics2D) getGraphics();
g2D.setColor(color);
g2D.fillRect(x, y, size, size);
}
}

Simon Says won't show sequence

Below is a Simon Says program I am working on. Right now it only displays a gray frame. I added in a keyListener to see if i could make the arcs light up.I wanted to display a flash animation sequence. Why isn't this working?
public class SimonShape extends JFrame implements KeyListener, ActionListener {
private JFrame f;
private JPanel p;
public static void main(String[] args) {
new SimonShape();
}
public SimonShape() {
f = new JFrame("Simon Says");
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawStuff draw = new DrawStuff();
p = new JPanel();
p.setBackground(Color.GRAY);
p.setLayout(new BorderLayout());
draw.playSequence();
p.add(draw, BorderLayout.CENTER);
// initiates the sequence
f.add(p);
f.addKeyListener(this);
f.setLocationRelativeTo(null); // positions the frame in the middle of
// the screen
f.setVisible(true);
}
public class DrawStuff extends JComponent {
Color COLOR1;
Color COLOR2;
Color COLOR3;
Color COLOR4;
public void playSequence() {
ArrayList<Integer> Computer = new ArrayList<Integer>();
ArrayList<Integer> Player = new ArrayList<Integer>();
int compPick, compPick2, compPick3, compPick4;
Random gen = new Random();
compPick = gen.nextInt(4);
compPick2 = gen.nextInt(4);
compPick3 = gen.nextInt(4);
compPick4 = gen.nextInt(4);
Computer.add(compPick);
Computer.add(compPick4);
Computer.add(compPick2);
Computer.add(compPick3);
for (int i = 0; i < Computer.size(); i++) {
if (Computer.get(i) == 0) {
COLOR1 = Color.GREEN.brighter();
repaint();
} else if (Computer.get(i) == 1) {
COLOR2 = Color.BLUE.darker();
repaint();
} else if (Computer.get(i) == 2) {
COLOR3 = Color.RED.darker();
repaint();
} else if (Computer.get(i) == 3) {
COLOR4 = Color.YELLOW.brighter();
repaint();
}
}
}
}
public int flash = 0;
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
Graphics2D g4 = (Graphics2D) g;
Graphics2D g5 = (Graphics2D) g;
// assume d == 145 && e == 90
if (flash == 1) {
g2.setPaint(Color.GREEN);
} else {
g2.setPaint(Color.GREEN.darker());
}
g2.fill(new Arc2D.Double(150, 150, 200, 200, 145, 90, Arc2D.PIE));
if (flash == 2) {
g3.setPaint(Color.BLUE);
} else {
g3.setPaint(Color.BLUE.darker());
}
g3.fill(new Arc2D.Double(150, 150, 200, 200, 235, 90, Arc2D.PIE));
if (flash == 3) {
g4.setPaint(Color.RED);
} else {
g4.setPaint(Color.RED.darker());
}
g4.fill(new Arc2D.Double(150, 150, 200, 200, 325, 90, Arc2D.PIE));
if (flash == 4) {
g5.setPaint(Color.YELLOW);
} else {
g4.setPaint(Color.YELLOW.darker());
}
g5.fill(new Arc2D.Double(150, 150, 200, 200, 55, 90, Arc2D.PIE));
}
public void keyPressed(KeyEvent e) {
int event = e.getKeyCode();
if (event == KeyEvent.VK_RIGHT) {
flash = 1;
}
if (event == KeyEvent.VK_DOWN) {
flash = 2;
}
if (event == KeyEvent.VK_LEFT) {
flash = 3;
}
if (event == KeyEvent.VK_UP) {
flash = 4;
}
}
#Override
public void keyTyped(KeyEvent e) {//not used
}
#Override
public void keyReleased(KeyEvent e) {//not used
}
#Override
public void actionPerformed(ActionEvent e) {//not used
}
}
When creating any Swing GUI, you should always use the model / view / controller pattern. This pattern allows you to separate your concerns and focus on one part of the GUI at a time.
Divide and conquer.
Here's the GUI I created.
The first thing I did was create a model for the game. The GameModel class is a plain Java object that holds the computer sequence and the player sequence.
public class GameModel {
private List<Integer> computerSequence;
private List<Integer> playerSequence;
private Random random;
public GameModel() {
this.computerSequence = new ArrayList<Integer>();
this.playerSequence = new ArrayList<Integer>();
this.random = new Random();
}
public void addToComputerSequence() {
computerSequence.add(Integer.valueOf(random.nextInt(4)));
}
public void clearComputerSequence() {
computerSequence.clear();
}
public List<Integer> getComputerSequence() {
return computerSequence;
}
public void clearPlayerSequence() {
playerSequence.clear();
}
public void addToPlayerSequence(int number) {
playerSequence.add(Integer.valueOf(number));
}
public boolean doSequencesMatch() {
if (computerSequence.size() == playerSequence.size()) {
for (int i = 0; i < computerSequence.size(); i++) {
int computer = computerSequence.get(i);
int player = playerSequence.get(i);
if (computer != player) {
return false;
}
}
return true;
}
return false;
}
}
The model class allows us to add to the computer sequence, add to the player sequence, and determine if the computer and player sequence match.
Next, we need a model class to hold the 4 slices of the circle. The ArcModel class is another plain Java object that holds a slice.
public class ArcModel {
private final int closureType;
private final double startingAngle;
private final double extent;
private Color color;
private final Color originalColor;
private final Rectangle rectangle;
public ArcModel(Color color, Rectangle rectangle, double startingAngle,
double extent, int closureType) {
this.color = color;
this.originalColor = color;
this.rectangle = rectangle;
this.startingAngle = startingAngle;
this.extent = extent;
this.closureType = closureType;
}
public int getClosureType() {
return closureType;
}
public double getStartingAngle() {
return startingAngle;
}
public double getExtent() {
return extent;
}
public Rectangle getRectangle() {
return rectangle;
}
public Color getColor() {
return color;
}
public void brighterColor() {
this.color = Color.WHITE;
}
public void darkerColor() {
this.color = originalColor;
}
}
In addition to the getters and setters, we have a method to brighten the color and a method to darken the color. I've set the bright color to white to make it more easily visible.
Now that we've created the model classes, let's look at the view classes. The first view class is the DrawingPanel class.
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 70146219705119575L;
private List<ArcModel> segments;
public DrawingPanel() {
this.segments = new ArrayList<ArcModel>();
int margin = 50;
int diameter = 300;
Rectangle r = new Rectangle(margin, margin, diameter, diameter);
segments.add(new ArcModel(Color.GREEN, r, 180, 90, Arc2D.PIE));
segments.add(new ArcModel(Color.BLUE, r, 270, 90, Arc2D.PIE));
segments.add(new ArcModel(Color.RED, r, 360, 90, Arc2D.PIE));
segments.add(new ArcModel(Color.YELLOW, r, 90, 90, Arc2D.PIE));
int width = diameter + margin + margin;
this.setPreferredSize(new Dimension(width, width));
}
public void brighterArcModelColor(int index) {
segments.get(index).brighterColor();
repaint();
}
public void darkerArcModelColor(int index) {
segments.get(index).darkerColor();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (ArcModel arcModel : segments) {
g2d.setPaint(arcModel.getColor());
Rectangle r = arcModel.getRectangle();
g2d.fill(new Arc2D.Double(r.getX(), r.getY(), r.getWidth(), r
.getHeight(), arcModel.getStartingAngle(), arcModel
.getExtent(), arcModel.getClosureType()));
}
}
}
Here, we create a List of ArcModel segments. We set the size of the drawing panel based on the margin and diameter of the circle we want to create with the segments.
We have two methods, one for brightening a color of a segment, and another for darkening a color of a segment.
We do the drawing in the paintComponent method. Since we created the ArcModel class, the actual drawing is straightforward. The paintComponent method does nothing but draw the pie slices of the circle.
Next, we look at the main SimonShape class. This class creates the game model and creates the GUI.
public class SimonShape implements Runnable {
private GameModel gameModel;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new SimonShape());
}
public SimonShape() {
this.gameModel = new GameModel();
}
#Override
public void run() {
frame = new JFrame("Simon Says");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingPanel drawingPanel = new DrawingPanel();
frame.add(drawingPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
GameRunnable runnable = new GameRunnable(drawingPanel, gameModel);
new Thread(runnable).start();
}
}
The last two lines of the run method create the animation.
The controller class is the GameRunnable class. I wrote enough code to have the computer pick 10 random segments, and display the sequence of the segments. I'm leaving the rest of the game code up to you. It will go in the GameRunnable class.
public class GameRunnable implements Runnable {
private volatile boolean running;
private DrawingPanel drawingPanel;
private GameModel gameModel;
public GameRunnable(DrawingPanel drawingPanel, GameModel gameModel) {
this.drawingPanel = drawingPanel;
this.gameModel = gameModel;
}
#Override
public void run() {
running = true;
while (running && gameModel.getComputerSequence().size() < 10) {
generateComputerSequence();
sleep(1800L);
}
}
private void generateComputerSequence() {
gameModel.addToComputerSequence();
for (Integer index : gameModel.getComputerSequence()) {
drawingPanel.brighterArcModelColor(index);
sleep(1000L);
drawingPanel.darkerArcModelColor(index);
sleep(200L);
}
}
private void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
}
}
public synchronized void setRunning(boolean running) {
this.running = running;
}
}
Remember, divide and conquer.

Adding JPanel after removing it from JFrame

I'm developing a Java Game. I'm stuck at a point,where I need to restart the whole game again after GameOver. Here is the skeleton of my program:
package projectflappy;
import java.awt.*;
public final class TheGame extends JFrame implements MouseListener{
JPanel jp;
//declaration of the varibles
int x_width = 500;
int y_height = 500;
int count = 5 ;
Ellipse2D Ball;
int x_ball;
int y_ball;
int cord_xup1,cord_xdown1;
int cord_xup2,cord_xdown2;
int cord_xup3,cord_xdown3;
int cord_xup4,cord_xdown4;
int cord_xup5,cord_xdown5;
Boolean flag = true;
RoundRectangle2D up1,down1,up2,down2,up3,down3,up4,down4;
Font font = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,40);
Font font1 = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,20);
Font font3 = new Font("Matura MT Script Capitals",Font.ROMAN_BASELINE,20);
float das[] = {10.0f};
BasicStroke color = new BasicStroke(10,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,20.0f,das,0.0f);
GradientPaint gp2 = new GradientPaint(20, 0,
Color.DARK_GRAY, 0, 10, Color.GRAY, true);
GradientPaint gp3 = new GradientPaint(30, 0,
Color.BLACK, 0, 20, Color.GREEN, true);
Toolkit kit = Toolkit.getDefaultToolkit();
//Getting the "background.jpg" image we have in the folder
Image background = kit.getImage("D:\\College\\Programs\\ProjectFLAPPY\\src\\projectflappy\\1.png");
JLabel a = new JLabel("Get Ready ! Click to Start.");
JLabel retry = new JLabel(new ImageIcon("D:\\College\\Programs\\ProjectFLAPPY\\src\\projectflappy\\unnamed.png"));
int score = 0;
//constructor
public TheGame() throws IOException
{
super("Simple Drawing");
setSize(x_width, y_height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
jp = new DrawingPanel();
add(jp);
addMouseListener(this);
}
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
update();
repaint();
}
};
Timer t = new Timer(50,action);
public void init()
{
x_ball = 30;
y_ball = 200;
cord_xup1 = 175; cord_xdown1 = 175;
cord_xup2 = 320; cord_xdown2 = 320;
cord_xup3 = 460; cord_xdown3 = 460;
cord_xup4 = 585; cord_xdown4 = 585;
cord_xup5 = 700; cord_xdown5 = 700;
retry.setVisible(false);
retry.setBounds(175,260,46,46);
a.setForeground(Color.YELLOW);
a.setFont(font1);
a.setVisible(true);
a.setBounds(105,200,300,100);
}
#Override
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
a.setVisible(false);
if( flag == false)
{
t.stop();
}
else
{
t.start();
}
y_ball = y_ball - 40;
count--;
}
#Override
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
// for drawing on the panel
class DrawingPanel extends JPanel{
private static final long serialVersionUID = 1L;
public DrawingPanel() {
setPreferredSize(new Dimension(300, 300));
setLayout(null);
init();
add(a);
add(retry);
// addMouseListener(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D d = (Graphics2D)g;
d.drawImage(background, -270,-30, this);
Ball = new Ellipse2D.Double(x_ball,y_ball,30,30);
d.setColor(Color.green);
d.setFont(font3);
up1 = new RoundRectangle2D.Double(cord_xup1,-5,30,175,20,20);
down1 = new RoundRectangle2D.Double(cord_xdown1,310,30,155,20,20);
up2 = new RoundRectangle2D.Double(cord_xup2,-5,30,200,20,20);
down2 = new RoundRectangle2D.Double(cord_xdown2,310,30,175,20,20);
up3 = new RoundRectangle2D.Double(cord_xup3,-5,30,230,20,20);
down3 = new RoundRectangle2D.Double(cord_xdown3,350,30,135,20,20);
up4 = new RoundRectangle2D.Double(cord_xup4,-5,30,115,20,20);
down4 = new RoundRectangle2D.Double(cord_xdown4,240,30,115,20,20);
d.setPaint(gp2);
d.setStroke(color);
d.fill(up1);
d.fill(down1);
d.fill(up2);
d.fill(down2);
d.fill(up3);
d.fill(down3);
d.fill(up4);
d.fill(down4);
d.setPaint(gp3);
d.setStroke(color);
d.fill(Ball);
d.setColor(Color.BLACK);
d.setFont(font1);
d.drawString(""+score ,200,50);
if( Ball.intersects(up1.getBounds()) || Ball.intersects(down1.getBounds()) || Ball.intersects(up2.getBounds()) || Ball.intersects(down2.getBounds()) || Ball.intersects(up3.getBounds()) || Ball.intersects(down3.getBounds()) || Ball.intersects(up4.getBounds()) || Ball.intersects(down4.getBounds()))
{
t.stop();
flag = false;
d.setColor(Color.red);
d.setFont(font);
d.drawString("Game Over : "+score ,100,250);
retry.setVisible(true);
}
retry.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent event) {
init(); //reset properties
}
//...
#Override
public void mousePressed(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseReleased(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseEntered(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void mouseExited(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}
public void update()
{
cord_xdown1 -= 5;
cord_xup1 -= 5;
cord_xdown2 -= 5;
cord_xup2 -= 5;
cord_xdown3 -= 5;
cord_xup3 -= 5;
cord_xdown4 -= 5;
cord_xup4 -= 5;
cord_xdown5 -= 5;
cord_xup5 -= 5;
if( cord_xup1 <=-20)
{
cord_xup1 = 500;
cord_xdown1 = 500;
}
if( cord_xup2 <=-20)
{
cord_xup2 = 500;
cord_xdown2 = 500;
}
if( cord_xup3 <=-20)
{
cord_xup3 = 500;
cord_xdown3 = 500;
}
if( cord_xup4 <=-20)
{
cord_xup4 = 500;
cord_xdown4 = 500;
}
if( cord_xup5 <=-20)
{
cord_xup5 = 500;
cord_xdown5 = 500;
}
if(count >= 0)
{
y_ball = y_ball - 7;
count--;
if( y_ball == y_height)
{
t.stop();
}
}
else
{
y_ball = y_ball + 7;
if( y_ball == y_height-70)
{
t.stop();
}
}
if(cord_xdown1 == x_ball || cord_xdown2 == x_ball || cord_xdown3 == x_ball || cord_xdown4 == x_ball)
{
score = score+1;
}
}
public static void main(String[] args) throws IOException {
new TheGame();
}
}
here retry is a JLabel in which I'm using a MouseListener to do things.
When I run,the JPanel gets completely removed from the JFrame but the new JPanel really doesn't seem to work. But only one component i.e, a.setVisble(true) works.
This is the frame when the Players gets out.
This Frames when the Player clicks on the retry button.
The reason your new panel is not showing is due to the component hierarchy being invalid. You attempt to revalidate, but you did it before adding the panel. You need to do it AFTER you add a component to an already visible container. Check out invalidate():
This method is called automatically when any layout-related information changes (e.g. setting the bounds of the component, or adding the component to a container).
So you must validate after adding the component, not before. revalidate() invalidates then revalidates the component hierarchy.
The proper way to handle this would be to revert your game back to it's original form; just change everything back to how it was. No need to create a new panel.
You could create a method, init(), which sets your game to how it should be:
//Contains the properties that will change during gameplay
void init() {
retry.setVisible(false);
a.setForeground(Color.YELLOW);
//...
}
Which you can then call when you create the board (in the constructor) and when you press retry (in the listener):
public DrawingPanel() {
setPreferredSize(new Dimension(300, 300));
setPreferredSize(new Dimension(300, 300));
setLayout(null);
init(); //sets properties
a.setFont(font1);
a.setVisible(true);
a.setBounds(105,200,300,100);
add(a);
retry.setBounds(175,260,46,46);
retry.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent event) {
init(); //reset properties
}
//...
});
add(retry);
}
You shouldn't add a listener to a component in your update() method, since update() will be called multiple times. Add it in your constructor.
If retry is a JButton, you should use an ActionListener. I wasn't sure, so I kept it as a mouse listener.
You should avoid using null layout (absolute positioning). Layout Managers position and size components using specific calculations to ensure your resulting GUI looks the same on all platforms. There are a few uses where absolute positioning is a viable option, as mentioned in the tutorials, but it's always best to prefer a Layout Manager. IMO, null layout is bad practice, and the only reason one would use it is if they didn't understand layout managers, which is a problem in itself.
To learn more about layout managers, check out the Visual Guide to Layout Managers trail. Not only does the JDK come bundled with layouts, but you can also create your own or use a third party layout, like MigLayout
EDIT:
Post Swing code to the Event Dispatch Thread. Swing event handlers (painting, listeners) are executed on the Event Dispatch Thread. To ensure the Swing code you write is in sync with the EDT, post any Swing code that isn't already being executed on the EDT to the EDT by using invokeLater or invokeAndWait.
Do not size your frame directly. Allow your frame to size based off the contents inside of it. Your DrawingPanel (the game canvas) should determine the size of the frame.
TheGame should not extend JFrame, since it's not a frame itself, rather than something contained within a frame. Having it extend JPanel would be a little easier on you (you won't be forced to create a new class to override the paint method). Although, TheGame shouldn't extend anything, it should HAVE these things (has-a relationship, not is-a). But since you're still a beginner, I don't wanna overwhelm you with a completely new design, so I considered TheGame to be the actual game canvas (where things will be draw; TheGame will extend JPanel), so you'll no longer need DrawingBoard.
As mentioned before, you should NOT add listeners (or do any task that is only needed once) in the paint method. Keep in mind that the paint method is for painting, not initializing or setting values. You should attempt to keep logic out of that method if possible.
Stay consistent. You use a JLabel for "Click to start!", yet you use drawString for "Game Over". Pick one or the other. This choice is really up to you. For this example, I chose to use drawString, since it's consistent with the rest of your rendering methods (how you paint the background, ball and obstacles)
DO NOT CREATE NEW OBJECTS IN YOUR PAINT METHOD. You're creating a ton of new objects every 50 milliseconds. This is NOT needed, and will harm performance critically. When you use the new keyword, you create a new object. Instead of creating a new object to change it (or revert it back), just change it's state.
Take advantage of Object Orientation. It'll help keep you organized, and allow you to easily manage and scale up your application. Don't shove a bunch of variables into one class to represent a ton of different things (cordx_up1, cordx_up2... it's definitely not scalable).
Look into some of the Adapter classes like MouseAdapter and KeyAdapter; they allow you to handle events without needing to declare methods you might not use.
Use access modifiers. If you aren't familiar with them, get to know them. It makes managing code a lot easier if you know where it can be used ahead of time.
Your paths point to a specific drive with a specific name. This should not be the case, since not everyone uses that drive and/or folder name. Package your images with your project, then refer to them locally.
With that said, you have a lot of studying to do.
What I did was create a Ball class and an Obstacle class, to get a little more organized. ball_x and ball_y are now inside the Ball class, as well as the gradient for it. The objects we create from this class will now have these properties (states). I create 1 ball object for your game.
Instead of creating new variables for each pole (cordx_up1), the Obstacle class has 2 RoundRectangle2D, top and bottom, which are the poles your ball is supposed to avoid. Each obstacle also has a gradient, which is used for both top and bottom. Now I can create 1 obstacle object for 2 aligned poles. You can change the starting x position of the obstacle (although I don't recommend allowing this; x should be set dynamically based on other obstacles' positions), as well as the size for top and bottom. I create 5 obstacle objects.
To keep your game labels organized (by color, message, location, font) while using drawString instead of JLabel, I created a GameLabel class.
I separated the main method into it's own class, named Launcher, which creates a JFrame and adds your game to it; all on the Event Dispatch Thread:
public class Launcher {
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new TheGame());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
Your Game class now extends JPanel, so you can override the paint method to render the game. I created 1 Ball and a LinkedList for your obstacles. I chose a LinkedList since inserting/removing from front/end is guaranteed constant time, meaning it'll take the same amount of time to remove/insert no matter how many obstacles are in the list. When the ball passes an obstacle, I remove it from the front of the list and add it to the back. The first obstacle in the list is always the next obstacle.
I saw how some Strings were being re-used, so I created final variables for them, which you can easily change. There's also the currentlyPlaying and isAlive booleans. currentlyPlaying is set to true when the user first clicks (to start the game), and set to false once the user has clicked to restart the game (after he lost).
readyToJump is the flag I use to forward mouse events to your update() method (technically your updatePlayerPostion() method, but it's still "centeralized" within your update() method). It's best to keep all your logic in one place. readyToJump = true would have been the only statement in your listener's method if you weren't relying on calling timer.start() in it. Since update() can't be called unless the timer has started, and mouseEvent starts the timer, we must still handle starting the game in your listener's method.
#SuppressWarnings("serial")
public final class TheGame extends JPanel implements MouseListener, ActionListener {
public static final int WIDTH = 500, HEIGHT = 500;
private final String START_SCORE = "0",
START_MESSAGE = "Get Ready ! Click to Start.",
BACKGROUND_URL = "/res/flappy.png";
private boolean currentlyPlaying, readyToJump, isAlive = true;
private int score;
private Timer timer;
private Image background;
private GameLabel messageLabel, scoreLabel;
private Collection<Obstacle> obstaclesInOrder;
private LinkedList<Obstacle> obstacles;
private Ball ball;
public TheGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addMouseListener(this);
timer = new Timer(50, this);
background = loadBackgroundImage();
messageLabel = new GameLabel(START_MESSAGE, 150, 240);
scoreLabel = new GameLabel(START_SCORE, 250, 60);
obstacles = new LinkedList<>();
obstacles.removeAll(obstacles);
obstaclesInOrder = Arrays.asList(new Obstacle(175, 20, 45), new Obstacle(320), new Obstacle(460), new Obstacle(585), new Obstacle(700));
obstacles.addAll(obstaclesInOrder);
ball = new Ball(30, 100);
}
#Override
public void mouseClicked(MouseEvent e) {
if (!currentlyPlaying) {
startGame();
} else if (!isAlive) {
reset();
}
readyToJump = true;
}
private void startGame() {
currentlyPlaying = true;
messageLabel.update("");
timer.start();
}
private void endGame() {
isAlive = false;
scoreLabel.update("");
messageLabel.update("Game Over. Your score was " + Integer.toString(score));
timer.stop();
}
private void reset() {
ball.reset();
for (Obstacle obstacle : obstacles)
obstacle.reset();
messageLabel.update(START_MESSAGE, 150, 240);
scoreLabel.update(START_SCORE, 250, 60);
obstacles.removeAll(obstacles);
obstacles.addAll(obstaclesInOrder);
score = 0;
isAlive = true;
currentlyPlaying = false;
repaint();
}
#Override
public void actionPerformed(ActionEvent ae) {
update();
repaint();
}
private void update() {
if (isAlive) {
updateBallPosition();
updateObstaclePositions();
if(ballOutOfBounds() || playerCollidedWithObstacle()) {
endGame();
} else if(ballPassedObstacle()) {
addToScore();
setupNextObstacle();
}
}
}
private void updateBallPosition() {
if (readyToJump) {
readyToJump = false;
ball.jump();
} else {
ball.fall();
}
}
private void updateObstaclePositions() {
for (Obstacle obstacle : obstacles) {
if (obstacle.getX() <= -obstacle.getWidth()) {
obstacle.moveToBack();
continue;
}
obstacle.moveForward();
}
}
private void addToScore() {
scoreLabel.update(Integer.toString(++score));
}
private void setupNextObstacle() {
obstacles.addLast(obstacles.removeFirst());
}
private boolean ballOutOfBounds() {
return ball.getY() >= HEIGHT || ball.getY() <= 0;
}
private boolean ballAtObstacle() {
Obstacle currentObstacle = obstacles.getFirst();
return ball.getX() + ball.getWidth() >= currentObstacle.getX() && ball.getX() <= currentObstacle.getX() + currentObstacle.getWidth();
}
private boolean ballPassedObstacle() {
Obstacle currentObstacle = obstacles.getFirst();
return ball.getX() >= (currentObstacle.getX() + currentObstacle.getWidth());
}
private boolean playerCollidedWithObstacle() {
boolean collided = false;
if(ballAtObstacle()) {
for (Obstacle obstacle : obstacles) {
RoundRectangle2D top = obstacle.getTop();
RoundRectangle2D bottom = obstacle.getBottom();
if (ball.intersects(top.getX(), top.getY(), top.getWidth(), top.getHeight()) || ball.intersects(bottom.getX(), bottom.getY(), bottom.getWidth(), bottom.getHeight())) {
collided = true;
}
}
}
return collided;
}
private Image loadBackgroundImage() {
Image background = null;
URL backgroundPath = getClass().getResource(BACKGROUND_URL);
if(backgroundPath == null) {
background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
} else {
try {
background = ImageIO.read(backgroundPath);
} catch (IOException e) {
e.printStackTrace();
}
}
return background;
}
#Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.drawImage(background, 0, 0, null);
ball.paint(g);
for (Obstacle obstacle : obstacles)
obstacle.paint(g);
scoreLabel.paint(g);
messageLabel.paint(g);
}
//...
}
loadBackgroundImage() loads and returns an image. If a problem occurs (image probably isn't there), it returns a black image.
(Most of) The game logic is in the update() method. Although it should all be in there, we can't due to a design flaw (from you using Timer which manages update(), and you start the timer in a listener, therefore we needed some logic in the listener). Your logic should be easy to read, and every execution step should be monitored and set by highest priority to lowest.
First, I check to make sure the ball hasn't collided with anything or gone out of bounds. If one of those things occur, I end the game.
If not, I check to see if the player has passed an obstacle. If the player passes an obstacle, I add to the score:
private void update() {
if (ballOutOfBounds() || playerCollidedWithObstacle()) {
endGame();
} else if (ballPassedObstacle()) {
addToScore();
setupNextObstacle();
}
updateBallPosition();
updateObstaclePositions();
}
I then finally update the positions.
To avoid constantly comparing the player's position and the obstacle's position (to see if the player has passed it), I created a boolean ballAtObstacle() method, which checks if the player is at an obstacle. Only then do I compare positions:
private boolean playerCollidedWithObstacle() {
boolean collided = false;
if (ballAtObstacle()) {
for (Obstacle obstacle : obstacles) {
RoundRectangle2D top = obstacle.getTop();
RoundRectangle2D bottom = obstacle.getBottom();
if (ball.intersects(top.getX(), top.getY(), top.getWidth(), top.getHeight()) || ball.intersects(bottom.getX(), bottom.getY(), bottom.getWidth(), bottom.getHeight())) {
collided = true;
}
}
}
return collided;
}
The ball.intersects method call is a bit messy. I did this so the shape didn't have to be specific, although you could declare the intersects method as boolean intersects(Shape shape).
Finally, I gave it a more flappy bird feel by increasing the fall speed as you fall. When you jump again, it goes back to normal. The longer it takes you to jump, the faster you'll fall. If you don't like this feature, and don't know how to remove it, let me know and I'll show you how.
The other classes involved:
GameLabel.java
public class GameLabel {
private String message;
private Font font;
private Color color;
private int x, y;
public GameLabel(String message, int x, int y, Color color, Font font) {
update(message, x, y, color, font);
}
public GameLabel(String message, int x, int y) {
this(message, x, y, Color.BLACK, new Font("Matura MT Script Capitals", Font.ROMAN_BASELINE, 20));
}
public GameLabel() {
this("", 0, 0);
}
public void setMessage(String message) {
this.message = message;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setColor(Color color) {
this.color = color;
}
public void setFont(Font font) {
this.font = font;
}
public final void update(String message, int x, int y, Color color, Font font) {
this.message = message;
this.x = x;
this.y = y;
this.color = color;
this.font = font;
}
public void update(String message, int x, int y) {
update(message, x, y, color, font);
}
public void update(String message) {
update(message, x, y);
}
public void paint(Graphics2D g) {
g.setFont(font);
g.setColor(color);
g.drawString(message, x, y);
}
public Font getFont() {
return font;
}
public Color getColor() {
return color;
}
public String getMessage() {
return message;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Obstacle.java
public class Obstacle {
public static final int DEFAULT_TOP_HEIGHT = 175;
public static final int DEFAULT_BOTTOM_HEIGHT = 175;
public static final int DEFAULT_WIDTH = 30;
public static final int DEFAULT_ARCH_WIDTH = 20;
public static final int DEFAULT_ARCH_HEIGHT = 20;
public static final int DEFAULT_TOP_INSET = -5;
public static final int DEFAULT_BOTTOM_INSET = TheGame.HEIGHT + 5;
private RoundRectangle2D top, bottom;
private BasicStroke stroke;
private GradientPaint gradient;
private int initialX, x, width;
public Obstacle(int x, int width, int topHeight, int bottomHeight) {
this.x = initialX = x;
this.width = width;
top = new RoundRectangle2D.Double(x, DEFAULT_TOP_INSET, width, topHeight, DEFAULT_ARCH_WIDTH, DEFAULT_ARCH_HEIGHT);
bottom = new RoundRectangle2D.Double(x, DEFAULT_BOTTOM_INSET-bottomHeight, width, bottomHeight, DEFAULT_ARCH_WIDTH, DEFAULT_ARCH_HEIGHT);
stroke = new BasicStroke(10, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 20.0f, new float[] { 10.0f }, 0.0f);
gradient = new GradientPaint(20, 0, Color.DARK_GRAY, 0, 10, Color.GRAY, true);
}
public Obstacle(int x, int topHeight, int bottomHeight) {
this(x, DEFAULT_WIDTH, topHeight, bottomHeight);
}
public void reset() {
x = initialX;
top.setRoundRect(initialX, top.getY(), top.getWidth(), top.getHeight(), top.getArcWidth(), top.getArcHeight());
bottom.setRoundRect(initialX, bottom.getY(), bottom.getWidth(), bottom.getHeight(), bottom.getArcWidth(), bottom.getArcHeight());
}
public Obstacle(int x, int width) {
this(x, width, DEFAULT_TOP_HEIGHT, DEFAULT_BOTTOM_HEIGHT);
}
public Obstacle(int x) {
this(x, DEFAULT_WIDTH);
}
public void moveToBack() {
x = 600;
}
public void moveForward() {
x -= 5;
top.setRoundRect(x, top.getY(), top.getWidth(), top.getHeight(), top.getArcWidth(), top.getArcHeight());
bottom.setRoundRect(x, bottom.getY(), bottom.getWidth(), bottom.getHeight(), bottom.getArcWidth(), bottom.getArcHeight());
}
public RoundRectangle2D getTop() {
return top;
}
public RoundRectangle2D getBottom() {
return bottom;
}
public int getX() {
return x;
}
public int getWidth() {
return width;
}
public void paint(Graphics2D g) {
g.setPaint(gradient);
g.setStroke(stroke);
g.fill(top);
g.fill(bottom);
}
}
Ball.java
public class Ball {
public static final int DEFAULT_DROP_SPEED = 7;
private Ellipse2D ball;
private GradientPaint gradient;
private int initialY, x, y, width = 30, height = 30, dropSpeed = DEFAULT_DROP_SPEED;
public Ball(int x, int y) {
this.x = x;
this.y = initialY = y;
width = height = 30;
ball = new Ellipse2D.Double(x, y, width, height);
gradient = new GradientPaint(30, 0, Color.BLACK, 0, 20, Color.GREEN, true);
}
public void reset() {
y = initialY;
updateBall();
}
public void jump() {
dropSpeed = DEFAULT_DROP_SPEED;
y -= 40;
updateBall();
}
public void fall() {
y += dropSpeed++;
updateBall();
}
private void updateBall() {
ball.setFrame(x, y, width, height);
}
public boolean intersects(double x, double y, double w, double h) {
return ball.intersects(x, y, w, h);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return width;
}
public void paint(Graphics2D g) {
g.setPaint(gradient);
g.fill(ball);
}
public void moveForward() {
x += 7;
}
}
Reinitialize all the components by adding the initialization code to one method(resetAll) and call that method when u want to reinitailize
Below is an example:
import java.awt.*;
import java.awt.event.*;
public class ResetTest extends Frame{
Button b;
TextField tf;
Frame f;
Panel p;
public ResetTest(){
f=this; //intialize frame f to this to have access to our frame in event handler methods
resetAll(); //first time call to resetAll will initialize all the parameters of the frame
f.pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
this.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
this.setVisible(true);
}
/**
This method will be called on click of button to
reset all the parameters of the frame so that we
get fresh new frame, everything as it was before.
**/
public void resetAll(){
b=new Button("Reset");
p=new Panel(new FlowLayout(FlowLayout.CENTER,20,20));
p.add(b);
tf = new TextField("Edit And Reset");
p.add(tf);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
remove(p); //remove the panel that contains all our components
resetAll(); // reset all the components
f.pack(); //refreshes the view of frame when everything is reset.
}
});
add(p);
}
}
class NewClass{
public static void main(String[] args) {
ResetTest fReset = new ResetTest();
}
}

Categories

Resources