Related
I have a Robot method declared in the gameplay class, I have declared the variables but It will not excecated the loop properly, I assume I mis stepped somewhere in the calling of the variables or method. I have it set to pull the X position of the ball and move towards that by using the robot class to press a key, which works just fine on the keyboard (i.e. I can press the keys specified and the paddle moves)
I tried to re declare the variables in the method, the coordinates of both the paddle and ball works, the game functions, but the robot method is not executing at all. I tried to create a new instance of the method in the main method, but nothing changes, I tried to use the "this." function instead of declaring a new object in the method, but it just throws errors. Sorry about the code, I am fairly new to Java, and I am more experienced with C# and unity as opposed to the terminal and stuff like this. Here is the Gameplay Class.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Robot;
public class TestGameplay extends JPanel implements KeyListener, ActionListener
{
private boolean play = false;
private int score = 0;
private int totalBricks = 48;
private Timer timer;
private int delay=8;
private int playerX = 310;
public int paddlePos;
private int ballposX = 120;
public int ballX;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public TestGameplay()
{
map = new MapGenerator(4, 12);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer=new Timer(delay,this);
timer.start();
paddlePos = playerX;
ballX = ballposX;
}
public void Robot() throws AWTException {
Robot breaker = new Robot();
int ballPos = ballposX;
if (ballPos > playerX) {
breaker.keyPress(KeyEvent.VK_2);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_2);
} else {
breaker.keyPress(KeyEvent.VK_1);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_1);
}
}
public void paint(Graphics g)
{
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
// drawing map
map.draw((Graphics2D) g);
// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
// the scores
g.setColor(Color.white);
g.setFont(new Font("serif",Font.BOLD, 25));
g.drawString(""+score, 590,30);
// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
// the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
// when you won the game
if(totalBricks <= 0)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("You Won", 260,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
// when you lose the game
if(ballposY > 570)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("Game Over, Scores: "+score, 190,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
g.dispose();
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_2)
{
if(playerX >= 600)
{
playerX = 600;
}
else
{
moveRight();
}
}
if (e.getKeyCode() == KeyEvent.VK_1)
{
if(playerX < 10)
{
playerX = 10;
}
else
{
moveLeft();
}
}
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if(!play)
{
play = true;
ballposX = 120;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator(3, 7);
repaint();
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void moveRight()
{
play = true;
playerX+=20;
}
public void moveLeft()
{
play = true;
playerX-=20;
}
public void actionPerformed(ActionEvent e)
{
timer.start();
if(play)
{
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = -2;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 70, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = ballXdir + 1;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 30, 550, 40, 8)))
{
ballYdir = -ballYdir;
}
// check map collision with the ball
A: for(int i = 0; i<map.map.length; i++)
{
for(int j =0; j<map.map[0].length; j++)
{
if(map.map[i][j] > 0)
{
//scores++;
int brickX = j * map.brickWidth + 80;
int brickY = i * map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect))
{
map.setBrickValue(0, i, j);
score+=5;
totalBricks--;
// when ball hit right or left of brick
if(ballposX + 19 <= brickRect.x || ballposX + 1 >= brickRect.x + brickRect.width)
{
ballXdir = -ballXdir;
}
// when ball hits top or bottom of brick
else
{
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if(ballposX < 0)
{
ballXdir = -ballXdir;
}
if(ballposY < 0)
{
ballYdir = -ballYdir;
}
if(ballposX > 670)
{
ballXdir = -ballXdir;
}
repaint();
}
}
}
Here is the Main method
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws AWTException {
JFrame obj=new JFrame();
TestGameplay gamePlay = new TestGameplay();
Robot robot
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Breakout Ball");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
obj.setVisible(true);
}
}
There is the map generator class as well, but It it not relevant to this I think
** I pulled the base game from Git but had to tweak some settings
Cannot put my game into the GUI without there being issues. When starting the GUI, it shows the game. It glitches out and only fixes after pressing on of the buttons. However the buttons are hidden unless you put your mouse over it. Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
public class BBSays extends JFrame implements ActionListener, MouseListener
{
private BufferedImage image;
public static BBSays bbsays;
public Renderer renderer;
public static final int WIDTH = 800, HEIGHT = 800;
public int flashed = 0, glowTime, dark, ticks, indexPattern;
public boolean creatingPattern = true;
public ArrayList<Integer> pattern;
public Random random;
private boolean gameOver;
private JPanel game;
JFrame frame = new JFrame("BB8 Says");
private JPanel menu;
private JPanel credits;
ImageIcon bbegif = new ImageIcon("tumblr_o0c57n9gfv1tha1vgo1_r3_250.gif");
public BBSays()
{
Timer timer = new Timer(20, this);
renderer = new Renderer();
frame.setSize(WIDTH +7, HEIGHT +30);
frame.setVisible(true);
frame.addMouseListener(this);
frame.add(renderer);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
start();
timer.start();
menu = new JPanel();
credits = new JPanel();
game = new JPanel();
menu.setBackground(Color.yellow);
credits.setBackground(Color.yellow);
game.setBackground(Color.yellow);
JButton button = new JButton("Start");
JButton button2 = new JButton("Exit");
JButton button4 = new JButton("Start");
JLabel greet = new JLabel(" Welcome to BB8 Says");
JLabel jif = new JLabel(bbegif);
JLabel jif2 = new JLabel(bbegif);
JLabel saus = new JLabel("BB8 Image: https://49.media.tumblr.com/7ba3be87bff2efc009e9cfa889d46b4e/tumblr_o0c57n9gfv1tha1vgo1_r3_250.gif");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setContentPane(game);
frame.invalidate();
frame.validate();
};
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
};
});
menu.setLayout(new GridLayout(2,2));
menu.add(jif2);
menu.add(greet);
menu.add(jif);
menu.add(button);
menu.add(button6);
menu.add(button2);
frame.setVisible(true);
}
private class MenuAction implements ActionListener {
private JPanel panel;
private MenuAction(JPanel pnl) {
this.panel = pnl;
}
#Override
public void actionPerformed(ActionEvent e) {
changePanel(panel);
}
}
private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().doLayout();
update(getGraphics());
}
public void start()
{
random = new Random();
pattern = new ArrayList<Integer>();
indexPattern = 0;
dark = 2;
flashed = 0;
ticks = 0;
}
public static void main(String[] args)
{
bbsays = new BBSays();
}
#Override
public void actionPerformed(ActionEvent e)
{
ticks++;
if (ticks % 20 == 0)
{
flashed = 0;
if (dark >= 0)
{
dark--;
}
}
if (creatingPattern)
{
if (dark <= 0)
{
if (indexPattern >= pattern.size())
{
flashed = random.nextInt(40) % 4 + 1;
pattern.add(flashed);
indexPattern = 0;
creatingPattern = false;
}
else
{
flashed = pattern.get(indexPattern);
indexPattern++;
}
dark = 2;
}
}
else if (indexPattern == pattern.size())
{
creatingPattern = true;
indexPattern = 0;
dark = 2;
}
renderer.repaint();
}
public void paint(Graphics2D g)
{
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.yellow);
g.fillRect(0, 0, WIDTH, HEIGHT);
if (flashed == 1)
{
g.setColor(Color.blue);
}
else
{
g.setColor(Color.blue.darker());
}
g.fillRect(0, 0, WIDTH/2, HEIGHT/2);
if (flashed == 2)
{
g.setColor(Color.green);
}
else
{
g.setColor(Color.green.darker());
}
g.fillRect(WIDTH/2, 0, WIDTH/2, HEIGHT/2);
if (flashed == 3)
{
g.setColor(Color.orange);
}
else
{
g.setColor(Color.orange.darker());
}
g.fillRect(0, HEIGHT/2, WIDTH/2, HEIGHT/2);
if (flashed == 4)
{
g.setColor(Color.gray);
}
else
{
g.setColor(Color.gray.darker());
}
g.fillRect(WIDTH/2, HEIGHT/2, WIDTH/2, HEIGHT/2);
g.setColor(Color.BLACK);
g.fillRoundRect(220, 220, 350, 350, 300, 300);
g.fillRect(WIDTH/2 - WIDTH/14, 0, WIDTH/7, HEIGHT);
g.fillRect(0, WIDTH/2 - WIDTH/12, WIDTH, HEIGHT/7);
g.setColor(Color.yellow);
g.setStroke(new BasicStroke(200));
g.drawOval(-100, -100, WIDTH+200, HEIGHT+200);
g.setColor(Color.black);
g.setStroke(new BasicStroke(5));
g.drawOval(0, 0, WIDTH, HEIGHT);
if (gameOver)
{
g.setColor(Color.WHITE);
g.setFont(new Font("Comic Sans", 1, 80));
g.drawString("You let", WIDTH / 2 - 140, HEIGHT / 2 - 70);
g.drawString("down BB8 :(", WIDTH / 2 - 220, HEIGHT / 2 );
g.drawString("Try again!", WIDTH / 2 - 195, HEIGHT / 2 + 80);
}
else
{
g.setColor(Color.WHITE);
g.setFont(new Font("Ariel", 1, 144));
g.drawString(indexPattern + "/" + pattern.size(), WIDTH / 2 - 100, HEIGHT / 2 + 42);
}
}
#Override
public void mousePressed(MouseEvent e)
{
int x = e.getX(), y = e.getY();
if (!creatingPattern && !gameOver)
{
if (x>0 && x<WIDTH/2 && y>0 && y<HEIGHT/2)
{
flashed = 1;
ticks = 1;
}
else if (x>WIDTH/2 && x<WIDTH && y>0 && y<HEIGHT/2)
{
flashed = 2;
ticks = 1;
}
else if (x>0 && x<WIDTH/2 && y>HEIGHT/2 && y<HEIGHT)
{
flashed = 3;
ticks = 1;
}
else if (x>WIDTH/2 && x<WIDTH && y>HEIGHT/2 && y<HEIGHT)
{
flashed = 4;
ticks = 1;
}
if (flashed != 0)
{
if (pattern.get(indexPattern)==flashed)
{
indexPattern++;
}
else
{
gameOver = true;
}
}
else
{
start();
gameOver = true;
}
}
else if (gameOver)
{
start();
gameOver = false;
}
}
Here is the code for the renderer class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Renderer extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (BBSays.bbsays != null)
{
BBSays.bbsays.paint((Graphics2D) g);
}
}
}
I think that the issue is here as I use the super. method and want to put the graphics on the game JPanel in the main code. I have tried many ways of doing this but I am not able to put the game on a JPanel.
If you can help it is greatly appreciated.
When you click in a box, it should create a circle in that box from the designated coordinate. Unless if its already there then its removed. How do I get currentx and currenty coordinates into the fill oval?
public class Grid extends Applet{
boolean click;
public void init()
{
click = false;
addMouseListener(new MyMouseListener());
}
public void paint(Graphics g)
{
super.paint(g);
g.drawRect(100, 100, 400, 400);
//each box
g.drawRect(100, 100, 100, 100);
g.drawRect(200, 100, 100, 100);
g.drawRect(300, 100, 100, 100);
g.drawRect(400, 100, 100, 100);
//2y
g.drawRect(100, 200, 100, 100);
g.drawRect(200, 200, 100, 100);
g.drawRect(300, 200, 100, 100);
g.drawRect(400, 200, 100, 100);
//3y1x
g.drawRect(100, 300, 100, 100);
g.drawRect(200, 300, 100, 100);
g.drawRect(300, 300, 100, 100);
g.drawRect(400, 300, 100, 100);
//4y1x
g.drawRect(100, 400, 100, 100);
g.drawRect(200, 400, 100, 100);
g.drawRect(300, 400, 100, 100);
g.drawRect(400, 400, 100, 100);
if (click)
{
g.fillOval(currentx, currenty, 100, 100); // problem HERE
}
}
private class MyMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
int nowx = e.getX();
int nowy = e.getY();
nowx = nowx / 100;
String stringx = Integer.toString(nowx);
stringx = stringx+"00";
int currentx = Integer.parseInt(stringx);
nowy = nowy /100;
String stringy = Integer.toString(nowy);
stringy = stringy+"00";
int currenty = Integer.parseInt(stringy);
click = true;
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
Your main problem is, painting in Swing/AWT is destructive, that is, each time your paint method is called, you are expected to repaint the current state of the component.
In that case, what you really need is some way to model the state of the game so when paint is called, you can repaint it in some meaningful way. This a basic concept of a Model-View-Controller paradigm, where you separate the responsibility of the program into separate layers.
The problem then becomes, how do you translate from the view to model?
The basic idea is take the current x/y coordinates of the mouse and divide it by the cell size. You also need to ensure that the results are within the expected ranges, as you could get a result which is beyond the columns/rows of grids
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final int CELL_COUNT = 3;
private int[][] board;
private int[] cell;
private boolean isX = true;
public TestPane() {
board = new int[CELL_COUNT][CELL_COUNT];
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int[] cell = getCellAt(e.getPoint());
if (board[cell[0]][cell[1]] == 0) {
board[cell[0]][cell[1]] = isX ? 1 : 2;
isX = !isX;
repaint();
}
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
cell = getCellAt(e.getPoint());
repaint();
}
});
}
protected int[] getCellAt(Point p) {
Point offset = getOffset();
int cellSize = getCellSize();
int x = p.x - offset.x;
int y = p.y - offset.y;
int gridx = Math.min(Math.max(0, x / cellSize), CELL_COUNT - 1);
int gridy = Math.min(Math.max(0, y / cellSize), CELL_COUNT - 1);
return new int[]{gridx, gridy};
}
protected Point getOffset() {
int cellSize = getCellSize();
int x = (getWidth() - (cellSize * CELL_COUNT)) / 2;
int y = (getHeight() - (cellSize * CELL_COUNT)) / 2;
return new Point(x, y);
}
protected int getCellSize() {
return Math.min(getWidth() / CELL_COUNT, getHeight() / CELL_COUNT) - 10;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Point offset = getOffset();
int cellSize = getCellSize();
if (cell != null) {
g2d.setColor(new Color(0, 0, 255, 128));
g2d.fillRect(
offset.x + (cellSize * cell[0]),
offset.y + (cellSize * cell[1]),
cellSize,
cellSize);
}
g2d.setColor(Color.BLACK);
FontMetrics fm = g2d.getFontMetrics();
for (int col = 0; col < CELL_COUNT; col++) {
for (int row = 0; row < CELL_COUNT; row++) {
int value = board[col][row];
int x = offset.x + (cellSize * col);
int y = offset.y + (cellSize * row);
String text = "";
switch (value) {
case 1:
text = "X";
break;
case 2:
text = "O";
break;
}
x = x + ((cellSize - fm.stringWidth(text)) / 2);
y = y + ((cellSize - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
}
}
int x = offset.x;
int y = offset.y;
for (int col = 1; col < CELL_COUNT; col++) {
x = offset.x + (col * cellSize);
g2d.drawLine(x, y, x, y + (cellSize * CELL_COUNT));
}
x = offset.x;
for (int row = 1; row < CELL_COUNT; row++) {
y = offset.x + (row * cellSize);
g2d.drawLine(x, y, x + (cellSize * CELL_COUNT), y);
}
g2d.dispose();
}
}
}
First off, if you want to truncate a number to the nearest 100, e.g. 142 becomes 100, all you have to do is:
num = (num/100)*100;
this is because when you divide 2 integers it automatically truncates it, and you can just multiply it back to get the number. And what I think you want in this case is to create some field variables and some accessor methods. At the top of your MouseListener class, you will need to add:
private int mouseX=0;
private int mouseY=0;
then to be able to access these variables from outside of the mouselistener class you will need to add accessor methods:
public int getMouseX(){
return mouseX;
}
in your Grid Class, you can add the field:
private MyMouseListener listener;
and then initialize it in your init by doing:
listener = new MyMouseListener();
addMouseListener(listener);
then you can do the same for mouseY, and finally from your paint method you can then call:
int mouseX = listener.getMouseX();
int mouseY = listener.getMouseY();
and from there it is as simple as doing if statements or switch statements to find which box you clicked in!
I'm trying to make a simulation on our school's enrollment system. But I'm stuck on a problem that i can't figure out why, the box that i rendered are blinking. I need it not to. can you help me? thanks.
import java.awt.Color;
import java.awt.*;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template
* in the editor.
*/
/**
*
* #author paolo
*/
public class simulator extends JPanel {
Thread tr;
Image i;
Graphics gbfr;
Dimension size;
int num = 0, check, wid, hyt, oq;
Random rand = new Random();
Dimension locs[];
list waiting, queue;
boolean allowMove = false;
simulator(int w, int h) {
oq = 0;
wid = w;
hyt = h;
tr = new tr1();
locs = new Dimension[30];
waiting = new list(50);
queue = new list(30);
int tw, u;
for (u = 0, tw = 64; u < 10; u++, tw += 55) {
locs[u] = new Dimension(tw, 275);
locs[19 - u] = new Dimension(tw, 325);
locs[u + 20] = new Dimension(tw, 375);
}
}
public void paint(Graphics g) {
i = createImage(getWidth(), getHeight());
gbfr = i.getGraphics();
gbfr.setColor(getBackground());
gbfr.fillRect(0, 0, getWidth(), getHeight());
gbfr.setColor(getForeground());
paintComponent(gbfr);
g.drawImage(i, 0, 0, this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
drawSettings(g);
drawStudents(g);
}
protected void drawSettings(Graphics g) {
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
}
protected void drawStudents(Graphics g) {
waiting.drawStudents(g);
}
public class tr1 extends Thread implements Runnable {
public void run() {
for (check = 0;; check++) {
num++;
try {
if (num % 100 == 0 && waiting.max != waiting.countL) {
waiting.add();
}
repaint();
Thread.sleep(1);
} catch (InterruptedException e) {
}
//repaint();
}
}
}
public class list {
int max, countL;
students temp, head;
list() {
head = new students();
countL = 0;
head.setNext(null);
max = 0;
}
list(int m) {
countL = 0;
head = new students(1);
list();
max = m;
head.setNext(null);
}
void add() {
students t;
t = head;
if (countL == 0) {
countL++;
t.setNext(new students());
} else {
temp = head.getNext();
while (temp != null) {
temp = temp.getNext();
}
countL++;
head.setNext(new students());
//updateCount();
}
}
void delete(int c) {
students t = head, t1;
int aa = 1;
if (countL == 1) {
if (c == 1) {
t.setNext(null);
}
} else {
if (c == 1) {
t.setNext(t.getNext());
} else {
for (t = t.getNext(); aa < c; aa++, t = t.getNext()) {
}
t.setNext(t.getNext().getNext());
}
}
}
void updateCount() {
students t = new students();
t = head;
t = t.getNext();
System.out.println(countL + "__");
for (int q = 1; q < countL; q++) {
System.out.println(t);
t.setCount(q);
t = t.getNext();
}
}
void drawStudents(Graphics g) {
students t = head;
if (countL != 0) {
t = t.getNext();
while (t != null) {
g.setColor(t.getClr());
g.fillRect(t.xpos, t.ypos, 10, 10);
t = t.getNext();
}
}
}
}
public class students {
int xpos, ypos, year, level, servtime, waittime, pos, destx, desty, count;
Color clr;
boolean active, onq;
students next;
students() {
//System.out.print("Recieved");
xpos = rand.nextInt((wid - 580) + 1) + 580;
onq = false;
ypos = rand.nextInt((hyt - 280) + 1) + 280;
waittime = rand.nextInt((100 - 50) + 1) + 50;
servtime = rand.nextInt((200 - 100) + 1) + 100;
count = 0;
level = 0;
next = null;
year = rand.nextInt((4 - 1) + 1) + 1;
clr = new Color(12, 12, 12);
if (year == 1) {
clr = Color.GREEN;
} else if (year == 2) {
clr = Color.YELLOW;
} else if (year == 3) {
clr = Color.RED;
} else {
clr = Color.BLUE;
}
pos = 0;
active = false;
}
students(int i) {
count = 0;
}
void setxpos(int x) {
xpos = x;
}
void setypos(int y) {
ypos = y;
}
void setpos(int p) {
pos = p;
}
void setCount(int q) {
count = q;
}
students getNext() {
return next;
}
Color getClr() {
return clr;
}
void setNext(students n) {
next = n;
}
int getpos() {
return pos;
}
boolean isActive() {
return active;
}
void activate() {
active = true;
}
}
}
Don't override the simulator JPanel's paint(Graphics g) method
Don't call paintComponent directly. You mess with all of Swing's graphics by doing these two things.
Draw your stable background image to a BufferedImage, and then draw the image in your JPanel's paintComponent(Graphics g) method.
Note that your code does not reproduce your problem for me. I don't see any blinking. Should there be some animation going on that we're not seeing?
e.g.,
// class names should begin with an upper-case letter
public class Simulator extends JPanel {
// ....
private BufferedImage settings = null;
Simulator(int w, int h) {
// ....
settings = createSettings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(wid, hyt);
}
// public void paint(Graphics g) {
// i = createImage(getWidth(), getHeight());
// gbfr = i.getGraphics();
// gbfr.setColor(getBackground());
// gbfr.fillRect(0, 0, getWidth(), getHeight());
//
// gbfr.setColor(getForeground());
// paintComponent(gbfr);
//
// g.drawImage(i, 0, 0, this);
// }
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
if (settings != null) {
g.drawImage(settings, 0, 0, this);
}
// !! drawSettings(g);
drawStudents(g);
}
private BufferedImage createSettings() {
int width = 700;
int height = 500;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
g.setColor(new Color(225, 225, 225));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(200, 200, 200));
g.fillRect(0, 0, 600, 200);
g.setColor(Color.black);
g.drawRect(0, 200, 20, 20);
g.drawRect(145, 200, 20, 20);
g.drawRect(290, 200, 20, 20);
g.drawRect(435, 200, 20, 20);
g.drawRect(580, 200, 20, 20);
g.drawRect(0, 0, 600, 200);
g.setColor(new Color(200, 200, 200));
g.fillRect(1, 180, 19, 40);
g.fillRect(146, 180, 19, 40);
g.fillRect(291, 180, 19, 40);
g.fillRect(436, 180, 19, 40);
g.fillRect(581, 180, 19, 40);
g.setColor(Color.black);
g.drawString("Cashier 1", 62, 190);
g.drawString("Cashier 2", 207, 190);
g.drawString("Cashier 3", 352, 190);
g.drawString("Cashier 4", 497, 190);
g.fillRect(20, 270, 560, 20);//
g.fillRect(20, 320, 560, 20);
g.fillRect(20, 370, 560, 20);
g.dispose();
return img;
}
// ...
}
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 {
}
}
}
}
}