I'm trying to create a "Paint" application with Processing 3, and I want to add buttons to change the color (later on for brushes, size, etc).
I'm stuck because I'm keep getting a NullPointerException for adding the button to my array.
(I know i could just ask for the mouseX and Y after creating every button without the array but it seems a bit unprofessional to me and would get very messy by time).
ERROR: Line 24 -> "allButtons[counter].name = Name;"
*Sidenote: I'm pretty new to Processing / Java xd
This is my code:
class button
{
public String name;
public int x;
public int y;
public color curColor;
};
color currentColor = color(0, 0, 0);
String currentBrush = "Brush";
int currentBrushSize = 3;
button[] allButtons = new button[100];
int buttonSize = 20;
int counter = 1;
void setup() {
size(800, 600);
background(255);
surface.setResizable(true);
surface.setTitle("Not Skribble");
}
void button(String Name, int X, int Y, color CurColor) {
allButtons[counter].name = Name;
allButtons[counter].x = X;
allButtons[counter].y = Y;
allButtons[counter].curColor = CurColor;
counter += 1;
fill(CurColor);
rect(X, Y, buttonSize, buttonSize);
if (overButton(X, Y, X + buttonSize, Y + buttonSize)) {
fill(0, 0, 0, 80);
rect(X, Y, buttonSize, buttonSize);
}
}
boolean overButton(int minX, int minY, int maxX, int maxY) {
if (mouseX >= minX && mouseX <= maxX) {
if (mouseY >= minY && mouseY <= maxY) {
return true;
}
}
return false;
}
boolean buttonPressed(String name) {
for (int i = 0; i < allButtons.length; i++) {
if (name == allButtons[i].name) {
if (mouseX >= allButtons[i].x && mouseX <= allButtons[i].x + buttonSize) {
if (mouseY >= allButtons[i].y && mouseY <= allButtons[i].y + buttonSize) {
if (mousePressed) {
return true;
}
}
}
}
}
return false;
}
void setColor(color settingColor) {
currentColor = settingColor;
}
void setBrush(String settingBrush) {
currentBrush = settingBrush;
}
void setBrushSize(int settingBrushSize) {
currentBrushSize = settingBrushSize;
}
void colorButtons() {
button("Orange", 10, 10, color(255, 100, 0));
if (buttonPressed("Orange")) setColor(color(255, 100, 0));
button("Blue", 50, 10, color(255, 100, 0));
if (buttonPressed("Blue")) setColor(color(0, 0, 255));
}
void brushButtons(){
}
void settingButtons(){
}
void draw() {
noStroke();
fill(100);
rect(0, 0, width, 70);
colorButtons();
brushButtons();
settingButtons();
}
When you create an array like this:
Button[] allButtons = new Button[100];
You're creating an array that can hold 100 Button instances. But that array starts out as empty. Try doing something like this:
println(allButtons[0]);
You'll see that this prints out null, which means that the value is basically empty. You haven't actually added any Button instances to your array. This is why you're getting an error: because you're trying to use values that don't exist.
To add an instance to your array, you'd do something like this:
allButtons[0] = new Button();
At which point it would be safe to do use that value:
allButtons[0].name = "cancel";
By the way, you might consider just using an ArrayList instead of an array. Or take advantage of Processing's array functions that allow you to add elements to an array instead of creating an array with a size of 100.
Also, in the future please try to use proper naming conventions. Variables should start with a lower-case letter, and classes should start with an upper-case letter. This makes your code much easier to read.
Related
I'm trying to make a java GUI game version of the game called " jump it" (http://www.crazygames.com/game/jump-it). I am currently on the part of drawing randomized rectangles for my character to jump on. However, I don't know how to continuously draw more rectangles since I'm fairly new to GUI. So my code is below and I hope you guys can help me!
class BtnActPanel extends JPanel implements
ActionListener{
private int x = 0,
x1 = 650,
y2 = (int)(Math.random()*100)+40,
y1 = (int)(Math.random()*100)+450,
x2 = (int)(Math.random()*600)+200;
.
.
.
}
public void actionPerformed(ActionEvent e) {
.
.
.
else if (e.getSource() == b3){
JOptionPane.showMessageDialog(null, "This is an exit button, hope you enjoyed the game! :)", "Exit message",JOptionPane.WARNING_MESSAGE ); //shows exit message
System.exit(0);//exits program
}
else if (e.getSource() == t){
if (index == 0){
index = 1;
c = arrImage[1];
}
else{
index = 0;
c = arrImage[0];
}
x = x-10;
x1 = x1-10;
repaint();
}
}
public void paintComponent(Graphics g){//this method draws and paints images and icons based on the user decisions
super.paintComponent(g);
if(check1 == 0)
g.drawImage(icon.getImage(),0,0,null);
if(check1 == 1){
g.drawImage(b.getImage(),0,0,null);
g.setColor(Color.black);
g.fillRect(x,495, 500, 35);
g.fillRect(x1, y1, x2, y2);
g.drawImage(c.getImage(), 100, 460, null);
}
if(check1 == 2)
g.drawImage(instruct.getImage(),0,0,null);
b1.setBounds(320, 350, 100, 100);
b2.setBounds(420, 350, 100, 100);
b3.setBounds(520, 350, 100, 100);
}
}//end of class
You can set a timer or generate some in a loop.
You can adjust the thresholds as you see fit.
static Random r = new Random();
static int upperX = 100;
static int lowerX = 20;
static int upperY = 100;
static int lowerY = 50;
static int minWidth = 100;
static int maxWidth = 300;
static int minHeight = 50;
static int maxHeight = 200;
public static Rectangle newRect() {
// All ranges inclusive of thresholds
int x = r.nextInt(upperX-lowerX + 1) + lowerX; // from 20 to 100
int y = r.nextInt(upperY-lowerY + 1) + lowerY; // from 50 to 100
int w = r.nextInt(maxWidth-minWidth + 1) + minWidth; // from 100 to 300
int h = r.nextInt(maxHeight - minHeight + 1) + minHeight; // from 50 to 200
return new Rectangle(x,y,w,h);
}
I am currently working on a code to connect ellipses with lines. I have been able to connect each ellipse with the previous. However, i cannot connect the last ellipse and the original (first) ellipse.
I would like to create an array that will
The Ellipses are drawn with the centre being the co-ordinates of where the mouse was clicked.
(Using Processing to code this program)
PS: sorry for bad formatting on the question, this is my first time asking a query.
I have researched on how to use arrays but it is still a bit confusing to me and thus i am using single integers for each point at the moment.
//SET GLOBAL VARIABLES
final int N_PARTITIONS = 10;
int PrevX = -1;
int PrevY = -1;
int count = 0;
int gridx = 0;
int gridy = 0;
int OriginalX = mouseX;
int OriginalY = mouseY;
//CREATING WINDOW SIZE
void setup() {
size(600, 360);
surface.setResizable(true);
}
void draw() {
}
//DRAWING ELLIPSE AND CONNECTING LINES
void mouseClicked() {
count++;
CallEllipse();
if (PrevX != -1) {
line(PrevX, PrevY, mouseX, mouseY);
}
if (count >= 3) {
line(OriginalX, OriginalY, PrevX, PrevY);
}
PrevX = mouseX;
PrevY = mouseY;
}
void CallEllipse() {
ellipse(mouseX, mouseY, N_PARTITIONS, N_PARTITIONS);
}
this is the result of the coding. I am not sure why the line is coming from the top left corner.
try to Add this code in the mouseClicked() method:
void mouseClicked() {
if(count == 0) {
OriginalX= mouseX;
OriginalY=mouseY;
}
count++;
CallEllipse();
if (PrevX != -1) {
line(PrevX, PrevY, mouseX, mouseY);
}
if (count >= 3) {
line(OriginalX, OriginalY, mouseX, mouseY);
}
PrevX = mouseX;
PrevY = mouseY;
}
Enjoy
i have been working on some code and merging two programs I have created but I understand I am missing a lot of information as I have many errors but I can't seem to fix the error. Below I have included the whole code which has been separated into classes. I am producing a version of space invaders.
Main class:
Bullets [] bullets = new Bullets[10];
Player player = new Player();
Boolean keyLftPressed = false, keyRghtPressed = false;
//Enemies[] enemies = new Enemies();
int state;
String gameLevel = "Main menu";
Boolean startTime = false;
void setup() {
for(int i=0; i<bullets.length; i++)
{
// if(i%2==0)
// bullets[i] = new Bullets();
// else
// bullets[i] = new Bullets(i);
}
size(800, 600);
state = 0;
}
void draw() {
background(255);
gameState();
player1.display();
movePlayer1();
handleEnemies();
handleBullets();
gamewon();
}
void gameState() {
if (gameLevel == "Main menu") {
background(0);
fill(255, 255, 255);
rect(270, 270, 280, 50, 20, 20, 20, 20);
//Draws rectangle for play game
fill(0);
textSize(30);
text("Play Game", 330, 305);
fill(255, 0, 0);
textSize(50);
text("Space Invaders", 220, 120);
if (mousePressed && mouseX > 250 && mouseX < 250 + 280 && mouseY > 270 && mouseY < 270 + 50)
{
gameLevel = "Level 1";
}
} else if (gameLevel == "Level 1")
{
background (255, 2555 , 255);
}
}
Bullets Class:
class Bullets {
class Bullet {
float x, y;
float velocity;
Bullet(float x, float y, float velocity) {
this.x = x;
this.y = y;
this.velocity = velocity;
}
void display(){
fill(80);
rect(this.x, this.y, 5,15);
}
void move(){
this.y+=this.velocity;
if (this.y > height || this.y < 0){
bullets.remove(this);
}
}
Class Enemies:
class Enemies {
float x, y;
float velocity;
Enemy(float x, float y) {
this.x = x;
this.y = y;
this.velocity = 3;
}
void display() {
fill(0,255,0);
ellipse(this.x, this.y, 30, 30);
noFill();
}
void move() {
this.x+=this.velocity;
if (this.x > width*.9) {
this.x = width*.9;
this.velocity *= -1;
this.y+=30;
}
if (this.x < width*.1) {
this.velocity*=-1;
this.x = width*.1;
this.y+=30;
}
}
void hitCheck() {
for (int i = 0; i < bullets.size(); i++){
Bullet b = (Bullet) bullets.get(i);
float distBetween = dist(b.x, b.y, this.x, this.y);
if (distBetween < 15 && b.velocity < 0){
score++;
enemies.remove(this);
float x = width*.1 + i%numCol*50;
float y = 60 + int(i/numCol)*60 ;
enemies.add(new Enemy(x, y));
}
}
}
}
Class Player:
class Player {
void movePlayer1() {
if (keyLftPressed) {
player1.x -=10;
}
if (keyRghtPressed) {
player1.x +=10;
}
}
void keyPressed() {
if (keyCode == LEFT) {
keyLftPressed = true;
}
else {
if (keyCode == RIGHT) {
keyRghtPressed = true;
}
else {
if (key == 'f') {
player1.shoot();
}
}
}
}
void keyReleased() {
if (keyCode == LEFT) {
keyLftPressed = false;
}
else {
if (keyCode == RIGHT) {
keyRghtPressed = false;
}
}
}
Class Score:
void gameFinish() {
{
for (int i = 0; i < 3; i++)
{
fill(color(255,0,0));
fill(255, 0, 0);
textAlign(CENTER);
text("Game over", width/2, height/2 - 50);
text(" Final score : "+ score, width/2, height/2 + 50);
}
}
}
}
void gamewon()
{
if (score == 10)
{
background(0);
fill(color(255,0,0));
fill(255, 0, 0);
textAlign(CENTER);
text("Congratulations you won!", width/2, height/5);
text(" Your final score is : "+ score, width/2, height/5 + 30);
text("Do you wish to continue?",width/2, height/2);
text(" If so press Y to Continue or N to exit ", width/2, height/2+30);
noLoop();
}
}
I don't want to be disheartening, but this code is a mess. You've got a ton of errors here, and asking us to go through all of them is asking quite a bit.
That being said, I'll try to get you started in the right direction.
First of all, you're missing closing curly brackets on several of these classes. Proper indenting will help you narrow this down, or you could consider putting each class in its own tab.
Then in your Player class, you use a variable named player1. Where is that variable defined? Do you mean to use the player variable? For that matter, since you're in the Player class already, why are you referring to a variable at all? Shouldn't you just use the x variables in that instance directly?
Which brings us to the next problem: your Player class doesn't actually define an x variable!
Similarly, your Player class calls a shoot() function, which doesn't seem to exist. You have to define that function.
Then let's see here... your Score class uses a score variable that doesn't seem to be declared anywhere.
Also, your bullets variable is an array, but you're calling functions on it that only work on an ArrayList object. Pick one or the other.
You also call a bunch of functions that don't exist: movePlayer1(), handleEnemies(), handleBullets(), and gameWon() for example. Some of these functions are defined inside of classes, so you need to use an instance of that class to get to the functions. Like this:
Example e = new Example();
e.function();
class Example{
void function(){
println("here");
}
}
Then your Enemies class has a constructor of Enemy, which isn't valid. Choose one or the other.
You're not going to like hearing this, but honestly, your best bet is probably to start from scratch. I would guess that you're trying to copy-paste all of this code from different sources without really understanding what the code is doing, which is a horrible idea. That never works, even for experienced programmers.
Instead, try breaking your problem down into smaller pieces. Get a single rectangle on the screen, then make it move around when you press the arrow keys, then add the ability to shoot. Then try adding some enemies, but only after the previous steps work perfectly!
If you get stuck, post an MCVE that shows the small step you're stuck on- not your entire project!
Here's my original question on SO kindly answered. The height is now set at what I think is the correct size. But I can't see the bottom 2/3s of the panel.
I have read, and asked, and mused, and experimented, but I still cannot find an answer. I don't need code, just a little help.
My JFrame class;
public Frame(String title) throws FileNotFoundException {
super(String.format("Title", title));
this.panel = new Panel();
this.panel.drawLinesAndTab();
this.panel.setSize(this.panel.getPreferredSize());
this.panel.validate();
this.scroller = new JScrollPane(this.panel);
//this.scroller.setPreferredSize(new Dimension(this.panel.getPreferredSize()));
this.scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//this.scroller.setSize(new Dimension(this.panel.getPreferredSize()));
this.scroller.getVerticalScrollBar().setUnitIncrement(20);
this.getContentPane().add(this.scroller);
//this.pack();
}
and this is the JPanel class. I know it's huge, and I do have plans to re-write this code, but I'm under time limitations and have to try and get it at least seeing all of the output.
public Panel() throws FileNotFoundException {
this.tab = new ReadTabFile("tabSource.txt");
this.image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
Graphics g = this.image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.image.getWidth(), this.image.getHeight());
setBorder(BorderFactory.createLineBorder(Color.black));
this.setFocusable(true);
}
public void drawLinesAndTab() {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
this.list = tab.readTabCode();
this.a = 20;
this.b = 100;
this.c = 60;
this.x = 40;
this.y = 100;
this.beginBarlineX = 20;
this.beginBarlineY = 100;
this.endBarY = 980;
this.endBarY = 100;
this.title = tab.getTitle();
g.drawString(this.title, 40, 20);
for (int i = 0; i < this.list.size(); i++) {
Bar theBar = (Bar) this.list.get(i);
drawBarline(a, b, a, b + 125);
ArrayList<String> stuff = theBar.getLinesInBar();
for (int j = 0; j < stuff.size(); j++) {
String line = stuff.get(j);
theFlag = line.substring(0, 1);
theNotes = line.substring(1, line.length());
if (newLine = true) {
}
try {
System.out.println(theNotes);
if (c <= (width - 40)) {
newLine = false;
String zero = theFlag;
drawFlag(zero, x + 5, y - 20);
String one = theNotes.substring(0, 1);
g.drawLine(a, b, c, b);
drawLetter(one, x, y);
String two = theNotes.substring(1, 2);
drawLetter(two, x, y += 25);
g.drawLine(a, b += 25, c, b);
String three = theNotes.substring(2, 3);
drawLetter(three, x, y += 25);
g.drawLine(a, b += 25, c, b);
String four = theNotes.substring(3, 4);
drawLetter(four, x, y += 25);
g.drawLine(a, b += 25, c, b);
String five = theNotes.substring(4, 5);
drawLetter(five, x, y += 25);
g.drawLine(a, b += 25, c, b);
String six = theNotes.substring(5, 6);
drawLetter(six, x, y += 25);
g.drawLine(a, b += 25, c, b);
this.repaint();
b -= 125;
y -= 125;
x += 40;
a += 40;
c += 40;
} else {
if (height < (b - 100)) {
height += 205;
}
newLine = true;
a = 20;
x = 20;
b += 225;
c = 60;
y += 225;
beginBarlineX = 20;
beginBarlineY += 100;
endBarX += 100;
endBarY = 100;
this.repaint();
}
} catch (Exception ex) {
System.err.println(ex + " within if drawtab/line for loop");
}
}
}
}
public void drawBarline(int xTop, int yTop, int xBot, int yBot) {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
g.drawLine(xTop, yTop, xBot, yBot);
}
public Point makeBarline(int xTop, int yTop, int xBot, int yBot) {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
g.drawLine(xTop, yTop, xBot, yBot);
return (new Point());
}
public Point drawLetter(String letter, int x, int y) throws FontFormatException, IOException {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
g.setFont(letterFont(letter).deriveFont(20.0f));
g.drawString(letter, x, y);
return (new Point());
}
public Point drawFlag(String letter, int x, int y) throws FontFormatException, IOException {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
g.setFont(flagFont(letter).deriveFont(30.0f));
g.drawString(letter, x, y);
return (new Point());
}
public Font letterFont(String fontString) throws FontFormatException, IOException {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
if (!Character.isDigit(fontString.charAt(0))) {
this.letterFont = Font.createFont(Font.TRUETYPE_FONT, new File("LeRoy.ttf"));
g.getFontMetrics(this.letterFont);
g.setFont(this.letterFont);
return this.letterFont;
} else {
return null;
}
}
public Font flagFont(String fontString) throws FontFormatException, IOException {
Graphics g = this.image.getGraphics();
g.setColor(Color.black);
if (!Character.isDigit(fontString.charAt(0))) {
this.flagFont = Font.createFont(Font.TRUETYPE_FONT, new File("LeroyLuteNotes1.ttf"));
g.getFontMetrics(this.flagFont);
g.setFont(this.flagFont);
return this.flagFont;
} else {
return null;
}
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(this.width, this.height));
}
public BufferedImage getImage() {
return this.image;
}
#Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics g = graphics.create();
g.drawImage(this.image, 0, 0, null);
}
}
I'm not sure what you are attempting to do with that code. It looks like you might be trying to do some custom painting on top of an image. If so then I have the following suggestions:
public Dimension getPreferredSize() {
return (new Dimension(this.width, this.height));
}
This makes no sense, you are saying that the preferred size is equal to the actual size of the component. The preferred size should be the size of the image.
Your custom painting code is completely wrong. All custom painting code should be done from the paintComponent() method. So first you would paint the image as the background of your component. Then you would invoke the other painting methods to paint stuff on top of the image. You would pass the Graphics object from the paintComponent() method to all of these other painting methods, instead of using image.getGraphics().
Start with a simple custom painting example from the Swing tutorial on Custom Painting. Once you learn the basics you customize your code one step at a time. That is first paint the background. Make sure the size is correct and scrolling works. Then move to the next step and add another method to paint something else on top of the image.
I never understand why people write hundreds of lines of code without doing basic testing along the way to make sure the code is working.
I recently took all my code a manually imported it into an eclipse project from BlueJ, I then got use to the settings up "Run Configurations", finally thinking I was home free. Then I ran the code, and I got this error
java.lang.NoSuchMethodError: main
Exception in thread "main"
so I figured I had to add a main method (I never had to do this in BlueJ, why?). So I did that just called the constructor method (in BlueJ I would just create a new object and the JFrame would show). So I did that, same error. After trying different things (such as moving the code in the constructor to a different method etc.). I just put this in for the main method:
public void main(String[] args)
{
System.out.println("Hello, this is main why won't Java find this.");
}
After that I still got the same error, so I then decided to add it to all my classes to make sure it wasn't using another class as the main class. Still same error, so I come to you wondering if any of you have encountered this problem. Also I did search Google and all I found was problems with private classes etc and sense all my classes are public (hey I come from Python :) ). I knew that wasn't the problem. Help Please :)
Picture of my Run Configuration
This is my main method code
WARNING: LONG
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class AppFrame extends JFrame
{
public String status = "Status:";// Status of Applet
public int paint_count = 1;// Number of times applet has been painted
public int[] mousePos = {-1, -1};// Stores Mouse's Last Clicked X and Y Cordinates
public int[] boardPos = {-1, -1};//Stores The Board's X and Y Cordinates
public int[] selectedSquarePos = {-1, -1};
public int[] boardSquare = {-1, -1};//Stores Last Clicked Square
public Color P1_Color = Color.GRAY;
public Color P2_Color = Color.WHITE;
public Color SquareEven = Color.BLACK;
public Color SquareOdd = Color.RED;// pieces move on this one
public int boardHeight = 400;
public int boardWidth = 400;
public boolean pieceSelected = false;
public boolean CheckersPiece = false;
public Board CheckersBoard = new Board();
public Image buffer = null;
public Graphics bg = null;
public void main(String[] args)
{
System.out.println("Hello, this is main why won't Java find this.");
}
public AppFrame()
{
super("JCheckers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900,900);
setVisible(true);
buffer = createImage(getWidth(), getHeight());
boardHeight = getHeight() - 40; // 20 pixel border at top and bottom and 20 pixels for blue bar
boardWidth = getWidth() - 40; // 20 pixel border at left and right
bg = buffer.getGraphics();
addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
handleClick(e);
}
}
);
}
public void handleClick(MouseEvent e)
{
/* Handles tracking of mouse clicks; DOES NOT HANDLE DISPLAY, it just updates the data and calls redraw */
mousePos[0] = e.getX();
mousePos[1] = e.getY();
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
render(g);
}
public void render(Graphics g)
{
bg.clearRect(0,0, getWidth(), getHeight());
//Draw Chess Board and Pieces
renderChessBoard(bg, 20, 20);
// Display Info
System.out.println(status);
System.out.println(String.format("Last Mouse Click # (X:%d Y:%d)", mousePos[0], mousePos[1]) );
System.out.println("Paint #" + paint_count );
System.out.println(String.format("Board Square (x:%s, y:%s) %b", boardSquare[0], boardSquare[1], CheckersPiece) );
System.out.println(CheckersBoard.status );
paint_count += 1;
// Draw Image to Screen
g.drawImage(buffer, 0, 25, null);// so it does not get hidden by the blue close/min/max room
}
public boolean isValidSquare(int col, int row)
{
if (col > -1 & col < 8) {return true;}
return false;
}
public void renderChessBoard(Graphics g, int x, int y)
{
/* Renders board and pieces*/
// sense the row squares are well squares then the
// board will be a square also; so we draw it with whatever
// side is smallest, width or height
boardPos[0] = x;
boardPos[1] = y;
drawBoard(g, x, y, boardWidth, boardHeight);
boardSquare = getBoardSquare(mousePos[0], mousePos[1]);
CheckersPiece = isCheckersPiece(boardSquare[0], boardSquare[1]);
boolean validSquare = isValidSquare(boardSquare[0], boardSquare[1]);
if (validSquare)
{
if (CheckersPiece)
{
selectSquare(g, boardSquare[0], boardSquare[1]);
}
else
{
if (pieceSelected)
{
int selectedCol = selectedSquarePos[0];
int selectedRow = selectedSquarePos[1];
int toCol = boardSquare[0];
int toRow = boardSquare[1];
System.out.println(selectedCol + " " + selectedRow + " " + toCol + " " + toRow);
if (!CheckersBoard.move(selectedSquarePos, boardSquare)) // not a valid move;
{
pieceSelected = false;
}
}
}
}
parseBoard(CheckersBoard.board, g);
}
public void drawBoard(Graphics g, int Bx, int By, int Bw, int Bh)
{
int numberRowsDrawed = 0;
int rH = Bh / 8;
int rW = Bw; // Row width is the same as the Board's width because the board and the row share the same sides
while (numberRowsDrawed < 8)
{
int rY = (numberRowsDrawed * rH) + By;
// Row X is the same as the Board X because the board and the row share the same sides
int rX = Bx;
Color EVEN = SquareEven;
Color ODD = SquareOdd;
// Yes Yes The EVEN Color is now odd and vica versa its because rows only now there row counts and so they start at 0 and don't
// include the rows above
if ((numberRowsDrawed % 2) != 0) {EVEN = SquareOdd; ODD = SquareEven;}
drawRow(g, rX, rY, rW, rH, EVEN, ODD);
numberRowsDrawed +=1;
}
}
public void drawRow(Graphics g, int x, int y, int width, int height, Color EVEN, Color ODD)
{
System.out.println("Board Y: " + y);
int squareW = width / 8;
int squareH = height;
int numberSquaresCreated = 0;
while (numberSquaresCreated < 8)
{
// needs a special case because Java's modulo uses division (so it would give a divide by 0 error) STUPID JAVA!!!!!!
if (numberSquaresCreated == 0)
{
g.setColor(EVEN);
g.fillRect(x, y, squareW, squareH);
}
else
{
if (numberSquaresCreated % 2 == 0){g.setColor(EVEN);}
else {g.setColor(ODD);}
int sX = x + (squareW * numberSquaresCreated);
g.fillRect(sX, y, squareW, squareH);
}
numberSquaresCreated +=1;
}
}
public void drawMan(Graphics g, int boardRow, int boardCol, Color pieceColor)
{
int x = boardPos[0];
int y = boardPos[1];
int pixelPosX = x + ((boardWidth / 8) * boardRow);
int pixelPosY = y + ((boardHeight / 8) * boardCol);
g.setColor(pieceColor);
g.fillOval(pixelPosX + 13, pixelPosY + 13, (boardWidth / 8) - 26, (boardHeight / 8) - 26);
}
public void drawKing(Graphics g, int boardRow, int boardCol, Color pieceColor, Color crownColor)
{
drawMan(g, boardRow, boardCol, pieceColor);
g.setColor(crownColor);
int x = boardPos[0];
int y = boardPos[1];
double DsizeFactor = ( (float) boardHeight / 8.0) / 3.75;
int sizeFactor = (int) DsizeFactor;
int pixelPosX = x + ((boardWidth / 8) - sizeFactor) / 2 + ((boardWidth / 8) * boardRow);
int pixelPosY = y + ((boardHeight / 8) - sizeFactor) / 2 + ((boardHeight / 8) * boardCol);
int[] xPoints = {pixelPosX, pixelPosX, pixelPosX + sizeFactor, pixelPosX + sizeFactor, pixelPosX + ((sizeFactor * 3) / 4), pixelPosX + (sizeFactor / 2), pixelPosX + (sizeFactor / 4) };
int[] yPoints = {pixelPosY, pixelPosY + sizeFactor, pixelPosY + sizeFactor, pixelPosY, pixelPosY + (sizeFactor / 2), pixelPosY, pixelPosY + (sizeFactor / 2)};
g.fillPolygon(xPoints, yPoints, 7);
}
public void selectSquare(Graphics g, int bSX, int bSY)
{
g.setColor(Color.YELLOW);
/*+10 is to offset text (the xy cordinates are the bottom left side of the text NOT top left.*/
pieceSelected = true;
int squareX = boardPos[0] + (boardWidth / 8) * bSX;
int squareY = 10 + boardPos[1] + (boardHeight / 8) * bSY;
selectedSquarePos[0] = bSX;
selectedSquarePos[1] = bSY;
g.drawString("Selected", squareX, squareY);
}
// Data Handling and Retreiving methods
public void parseBoard(String[][] Board, Graphics g)
{
int row = 0;
int col = 0;
for (String[] rowOfPieces : Board)
{
for (String piece : rowOfPieces)
{
if (piece != "X")
{
Color PIECE_COLOR = P1_Color;
if (piece.contains("P2")) {PIECE_COLOR = P2_Color;}
if (piece.contains("C"))
{
drawMan(g, col, row, PIECE_COLOR);
}
if (piece.contains("K"))
{
Color Crown_Color = P2_Color;
if (PIECE_COLOR != P1_Color) {Crown_Color = P1_Color;}
drawKing(g, col, row, PIECE_COLOR, Crown_Color);
}
}
col+=1;
}
row +=1;
col = 0;
}
}
public int[] getBoardSquare(int x, int y)
{
//row or col = boardpos - offset / row height or width
if ((x < boardPos[0]) | (y < boardPos[1]) | (x > (boardPos[0] + boardWidth)) | (y > (boardPos[1] + boardHeight)) )
{
int[] BS = {-1, -1};
return BS;
}
int col = (x - boardPos[0]) / (boardWidth / 8);
int row = (y - boardPos[1]) / (boardHeight / 8);
int[] BS = {col, row};
return BS;
}
public boolean isCheckersPiece(int BoardSquareX, int BoardSquareY)
{
int Px = BoardSquareX;
int Py = BoardSquareY;
if (Px == -1 & Py == -1)
{
return false;
}
String Square = CheckersBoard.board[Py][Px];
return Square != "X";
}
}
You forgot static:
public static void main(String[] args)
But in order to really start your application, you should launch it from that method, not merely have it. Here is how to start it:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AppFrame frame = new AppFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
It's important to note the EXIT_ON_CLOSE - this will make the JVM exit when you press the X button. Otherwise your application will continue running, and you might even not notice.
Make main static.