ActionListener only responding once - java

I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:
Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.
For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.
WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;
public class WheelBuilder extends JApplet{
public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;
public void init()
{
resize(540,600);
spin = new JButton("SPIN!");
spin.addActionListener(new spinListener());
Container cp = getContentPane();
cp.setVisible(true);
cp.setBackground((Color.GREEN).darker().darker());
Abet = new JButton("+BET+");
Abet.addActionListener(new aListener());
Sbet = new JButton("-BET-");
Sbet.addActionListener(new sListener());
cp.add(Sbet);
cp.add(spin);
cp.add(Abet);
cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
page.setColor((Color.GREEN).darker().darker());
page.fillRect(0, 0, 1000, 1000);
setBackground((Color.GREEN).darker().darker());
wheel.paintWheel(page, wheel.getStatus());
page.setColor(Color.BLACK);
page.drawString("TOTAL: "+total, 400, 50);
page.drawString("Current Bet: "+Tbet, 400, 25);
page.drawString("Last Spin:", 50, 25);
page.setColor(Color.WHITE);
page.fillOval(260, 75, 20, 20);
page.fillRect(50, 35, 60, 25);
page.setColor(color);
page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
int countEnd = randomSpin();
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
if (wheel.getStatus())
{
color = Color.RED;
last = (int)(Math.random()*7)*2+1;
}
else
{
color = Color.BLACK;
last = (int)(Math.random()*7)*2+2;
}
}
public void changeWheel()
{
int countEnd = randomSpin();
if (count <= countEnd)
{
wheel.setStatus(!(wheel.getStatus()));
repaint();
count++;
}
}
public int randomSpin()
{
return ((int)(Math.random()*2)+21);
}
}
public class aListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet <= total-50)
{
Tbet+=50;
}
last = 0;
repaint();
}
}
public class sListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet > 50)
{
Tbet-=50;
}
last = 0;
repaint();
}
}
}
RouletteWheel
import javax.swing.JApplet;
import java.awt.*;
public class RouletteWheel extends JApplet {
public boolean status;
public void paintWheel(Graphics page, boolean status)
{
if (status){
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.BLACK);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.setColor(Color.RED);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
if (!status)
{
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.RED);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
}
public boolean getStatus()
{
return status;
}
public void setStatus(boolean s)
{
status = s;
}
}

Related

Attempting to create a moving sprite in java but there is an afterimage

I'm trying to create a moving sprite in java, which I have managed to do, except every time I move it there is an afterimage that follows the sprite. Are there any ways I could easily fix this problem without radically changing my code?
I'm completely stumped as to any kind of ways I could fix this problem.
To get the full context I have to post all three files.
Here's the first file:
package gameproject;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class CarMovement {
private int dx;
private int dy;
private int x = 635;
private int y = 550;
private int w;
private int h;
private Image moveimage;
public CarMovement() {
loadImage();
}
private void loadImage() {
ImageIcon q = new ImageIcon("racecar.png");
moveimage = q.getImage();
w = moveimage.getWidth(null);
h = moveimage.getHeight(null);
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public Image getImage() {
return moveimage;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = -10;
}
if (key == KeyEvent.VK_D) {
dx = 10;
}
if (key == KeyEvent.VK_W) {
dy = -10;
}
if (key == KeyEvent.VK_S) {
dy = 10;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
if (key == KeyEvent.VK_W) {
dy = 0;
}
if (key == KeyEvent.VK_S) {
dy = 0;
}
}
}
The second:
package gameproject;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CarMovement2 extends JPanel implements ActionListener {
private Timer timer;
private CarMovement racecar;
private final int DELAY = 10;
public CarMovement2() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
racecar = new CarMovement();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0, 204, 0));
g.fillRect(0, 0, 400, 1100);
g.fillRect(1525, 0, 400, 1100);
g.setColor(new Color(102, 102, 102));
g.fillRect(400, 0, 1125, 1100);
g.setColor(new Color(255, 255, 255));
g.fillRect(940, 25, 25, 100);
g.fillRect(940, 325, 25, 100);
g.fillRect(940, 475, 25, 100);
g.fillRect(940, 625, 25, 100);
g.fillRect(940, 775, 25, 100);
g.fillRect(940, 925, 25, 100);
g.setColor(new Color(255, 255, 255));
g.fillRect(400, 175, 1125, 100);
g.setColor(new Color(0, 0, 0));
g.fillRect(400, 225, 50, 50);
g.fillRect(450, 175, 50, 50);
g.fillRect(500, 225, 50, 50);
g.fillRect(550, 175, 50, 50);
g.fillRect(600, 225, 50, 50);
g.fillRect(650, 175, 50, 50);
g.fillRect(700, 225, 50, 50);
g.fillRect(750, 175, 50, 50);
g.fillRect(800, 225, 50, 50);
g.fillRect(850, 175, 50, 50);
g.fillRect(900, 225, 50, 50);
g.fillRect(950, 175, 50, 50);
g.fillRect(1000, 225, 50, 50);
g.fillRect(1050, 175, 50, 50);
g.fillRect(1100, 225, 50, 50);
g.fillRect(1150, 175, 50, 50);
g.fillRect(1200, 225, 50, 50);
g.fillRect(1250, 175, 50, 50);
g.fillRect(1300, 225, 50, 50);
g.fillRect(1350, 175, 50, 50);
g.fillRect(1400, 225, 50, 50);
g.fillRect(1450, 175, 50, 50);
g.fillRect(1500, 225, 25, 50);
g.setColor(new Color(255, 255, 255));
g.fillRect(380, 0, 20, 1100);
g.fillRect(1525, 0, 20, 1100);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(racecar.getImage(), racecar.getX(),
racecar.getY(), this);
}
#Override
public void actionPerformed(ActionEvent e) {
step();
}
private void step() {
racecar.move();
repaint(racecar.getX()-1, racecar.getY()-1,
racecar.getWidth()+2, racecar.getHeight()+2);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
racecar.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racecar.keyPressed(e);
}
}
}
The third:
package gameproject;
import java.awt.EventQueue;
import javax.swing.JFrame;
public final class CarMovement3 extends JFrame {
public CarMovement3() {
InitUI();
}
private void InitUI() {
add(new CarMovement2());
setTitle("Top Speed Triumph");
setSize(1900, 1100);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CarMovement3 ex = new CarMovement3();
ex.setVisible(true);
});
}
}
And the link to the sprite :
http://www.clker.com/clipart-red-sports-car-top-view.html
So, your problem stems from using...
repaint(racecar.getX() - 1, racecar.getY() - 1,
racecar.getWidth() + 2, racecar.getHeight() + 2);
Basically, you're not covering enough of the "existing" area that use to occupy to completely "remove" it.
You can simply use repaint() instead and it will solve your basic problem. I'd avoid worrying about this level of optimisation until it actually becomes a problem.
If you want to use it, then I would take a snap shot of the location of the care before it was moved (ie grab it's current x/y position) and merge that with it's new location so you cover both areas. That, or call repaint(x, y, width, height) twice, once with the old position and once with the new
private void step() {
Rectangle old = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
racecar.move();
Rectangle now = new Rectangle(racecar.getX(), racecar.getY(), racecar.getWidth(), racecar.getHeight());
repaint(old);
repaint(now);
}
Also, you'll find that KeyListener is unreliable, I would suggest making use of the key bindings API which will solve the issues which KeyListener suffers from
I would also recommend using ImageIO over ImageIcon as more reliable way of loading your images, see Reading/Loading an Image for more details

Java object not updating from KeyEvent?

I am currently working on a simple program that will highlight a square depending on the corresponding key press (q for top left, e for top right, etc), and I cannot seem to get the rectangles to trigger from my key events. The key events are triggered, and the if statements are met for each one (put in a system.out in the color if statement and it displayed when key was pressed), however, the objects are not updating at all. Here is my code:
package acm;
import acm.graphics.*;
import acm.program.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class NewFinalGame extends GraphicsProgram {
private GObject redBrick, blueBrick, yellowBrick, greenBrick;
private GRectangle redBounds, blueBounds, yellowBounds, greenBounds;
Color dullRed = new Color(102, 0, 0);
Color dullBlue = new Color(0, 0, 51);
Color dullYellow = new Color(100, 100, 0);
Color dullGreen = new Color(0, 51, 0);
int level = 1;
public void init() {
addKeyListeners();
addMouseListeners();
setSize(500, 500);
setBackground(Color.black);
mainMenu();
}
public void run() {
waitForClick();
removeAll();
addSquares();
redBounds = redBrick.getBounds();
blueBounds = blueBrick.getBounds();
yellowBounds = yellowBrick.getBounds();
greenBounds = yellowBrick.getBounds();
}
public void mainMenu() {
GLabel welcome = new GLabel("Welcome to Simon.");
welcome.setColor(Color.white);
add(welcome, 100, 100);
GLabel clickToContinue = new GLabel("Click to continue...");
clickToContinue.setColor(Color.white);
add(clickToContinue, 150, 150);
}
public void addSquares() {
yellowBrick = new GRect(50, 50, 175, 175);
((GRect) yellowBrick).setFilled(true);
yellowBrick.setColor(dullYellow);
add(yellowBrick);
blueBrick = new GRect(275, 50, 175, 175);
((GRect) blueBrick).setFilled(true);
blueBrick.setColor(dullBlue);
add(blueBrick);
redBrick = new GRect(50, 275, 175, 175);
((GRect) redBrick).setFilled(true);
redBrick.setColor(dullRed);
add(redBrick);
greenBrick = new GRect(275, 275, 175, 175);
((GRect) greenBrick).setFilled(true);
greenBrick.setColor(dullGreen);
add(greenBrick);
}
public void highlight(GObject rect) {
if (rect.getColor() == dullYellow) {
System.out.println("Success!");
rect.setColor(Color.yellow);
pause(1000);
rect.setColor(dullYellow);
}
if (rect.getColor() == dullBlue) {
rect.setColor(Color.blue);
pause(1000);
rect.setColor(dullBlue);
}
if (rect.getColor() == dullRed) {
rect.setColor(Color.red);
pause(1000);
rect.setColor(dullRed);
}
if (rect.getColor() == dullGreen) {
rect.setColor(Color.green);
pause(1000);
rect.setColor(dullGreen);
}
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_Q:
highlight(yellowBrick);
break;
case KeyEvent.VK_W:
highlight(blueBrick);
break;
case KeyEvent.VK_A:
highlight(redBrick);
break;
case KeyEvent.VK_S:
highlight(greenBrick);
break;
}
}
}
Thank you for any help.

Create basic animation

How can I create basic animation in Java?
Currently i am trying to implement a basic animation program using swing in Java.
But i am not getting whether my logic for program in correct or not.
My program implements Runnable, ActionListener interfaces and also extends JApplet.
I want to know that, is it necessary to differentiate start method of JApplet and Runnable?
And if yes then why..?
My program is basic balloon program, when I click on start button balloons start moving upward and comes to floor again. This will be continue till i press stop button.
Here is my code.
public class Balls extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
JPanel btnPanel=new JPanel();
static boolean flag1=true;
static boolean flag2=true;
static boolean flag3=false;
static int h;
static int temp=10;
Thread t=new Thread(this);
JButton start;
JButton stop;
public void init()
{
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't create GUI because of exception");
System.exit(0);
}
}
private void makeGUI() {
start=new JButton("start");
stop=new JButton("stop");
btnPanel.add(start);
btnPanel.add(stop);
add(btnPanel,BorderLayout.NORTH);
}
public void run()
{
while(true)
{
if(flag1)
{
repaint();
flag1=false;
}
else
{
try
{
wait();
flag3=true;
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Error ocuured !!\n Exiting..");
System.exit(0);
}
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h=Integer.parseInt(getParameter("height"));
if (flag1)
{
g.setColor(Color.RED);
g.fillOval(10,h,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,h,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h,60,40);
g.setColor(Color.pink);
g.fillOval(370,h,65,45);
flag1=false;
}
else
{
g.setColor(Color.RED);
g.fillOval(10,h-temp,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h-temp,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h-temp,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,355,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h-temp,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h-temp,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h-temp,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h-temp,60,40);
g.setColor(Color.pink);
g.fillOval(370,h-temp,65,45);
if(flag2 && temp<=400)
{
temp+=10;
if(temp==400)
{
flag2=false;
}
}
else if(!flag2)
{
temp-=10;
if(temp==10)
{
flag2=true;
}
}
else
{
}
}
}
public void start()
{
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.start();
if(flag3)
{
notify();
}
}
});
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag1=false;
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
repaint();
t=null;
}
}
});
}
}
1) Use SwingTimer as recommended instead of your Runnable implementation.
2) Read about custom painting , and here
3) draw at the JPanel instead of on JFrame
I have changed your code, examine it. I think, that it does what you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Balls extends JApplet {
private static final long serialVersionUID = 1L;
JPanel btnPanel = new JPanel();
static boolean flag1 = true;
static boolean flag2 = true;
static boolean flag3 = false;
static int h;
static int temp = 10;
JButton start;
JButton stop;
private Timer timer;
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
makeGUI();
}
});
}
private void makeGUI() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
});
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.stop();
}
});
btnPanel.add(start);
btnPanel.add(stop);
add(new MyPanel(), BorderLayout.CENTER);
add(btnPanel, BorderLayout.NORTH);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = Integer.parseInt(getParameter("height"));
if (flag1) {
g.setColor(Color.RED);
g.fillOval(10, h, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, h, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h, 65, 45);
flag1 = false;
} else {
g.setColor(Color.RED);
g.fillOval(10, h - temp, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h - temp, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h - temp, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, 355, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h - temp, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h - temp, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h - temp, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h - temp, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h - temp, 65, 45);
if (flag2 && temp <= 400) {
temp += 10;
if (temp == 400) {
flag2 = false;
}
} else if (!flag2) {
temp -= 10;
if (temp == 10) {
flag2 = true;
}
} else {
}
}
}
}
}

Why isn't this keyListener Working? How can i get it to work?

So I have my keyListener called TAdapter. For some reason i can't get this to work right. I have set the focus to the panel and it still doesnt work. I have searched and searched the web and found absolutely nothing on why this isn't working correctly. I'm new to java and completely stumped
import java.awt.*;
import javax.swing.JPanel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.TimerTask;
import java.util.Timer;
import java.awt.Toolkit;
public class Game extends JPanel implements Shared{
private static Brick bricks[];
private static Ball ball;
private static Paddle paddle;
Timer timer;
public Game(){
super();
this.addKeyListener(new TAdapter());
this.setFocusable(true);
this.requestFocusInWindow();
setSize(Shared.WIDTH, Shared.HEIGHT);
bricks = new Brick[100];
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
}
public void addNotify(){
super.addNotify();
gameInit();
}
public static void gameInit(){
ball = new Ball();
paddle = new Paddle();
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.GREEN, true);
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
switch(i){
case 0:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 255), true);
break;
case 1:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 20, 127), true);
break;
case 2:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 0), true);
break;
case 3:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 127, 0), true);
break;
case 4:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 255, 0), true);
break;
case 5:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 0), true);
break;
case 6:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 127), true);
break;
case 7:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 127, 255), true);
break;
case 8:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 0, 255), true);
break;
case 9:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(127, 0, 255), true);
break;
}
bricks[k] = new Brick((j*BRICK_WIDTH) + (j*BRICK_SEP), (i*BRICK_HEIGHT) + BRICK_Y_OFFSET+(i*BRICK_SEP), gp);
k++;
}
}
}
public void paint(Graphics g){
super.paint(g);
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.RED, true);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g2.fillOval(ball.getX(), ball.getY(), BALL_RADIUS, BALL_RADIUS);
g2.fillRoundRect((Shared.WIDTH/2) - PADDLE_WIDTH/2, Shared.HEIGHT - PADDLE_Y_OFFSET*2, PADDLE_WIDTH, PADDLE_HEIGHT, 3, 3);
for(int i = 0; i< 100; i++){
if(!bricks[i].isDestroyed()){
g2.setPaint(bricks[i].getPaint());
g2.fillRoundRect(bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), 5, 5);
}
}
Toolkit.getDefaultToolkit().sync();
g2.dispose();
}
private class TAdapter extends KeyAdapter{
public void keyReleased(KeyEvent e){
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e){
paddle.keyPressed(e);
}
}
class ScheduleTask extends TimerTask{
public void run(){
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
public void stopGame(){
timer.cancel();
}
public void checkCollision() {
if (ball.getRect().getMaxY() > Shared.HEIGHT) {
stopGame();
}
for (int i = 0, j = 0; i < 100; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
if (j == 100) {
stopGame();
}
}
if ((ball.getRect()).intersects(paddle.getRect())) {
int paddleLPos = (int)paddle.getRect().getMinX();
int ballLPos = (int)ball.getRect().getMinX();
int first = paddleLPos + 8;
int second = paddleLPos + 16;
int third = paddleLPos + 24;
int fourth = paddleLPos + 32;
if (ballLPos < first) {
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballLPos >= first && ballLPos < second) {
ball.setXDir(-1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos >= second && ballLPos < third) {
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballLPos >= third && ballLPos < fourth) {
ball.setXDir(1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos > fourth) {
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < 100; i++) {
if ((ball.getRect()).intersects(bricks[i].getRect())) {
int ballLeft = (int)ball.getRect().getMinX();
int ballHeight = (int)ball.getRect().getHeight();
int ballWidth = (int)ball.getRect().getWidth();
int ballTop = (int)ball.getRect().getMinY();
Point pointRight =
new Point(ballLeft + ballWidth + 1, ballTop);
Point pointLeft = new Point(ballLeft - 1, ballTop);
Point pointTop = new Point(ballLeft, ballTop - 1);
Point pointBottom =
new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDestroyed()) {
if (bricks[i].getRect().contains(pointRight)) {
ball.setXDir(-1);
}
else if (bricks[i].getRect().contains(pointLeft)) {
ball.setXDir(1);
}
if (bricks[i].getRect().contains(pointTop)) {
ball.setYDir(1);
}
else if (bricks[i].getRect().contains(pointBottom)) {
ball.setYDir(-1);
}
bricks[i].setDestroyed(true);
}
}
}
}
}`
then here is the main
import javax.swing.*;
public class BreakOut extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
static Game game =new Game();
public BreakOut()
{
add(game);
setTitle("Breakout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(Shared.WIDTH, Shared.HEIGHT);
setResizable(false);
setVisible(true);
setIgnoreRepaint(true);
}
public static void main(String arg[]){
new BreakOut();a
}
}
Your key listener just sends the events to paddle.
You might want to include the code (or at least look in the code) for paddle.keyPressed(e) and paddle.keyReleased(e); but really, you probably shouldn't have your paddle object handling the keys directly. It is nice to translate your key presses to in-game meaningful calls, like paddle.moveUp() or something.
Im not sure where the shared interface comes from/does, but try implementing KeyListener. "Public class Game extends JPanel implements Shared, KeyListner" if you keep using the shared but like i said idk what its purpose is or what it does right off the top of my head.

repaint problem

I have a problem with my repaint in the method move. I dont know what to doo, the code is below
import java.awt.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.lang.*;
public class bbb extends JPanel
{
public Stack<Integer> stacks[];
public JButton auto, jugar, nojugar;
public JButton ok, ok2;
public JLabel info = new JLabel("Numero de Discos: ");
public JLabel instruc = new JLabel("Presiona la base de las torres para mover las fichas");
public JLabel instruc2 = new JLabel("No puedes poner una pieza grande sobre una pequenia!");
public JComboBox numeros = new JComboBox();
public JComboBox velocidad = new JComboBox();
public boolean seguir = false, parar = false, primera = true;
public int n1, n2, n3;
public int click1 = 0;
public int opcion = 1, tiempo = 50;
public int op = 1, continuar = 0, cont = 0;
public int piezas = 0;
public int posx, posy;
public int no;
public bbb() throws IOException
{
stacks = new Stack[3];
stacks[0] = new Stack<Integer>();
stacks[1] = new Stack<Integer>();
stacks[2] = new Stack<Integer>();
setPreferredSize(new Dimension(1366, 768));
ok = new JButton("OK");
ok.setBounds(new Rectangle(270, 50, 70, 25));
ok.addActionListener(new okiz());
ok2 = new JButton("OK");
ok2.setBounds(new Rectangle(270, 50, 70, 25));
ok2.addActionListener(new vel());
add(ok2);
ok2.setVisible(false);
auto = new JButton("Automatico");
auto.setBounds(new Rectangle(50, 80, 100, 25));
auto.addActionListener(new a());
jugar = new JButton("PLAY");
jugar.setBounds(new Rectangle(100, 100, 70, 25));
jugar.addActionListener(new play());
nojugar = new JButton("PAUSE");
nojugar.setBounds(new Rectangle(100, 150, 70, 25));
nojugar.addActionListener(new stop());
setLayout(null);
info.setBounds(new Rectangle(50, 50, 170, 25));
info.setForeground(Color.white);
instruc.setBounds(new Rectangle(970, 50, 570, 25));
instruc.setForeground(Color.white);
instruc2.setBounds(new Rectangle(970, 70, 570, 25));
instruc2.setForeground(Color.white);
add(instruc);
add(instruc2);
add(jugar);
add(nojugar);
jugar.setVisible(false);
nojugar.setVisible(false);
add(info);
info.setVisible(false);
add(ok);
ok.setVisible(false);
add(auto);
numeros.setBounds(new Rectangle(210, 50, 50, 25));
numeros.addItem(1);
numeros.addItem(2);
numeros.addItem(3);
numeros.addItem(4);
numeros.addItem(5);
numeros.addItem(6);
numeros.addItem(7);
numeros.addItem(8);
numeros.addItem(9);
numeros.addItem(10);
add(numeros);
numeros.setVisible(false);
velocidad.setBounds(new Rectangle(150, 50, 100, 25));
velocidad.addItem("Lenta");
velocidad.addItem("Intermedia");
velocidad.addItem("Rapida");
add(velocidad);
velocidad.setVisible(false);
}
public void Mover(int origen, int destino)
{
for (int i = 0; i < 3; i++)
{
System.out.print("stack " + i + ": ");
for (int n : stacks[i])
{
System.out.print(n + ";");
}
System.out.println("");
}
System.out.println("de <" + origen + "> a <" + destino + ">");
stacks[destino].push(stacks[origen].pop());
System.out.println("");
this.validate();
this.repaint();
}
public void hanoi(int origen, int destino, int cuantas)
{
while (parar)
{
}
if (cuantas <= 1)
{
Mover(origen, destino);
}
else
{
hanoi(origen, 3 - (origen + destino), cuantas - 1);
Mover(origen, destino);
hanoi(3 - (origen + destino), destino, cuantas - 1);
}
}
public void paintComponent(Graphics g)
{
ImageIcon fondo = new ImageIcon("fondo.jpg");
g.drawImage(fondo.getImage(), 0, 0, 1366, 768, null);
g.setColor(new Color((int) (Math.random() * 254),
(int) (Math.random() * 255),
(int) (Math.random() * 255)));
g.fillRect(0, 0, 100, 100);
g.setColor(Color.white);
g.fillRect(150, 600, 250, 25);
g.fillRect(550, 600, 250, 25);
g.fillRect(950, 600, 250, 25);
g.setColor(Color.red);
g.fillRect(270, 325, 10, 275);
g.fillRect(270 + 400, 325, 10, 275);
g.fillRect(270 + 800, 325, 10, 275);
int x, y, top = 0;
g.setColor(Color.yellow);
x = 150;
y = 580;
for (int ii : stacks[0])
{
g.fillRect(x + ((ii * 125) / 10), y - (((ii) * 250) / 10), ((10 - ii) * 250) / 10, 20);
}
x = 550;
y = 580;
for (int ii : stacks[1])
{
g.fillRect(x + ((ii * 125) / 10), y - (((ii) * 250) / 10), ((10 - ii) * 250) / 10, 20);
}
x = 950;
y = 580;
for (int ii : stacks[2])
{
g.fillRect(x + ((ii * 125) / 10), y - (((ii) * 250) / 10), ((10 - ii) * 250) / 10, 20);
}
System.out.println("ENTRO");
setOpaque(false);
}
private class play implements ActionListener //manual
{
public void actionPerformed(ActionEvent algo)
{
parar = false;
if (primera = true)
{
hanoi(0, 2, no);
primera = false;
}
}
}
private class stop implements ActionListener //manual
{
public void actionPerformed(ActionEvent algo)
{
parar = true;
}
}
private class vel implements ActionListener //manual
{
public void actionPerformed(ActionEvent algo)
{
if (velocidad.getSelectedItem() == "Lenta")
{
tiempo = 150;
}
else if (velocidad.getSelectedItem() == "Intermedia")
{
tiempo = 75;
}
else
{
tiempo = 50;
}
ok2.setVisible(false);
jugar.setVisible(true);
nojugar.setVisible(true);
}
}
private class a implements ActionListener //auto
{
public void actionPerformed(ActionEvent algo)
{
auto.setVisible(false);
info.setVisible(true);
numeros.setVisible(true);
ok.setVisible(true);
op = 3;
}
}
private class okiz implements ActionListener //ok
{
public void actionPerformed(ActionEvent algo)
{
no = Integer.parseInt(numeros.getSelectedItem().toString());
piezas = no;
if (no > 0 && no < 11)
{
info.setVisible(false);
numeros.setVisible(false);
ok.setVisible(false);
for (int i = no; i > 0; i--)
{
stacks[0].push(i);
}
opcion = 2;
if (op == 3)
{
info.setText("Velocidad: ");
info.setVisible(true);
velocidad.setVisible(true);
ok2.setVisible(true);
}
}
else
{
}
repaint();
}
}
}
the code of the other class that calls the one up is below:
import java.awt.*;
import java.io.*;
import java.net.URL;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
import java.awt.event.*;
public class aaa extends JPanel
{
private ImageIcon Background;
private JLabel fondo;
public static void main(String[] args) throws IOException
{
JFrame.setDefaultLookAndFeelDecorated(true);
final JPanel cp = new JPanel(new BorderLayout());
JFrame frame = new JFrame ("Torres de Hanoi");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize(550,550);
frame.setVisible(true);
bbb panel = new bbb();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Assuming that you see the progress in the println statements but not on the screen, it is because a call to repaint is not synchronous. Swing has a special thread for handling UI - called Event Dispatch Thread. A call to repaint is handled by that thread, but asynchronously - after all the current events scheduled on that thread have been processed.
When you call hanoi in your actionPerformed, that is done on the same UI thread. What happens is that until your recursion is fully done, repaint() calls are just queued. Once the recursion completes (and all stacks have been moved in the model), the UI thread processes all repaint() requests, painting - what i assume - the final state.
What you need to do is to separate the model processing into a separate worker thread. On every recursion step, issue a repaint() call and sleep for a few hundred milliseconds. This will allow the UI thread to repaint the current state of the model and let the user actually trace the progress.

Categories

Resources