Uno card draw game cant print the card to the panel - java

Im working on a program that draws a card from a collection(deck) of uno cards. It should display the first card on startup, then every time the "next card" button is pressed it draws another card. However I'm very new to GUI's and can't figure out what i'm doing wrong. I get "Uno" in the box that should display the text representation of the card.
package Uno;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GameFrame extends JFrame
{
private PlayingCardPanel panel;
private JPanel field;
private JPanel menu;
public GameFrame(){
this.setLayout(new FlowLayout());
this.setSize( 300, 150);
this.setTitle("UNO");
this.createFieldPanel();
this.createMenuPanel();
this.add(field);
this.add(menu);
}
private void createMenuPanel(){
menu = new JPanel();
menu.setBounds(0,300,250,100);
JButton drawButton = new JButton("Next Card");
drawButton.setSize(300,200);
drawButton.addActionListener(new drawListener());
menu.add(drawButton);
}
private void createFieldPanel()
{
field = new JPanel();
field.setBounds(0,0,250,200);
panel = new PlayingCardPanel();
field.add(panel);
}
private class drawListener implements ActionListener{
public void actionPerformed(ActionEvent e){
panel.drawCard();
}
}
}
package Uno;
import java.awt.*;
import javax.swing.*;
public class PlayingCardPanel extends JPanel{
private StandardDeck playingdeck;
private PlayingCard card;
public PlayingCardPanel(){
this.setPreferredSize(new Dimension(100,100));
playingdeck = new StandardDeck();
playingdeck.shuffle();
playingdeck.drawTopCard();
}
public void drawCard(){
playingdeck.drawTopCard();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int panelWidth = this.getWidth();
int panelHeight = this.getHeight();
g.drawRoundRect(0, 0, panelWidth-1, panelHeight-1, 10, 10);
card = playingdeck.drawTopCard();
g.drawString(card.toString(), 75, 75);
}
}
package Uno;
import Uno.GameFrame;
public class GameApp{
/**
* #param args
*/
public static void main(String[] args)
{
GameFrame aBoard = new GameFrame();
aBoard.setVisible(true);
}
}
package Uno;
public class PlayingCard {
private int number;
private String color;
public int getNumber() {
return number;
}
public String getColor(){
return color;
}
public PlayingCard(PlayingCard card){
number = card.getNumber();
color = new String(card.getColor());
}
public PlayingCard(int cardNumber, String cardColor){
number = cardNumber;
color = cardColor;
}
}
package Uno;
public class PlayingCard {
private int number;
private String color;
public int getNumber() {
return number;
}
public String getColor(){
return color;
}
public PlayingCard(PlayingCard card){
number = card.getNumber();
color = new String(card.getColor());
}
public PlayingCard(int cardNumber, String cardColor){
number = cardNumber;
color = cardColor;
}
}
package Uno;
import java.util.Collections;
import java.util.Vector;
public class StandardDeck {
protected Vector<PlayingCard> cardsVector;
public StandardDeck(){
cardsVector = new Vector<PlayingCard>();
String[] colors = {"blue","red","yellow","green"};
for(String color : colors){
for(int i=1;i<=9;i++){
cardsVector.add(new PlayingCard(i,color));
cardsVector.add(new PlayingCard(i,color));
}
cardsVector.add(new PlayingCard(0,color));
for(int i=-3;i<0;i++){
cardsVector.add(new PlayingCard(i,color));
cardsVector.add(new PlayingCard(i,color));
}
}
for(int i=0;i<4;i++){
cardsVector.add(new PlayingCard(-4,"black"));
cardsVector.add(new PlayingCard(-5,"black"));
}
}
public int getSize(){
return cardsVector.size();
}
public StandardDeck reset(){
StandardDeck resetDeck = new StandardDeck();
return resetDeck;
}
public void shuffle(){
Collections.shuffle(cardsVector);
}
public PlayingCard drawTopCard(){
return new PlayingCard(cardsVector.remove(cardsVector.size()-1));
}
}
package Uno;
import Uno.IPlayingCard;
public interface IDeck
{
public void reset();
public void shuffle();
public IPlayingCard drawTopCard(PlayingCard card);
}
package Uno;
import Uno.PlayingCard;
public interface IPlayingCard extends Comparable<PlayingCard>{
public String getColor();
public String getNumber();
}
Thanks for any help!

It's actually printing something like Uno.PlayingCard#56609959 -- the last part of it is being truncated though, so you're only seeing "Uno" at the edge of your panel.
You are missing your toString() implementation in PlayingCard class.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int panelWidth = this.getWidth();
int panelHeight = this.getHeight();
g.drawRoundRect(0, 0, panelWidth - 1, panelHeight - 1, 10, 10);
card = playingdeck.drawTopCard();
g.drawString(card.toString(), 75, 75); // you're calling toString() here...
}
Since you don't have it implemented, it's calling the default Object.toString() method. You probably meant to add something like this to your PlayingCard class?
public String toString() {
return ""+number;
}

Related

How to paint over a JPanel?

I (A novice programmer) am trying to paint an oval over a JPanel. I am trying to use the method paint. However, it requires a Graphics argument. I get a NullPointerException when I include my Graphics as a argument because it is null, but I do not know how else to paint the oval. I tried repaint instead but nothing happened. Any help would be appreciated. Here is my main class:
public class Checkers extends JPanel{
public static final int BOARDSQUARES = 8;
public static final int BOARDSIZE = 75;
private JPanel[][] board;
private final Point point1;
private final LineBorder border1;
public JFrame frame;
checkerPiece piece = new checkerPiece(this);
Graphics g;
public Checkers(){
board = new JPanel[BOARDSQUARES][BOARDSQUARES];
point1 = new Point (BOARDSIZE,BOARDSIZE);
border1=new LineBorder(Color.BLACK, 1);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Checkers checkers = new Checkers();
checkers.frame=checkers.createJFrame();
checkers.board =checkers.createBoard(checkers.board, checkers.point1, checkers.border1);
for (int y=0;y<BOARDSQUARES;y++){
for (int x = 0;x<BOARDSQUARES;x++){
checkers.frame.getContentPane().add(checkers.board[y][x]);
}
}
checkers.paint(checkers.g);
}
private JPanel[][] createBoard (JPanel[][] board, Point point, LineBorder border1){
for (int row = 0; row<BOARDSQUARES;row++){
point.y=BOARDSIZE;
for (int col = 0; col <BOARDSQUARES;col++){
board[row][col] = new JPanel();
board[row][col].setLocation(point);
board[row][col].setVisible(true);
board[row][col].setSize(BOARDSIZE,BOARDSIZE);
board[row][col].setOpaque(true);
if ((row%2==0&&col%2==0)||(row%2==1&&col%2==1)){
board[row][col].setBackground(new Color (230,200,150));
} else if ((row%2==0&&col%2==1)||(row%2==1&&col%2==0)) {
board[row][col].setBackground(new Color (165, 42,42) );
}
board[row][col].setBorder(border1);
point.y = point.y+BOARDSIZE;
}
point.x=point.x+BOARDSIZE;
}
return board;
}
private JFrame createJFrame (){
JFrame mainFrame = new JFrame("Checkers");
mainFrame.setSize(1000,1000);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new Checkers());
return mainFrame;
}
#Override
public void paint (Graphics g){
System.out.println("hi");
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
piece.paint(g2d,board[0][0].getLocation().x,board[0][0].getLocation().y,Color.BLACK);
}
}
A necessary snippet from my other class (cherkerPiece piece):
public void paint (Graphics2D g, int x, int y, Color color){
g.setColor(color);
g.fillOval(x, y, DIAMETER, DIAMETER);
}
Thank you for your help
To create something as complex as a checkers game, you should follow the model / view / controller pattern when creating your Java Swing GUI.
I created a model class for a checker board square and another model class for a checker piece. I created a model class for the checker board and another model class to hold all of the checker pieces.
I created a view class to draw the checker board. I created another view class to create the main window.
I did not create any controller classes. This code just shows you how to draw a checker board. I put all of the classes together to make it easier to paste the code. You should separate the classes into separate Java files.
package com.ggl.testing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CheckerBoard implements Runnable {
private Board board;
private CheckerBoardPanel checkerBoardPanel;
private JFrame frame;
private Pieces pieces;
public static void main(String[] args) {
SwingUtilities.invokeLater(new CheckerBoard());
}
public CheckerBoard() {
this.board = new Board();
this.pieces = new Pieces();
}
#Override
public void run() {
frame = new JFrame("Checker Board");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
checkerBoardPanel = new CheckerBoardPanel(board, pieces);
frame.add(checkerBoardPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class CheckerBoardPanel extends JPanel {
private static final long serialVersionUID = 3770663347384271771L;
private Board board;
private Pieces pieces;
public CheckerBoardPanel(Board board, Pieces pieces) {
this.board = board;
this.pieces = pieces;
this.setPreferredSize(board.getPreferredSize());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Square[][] checkerBoard = board.getBoard();
for (int row = 0; row < checkerBoard.length; row++) {
for (int column = 0; column < checkerBoard[row].length; column++) {
Square square = checkerBoard[row][column];
Rectangle drawingRectangle = square.getDrawingRectangle();
g.setColor(square.getColor());
g.fillRect(drawingRectangle.x, drawingRectangle.y,
drawingRectangle.width, drawingRectangle.height);
}
}
List<Piece> checkerPieces = pieces.getPieces();
for (Piece checkerPiece : checkerPieces) {
Point coordinate = checkerPiece.getCoordinate();
Rectangle drawingRectangle = checkerBoard[coordinate.x][coordinate.y]
.getDrawingRectangle();
int x = drawingRectangle.x + drawingRectangle.width / 2;
int y = drawingRectangle.y + drawingRectangle.height / 2;
int radius = board.getSquareWidth() * 2 / 6;
g.setColor(checkerPiece.getColor());
g.fillOval(x - radius, y - radius, radius + radius, radius
+ radius);
}
}
}
public class Board {
private static final int BOARD_WIDTH = 8;
private static final int SQUARE_WIDTH = 64;
private Square[][] board;
public Board() {
this.board = initalizeBoard(BOARD_WIDTH, SQUARE_WIDTH);
}
private Square[][] initalizeBoard(int boardWidth, int squareWidth) {
Square[][] board = new Square[boardWidth][boardWidth];
int x = 0;
int y = 0;
for (int row = 0; row < boardWidth; row++) {
for (int column = 0; column < boardWidth; column++) {
Square square = new Square();
if (isLightSquare(row, column)) {
square.setColor(Color.WHITE);
} else {
square.setColor(Color.LIGHT_GRAY);
}
square.setCoordinate(new Point(row, column));
square.setDrawingRectangle(new Rectangle(x, y, squareWidth,
squareWidth));
board[row][column] = square;
x += squareWidth;
}
x = 0;
y += squareWidth;
}
return board;
}
public boolean isLightSquare(int row, int column) {
if (row % 2 == 0) {
if (column % 2 == 0) {
return true;
} else {
return false;
}
} else {
if (column % 2 == 0) {
return false;
} else {
return true;
}
}
}
public Dimension getPreferredSize() {
int width = SQUARE_WIDTH * 8 + 1;
return new Dimension(width, width);
}
public Square[][] getBoard() {
return board;
}
public int getSquareWidth() {
return SQUARE_WIDTH;
}
}
public class Square {
private Color color;
private Point coordinate;
private Rectangle drawingRectangle;
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
public Rectangle getDrawingRectangle() {
return drawingRectangle;
}
public void setDrawingRectangle(Rectangle drawingRectangle) {
this.drawingRectangle = drawingRectangle;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
public class Pieces {
private List<Piece> pieces;
public Pieces() {
this.pieces = addPieces();
}
private List<Piece> addPieces() {
List<Piece> pieces = new ArrayList<Piece>();
Piece piece = new Piece();
piece.setColor(Color.RED);
piece.setCoordinate(new Point(2, 1));
pieces.add(piece);
piece = new Piece();
piece.setColor(Color.BLACK);
piece.setCoordinate(new Point(5, 0));
pieces.add(piece);
// Add the rest of the red and black pieces here
return pieces;
}
public List<Piece> getPieces() {
return pieces;
}
public void addPiece(Piece piece) {
this.pieces.add(piece);
}
}
public class Piece {
private Color color;
private Point coordinate;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Point getCoordinate() {
return coordinate;
}
public void setCoordinate(Point coordinate) {
this.coordinate = coordinate;
}
}
}
you need to add a class that extends Canvas and do all your painting in that class. like this
public class FirstWindow extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public FirstWindow()
{
super("Kayte does not go to water parks");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
}
public class Start extends Canvas implements Runnable
public class Main
{
public static void main(String arg[])
{
FirstWindow fw = new FirstWindow();
Start game = new Start(500, 500);
fw.add(game);
fw.setVisible(true);
new Thread(game).start();
}
}

Java repaint() not working

I am making a simple program to paint a graph and some points in it. The points should be made with methods while changing coordinates of the g.fillOval but actually its painting only the last point.
Here is the code:
import javax.swing.*;
import java.awt.*;
public class PointGraphWriter extends JPanel
{
JFrame korniza = new JFrame();
private int x;
private int y;
private int length;
private String OX;
private String OY;
private String emri;
private int y_height;
private int x_num;
public PointGraphWriter()
{
int width= 500;
korniza.setSize(width,width);
korniza.setVisible(true);
korniza.setTitle(emri);
korniza.getContentPane().add(this);
}
public void paintComponent(Graphics g)
{
g.drawLine(x,y,x+length,y);
g.drawLine(x,y,x,y-length);
g.drawString(OX,x+length, y+15);
g.drawString(OY,x-15,y-length);
g.drawString("0", x -15,y);
g.drawString("0", x,y+15);
g.fillOval(x_num,y-y_height-2, 4 ,4);
}
public void setTitle(String name)
{
emri= name;
this.repaint();
}
public void setAxes(int x_pos, int y_pos, int axis_length, String x_label, String y_label)
{
x= x_pos;
y=y_pos;
length= axis_length;
OX = x_label;
OY = y_label;
}
public void setPoint1(int height)
{
y_height=height;
x_num = x-2;
this.repaint();
}
public void setPoint2(int height)
{
y_height=height;
x_num = x + length/5-2;
this.repaint();
}
}
and here is the main method:
public class TestPlot
{
public static void main(String[] a)
{
PointGraphWriter e = new PointGraphWriter();
e.setTitle("Graph of y = x*x");
e.setAxes(50, 110, 90, "5", "30");
int scale_factor = 3;
e.setPoint1(0 * scale_factor);
e.setPoint2(1 * scale_factor);
}
}
Please have a look at this example. Something in lines of this, you might have to incorporate in your example, to make it work. Simply use a Collection to store what you have previously painted, and when the new thingy comes along, simply add that thingy to the list, and repaint the whole Collection again. As shown below :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class RectangleExample {
private DrawingBoard customPanel;
private JButton button;
private Random random;
private java.util.List<Rectangle2D.Double> rectangles;
private ActionListener buttonActions =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Rectangle2D.Double rectangle = new Rectangle2D.Double(
(double) random.nextInt(100), (double) random.nextInt(100),
(double) random.nextInt(100), (double) random.nextInt(100));
rectangles.add(rectangle);
customPanel.setValues(rectangles);
}
};
public RectangleExample() {
rectangles = new ArrayList<Rectangle2D.Double>();
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Rectangle Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
customPanel = new DrawingBoard();
contentPane.add(customPanel, BorderLayout.CENTER);
button = new JButton("Create Rectangle");
button.addActionListener(buttonActions);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new RectangleExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawingBoard extends JPanel {
private java.util.List<Rectangle2D.Double> rectangles =
new ArrayList<Rectangle2D.Double>();
public DrawingBoard() {
setOpaque(true);
setBackground(Color.WHITE);
}
public void setValues(java.util.List<Rectangle2D.Double> rectangles) {
this.rectangles = rectangles;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rectangle2D.Double rectangle : rectangles) {
g.drawRect((int)rectangle.getX(), (int)rectangle.getY(),
(int)rectangle.getWidth(), (int)rectangle.getHeight());
}
System.out.println("WORKING");
}
}
See Custom Painting Approaches for examples of the two common ways to do painting:
Keep a List of the objects to be painted
Paint onto a BufferedImage
The approach you choose will depend on your exact requirement.

Maze Game Programming

This my code for the simple maze game. Its being compiled and class file of MazeGame.java and Board.java are being created but not of Player.java and Map.java. The code is being compiled error free but its not running. Please help me out.
//MazeGame.java
package mygame;
import javax.swing.*;
public class MazeGame {
public static void main(String[] args) {
new MazeGame();
}
public MazeGame() {
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.setSize(450,450);
f.setLocationRelativeTo(null);
f.add(new Board());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Board.java
package mygame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
private String Message="";
private Font font = new Font("Comic Sans",Font.BOLD,50);
public Board() {
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0; y<14; y++) {
for(int x=0; x<14; x++) {
if(m.getMap(x,y).equals("f")) {
g.drawImage(m.getFinish(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("g")) {
g.drawImage(m.getGrass(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("w")) {
g.drawImage(m.getWall(),x*32,y*32,null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()*32,p.getTileY()*32,null);
}
if(win)
{
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(Message,100,300);
}
}
public class Al extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode==KeyEvent.VK_W) || (keyCode==KeyEvent.VK_UP)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(0,-1);
}
}
if((keyCode==KeyEvent.VK_S) || (keyCode==KeyEvent.VK_DOWN)) {
if(!(m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))) {
p.move(0,1);
}
}
if((keyCode==KeyEvent.VK_A) || (keyCode==KeyEvent.VK_LEFT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(-1,0);
}
}
if((keyCode==KeyEvent.VK_D) || (keyCode==KeyEvent.VK_RIGHT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(1,0);
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")) {
Message = "WINNER!!!";
win = true;
}
repaint();
}
}
//Map.java
package mygame;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.*;
public class Map {
private Scanner s;
private String Map[] = new String[14];
private Image grass,wall,finish;
public Map() {
ImageIcon img = new ImageIcon("G://sonali_java//mygame//grass.png");
grass = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//wall.png");
wall = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public String getMap(int x,int y) {
String index = Map[y].substring(x,x+1);
return index;
}
public Image getGrass() {
return grass;
}
public Image getWall() {
return wall;
}
public Image getFinish() {
return finish;
}
public void openFile() {
try {
s= new Scanner(new File("G://sonali_java//mygame//Map.txt"));
}
catch(Exception e) {
System.out.println("Error Loading File!!!!");
}
}
public void readFile() {
while(s.hasNext()) {
for(int i=0; i<14; i++) {
Map[i] = s.next();
}
}
}
public void closeFile() {
s.close();
}
}
//Player.java
package mygame;
import java.awt.*;
public class Player {
private int tileX,tileY;
private Image player;
public Player() {
tileX=1;
tileY=1;
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
player = img.getImage();
}
public Image getPlayer() {
return player;
}
public int getTileX() {
return tileX;
}
public int getTileY() {
return tileY;
}
public void move(int dx, int dy) {
tileX += dx;
tileY += dy;
}
}
I dont want to be mad but you are defining different folder locations
in some places "G://sonali_java//mygane//object.png", check "mygaNe"
in some places "G://sonali_java//mygame//Map.txt", check "mygaMe"
Are you sure while loading it does not throw a NullPointerException ?
Are you aware that you can, place code like
public void draw(Graphics g){
g.drawImage(playerImg, getX(), getY(), null);
}
in your player class, thus leaving the player class with drawing the player and simply calling the players draw method inside your Board paint method? This can also be done for drawing the map. Remember to call the draw methods in the paint method.
ALSO, THIS
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
check your directory location

Can't subtract 1 from bank

PS: the links you have to take out the () from http because I don't have enough rep points or something.
Board:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Turn_Ticker turn = new Turn_Ticker();
Bank bank = new Bank();
Image Background;
Timer timer;
String time="";
public Board() {
setFocusable(true);
ImageIcon icon = new ImageIcon("res/Level1.png"); // calls image for background
Background = icon.getImage(); // sets variable background to icon image
timer = new Timer(5,this); // sets how fast page refreshes
timer.start();
}
public void actionPerformed(ActionEvent event) { // Refreshes page according to timer
repaint();
}
public void paint(Graphics paint) { // paints on frame
super.paint(paint);
Graphics2D p = (Graphics2D) paint;
turn.getTick();
bank.subBank();
p.drawImage(Background, 0, 0, null);
p.drawString(bank.getBank()+"",125,70);
p.drawString(bank.getEnemy_Bank()+"",125,115);
p.drawString(turn.getSecond()+" Second(s) Turn: "+turn.getTurn(), 120, 200);
if(turn.getTick())
p.drawString("Ticker = true", 500,500);/*
if(turn.getNum()==0)
p.drawString("Number = 0", 500,550);
if(turn.getNum()==0&&turn.getTick()){
bank.subBank();
p.drawString("Both are =", 500, 600);
}*/
//System.out.println("X: "+mouse.getX()+" Y: "+mouse.getY());
}
}
Turn_Ticker:
package game;
public class Turn_Ticker {
long before,after,difference;
boolean checkTime=true;
int seconds=0;
boolean ticker=false;
int turn=1;
int num=0;
public Turn_Ticker(){
if (checkTime == true)
before=System.currentTimeMillis();
checkTime=false;
}
public int getSecond() {
after=System.currentTimeMillis();
difference= after-before;
if(difference >= 1000) {
before=System.currentTimeMillis();
if(seconds<=0) {
seconds=30;
ticker=true;
num=0;
}
else {
seconds-=1;
num=1;
ticker=false;
}
}
return seconds;
}
public boolean getTick() {
if(ticker&&num==0) {
turn++;
}
return ticker;
}
public int getNum(){
return num;
}
public int getTurn() {
return turn;
}
public boolean getTickVar(){
return ticker;
}
}
Bank:
package game;
public class Bank {
Turn_Ticker turn = new Turn_Ticker();
int bank=5, enemy_Bank=5;
int baseRein=3, reinforcements,num=0;
public Bank(){
if(turn.getTick()==false)
num=0;
}
public int getBank(){
return bank;
}
public int getEnemy_Bank(){
return enemy_Bank;
}
public void subBank(){
if(turn.getNum()==0&&turn.getTick())
bank--;
}
public void subEn_Bank(){
enemy_Bank-=1;
}
}
Frame:
package game;
import javax.swing.*;
import java.awt.Font;
public class Frame {
public Frame() {
JFrame frame = new JFrame();
frame.add(new Board());
frame.setTitle("WSMD");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024,768);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args){
new Frame();
}
}
My problem is that I can not, for the life of me, figure out why it won't subtract -1(bank.subBank()) from the bank. I've printed out the code and went through it step by step.

Swing Animation Issue?

I am trying to make a Sprite move across a background image in swing, but every time I update the position and it repaints, it repaints with the previous position of the image as well. However I am just trying to make it so that it moves 10 pixels for every time the right arrow is pressed. Here is the Main class, which controls the movement.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Main extends JFrame implements KeyListener, ActionListener{
private static final long serialVersionUID = 1L;
//Caitlan info
Image caitlanImage = new ImageIcon("Caitlan.png").getImage();
Person caitlan = new Person(caitlanImage, "Caitlan", 50, 200, true);
//Jake info
Image jakeImage = new ImageIcon("Jake.png").getImage();
Person jake = new Person(jakeImage, "Jake", 0, 200, true);
//Level objects
Image granadaBackground = new ImageIcon("Granada Background.jpg").getImage();
Level granada = new Level(granadaBackground, "Granada", new Point(600, 300));
Image elevatorBackground = new ImageIcon("Elevator.png").getImage();
Level elevator = new Level(elevatorBackground, "Elevator", new Point(0,0));
public static void main(String[] args) throws InterruptedException{
new Main();
}
public Main() throws InterruptedException{ //Constructor (only should be called once)
setSize(700,300);
setTitle("Project Anniversary");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addKeyListener(this);
}
public void paint(Graphics g){ //Overridden paint method.
if(checkIfLevelDone(granada, caitlan)){
granada.setDone();
}
if(!granada.isDone()){
g.drawImage(granada.getImage(), 0, 0, granadaBackground.getWidth(null), granadaBackground.getHeight(null),null);
g.drawImage(jake.getImage(), jake.getPosX(), jake.getPosY(), jake.getImage().getWidth(null), jake.getImage().getHeight(null),null);
g.drawImage(caitlan.getImage(), caitlan.getPosX(), caitlan.getPosY(), caitlan.getImage().getWidth(null), caitlan.getImage().getHeight(null), null);
}
else if(granada.isDone()){
setSize(300,300);
g.drawImage(elevator.getImage(), 0, 0,
elevator.getImage().getWidth(null), elevator.getImage().getHeight(null),null);
g.drawImage(jake.getImage(), jake.getPosX(), jake.getPosY(),
jake.getImage().getWidth(null), jake.getImage().getHeight(null),null);
g.drawImage(caitlan.getImage(), caitlan.getPosX(), caitlan.getPosY(),
caitlan.getImage().getWidth(null), caitlan.getImage().getHeight(null), null);
}
}
public void keyPressed(KeyEvent e) { //Method called whenever a key is pressed
caitlan.printLocation();
int code = e.getKeyCode();
if(code == KeyEvent.VK_RIGHT){ //When the user presses the right arrow
caitlan.setLocation(caitlan.getPosX() + 10, caitlan.getPosY());
repaint();
}
if(code == KeyEvent.VK_LEFT){ //When the user presses the left arrow
caitlan.setLocation(caitlan.getPosX() - 10, caitlan.getPosY());
repaint();
}
if(code == KeyEvent.VK_UP){ //Implement jumping code here
repaint();
}
}
public boolean checkIfLevelDone(Level l, Person p){
//Method to check if a given level is done
if(l.getCompletionPoint().x <= p.getPosX()){
return true;
}
return false;
}
public void followOtherPerson(Person a, Person b) throws InterruptedException{
//Method to follow the other character
}
public void jump(Person p) throws InterruptedException{ //Jump method
caitlan.setLocation(caitlan.getPosX(), caitlan.getPosY() - 60);
repaint();
}
public void keyReleased(KeyEvent e) { //IGNORE
}
public void keyTyped(KeyEvent e) { //IGNORE
}
public void actionPerformed(ActionEvent e) { //IGNORE
}
}
Here is the Level class:
import java.awt.Image;
import java.awt.Point;
public class Level {
//Private attributes
private Image backgroundImage; //Image
private String levelName; //Name of level
private boolean levelComplete; //Status that holds if the level is done
private Point completionPoint; //Point at which the level is completed
public Level(Image i, String l, Point p){ //Constructor
this.backgroundImage = i;
this.levelName = l;
this.completionPoint = p;
levelComplete = false;
}
public void setDone(){
levelComplete = true;
}
public boolean isDone(){ //Returns if the level is done or not
return levelComplete;
}
public Image getImage(){ //Getters and setters
return backgroundImage;
}
public String getLevelName(){
return levelName;
}
public void setImage(Image i){
this.backgroundImage = i;
}
public void setName(String name){
this.levelName = name;
}
public Point getCompletionPoint(){
return completionPoint;
}
public void setCompletionPoint(Point p){
this.completionPoint = p;
}
}
And finally, here is the Person class.
import java.awt.*;
public class Person{
//Attributes
private Image image;
private String name;
private int xlocation;
private int ylocation;
/*Boolean that you can publically access to determine if the given Person object is a
player*/
public boolean isPlayer;
public Person(Image i, String s){ //Really shouldn't be used
this.image = i;
this.name = s;
}
public Person(Image i){ //Really shouldn't be used
this.image = i;
}
public Person(Image i, String s, int xloc, int yloc){ //Basic constructor
this.name = s;
this.image = i;
this.xlocation = xloc;
this.ylocation = yloc;
}
public Person(Image i, String s, int xloc, int yloc, boolean isPlayer){ //Detailed constructor
this.name = s;
this.image = i;
this.xlocation = xloc;
this.ylocation = yloc;
this.isPlayer = isPlayer;
}
public void printLocation(){
System.out.println("Person " + name + " is at location (" + xlocation +", " + ylocation +").");
}
public void incrementPositionX(){ //Increase xlocation by 1
xlocation++;
}
public void incrementPositionY(){ //Increase ylocation by 1
ylocation++;
}
public void setName(String name){ //Method to change the name of a sprite
this.name = name;
}
public void setImage(Image image){ //Method to change the image of a sprite
this.image = image;
}
public Image getImage(){ //Get image
return image;
}
public int getPosX(){ //Get x position
return xlocation;
}
public int getPosY(){ //Get y position
return ylocation;
}
public String getName(){ //Get name
return name;
}
public void setLocation(int x, int y){ //Method to change the location of a sprite
this.xlocation = x;
this.ylocation = y;
}
}
You should not paint directly on top level container such as JFrame. Instead, use JComponent or JPanel. Override paintComponent() for painting rather than paint() and don't forget to call super.paintComponent(g)
Take a look at Performing Custom Painting tutorial for more information.
Also, key listener is a lower level interface. It is best to use Key Bindings instead. See How to Use Key Bindings for details and examples.
Also, there is no need to create ImageIcon to get Image. Look into ImageIO.read() methods.

Categories

Resources