I am having trouble trying to initialize a variable correctly. Earlier I was getting a Number Format Exception because I was parsing an integer inside of an empty text field. Now I have created an if statement that checks first to see if the field is empty, then parses an integer inside of it. The problem i'm having now is that my event handler can't recognize the variable, because it is inside the if statement. I tried declaring it outside of the if statement but that didn't work either. Any tips to point me in the right direction? Here is my code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList<Integer> deck;
deck = new ArrayList<>();
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
final AtomicReference<String> result = new AtomicReference<>("go.");
Collections.shuffle(deck);
BorderPane pane = new BorderPane();
HBox top = new HBox(10);
Label display = new Label(result.toString());
Button btShuffle = new Button("Shuffle");
btShuffle.setOnAction(
e -> {
Collections.shuffle(deck);
});
top.getChildren().add(display);
top.getChildren().add(btShuffle);
HBox center = new HBox(10);
Card card1 = new Card(deck.get(0));
center.getChildren().add(card1);
Card card2 = new Card(deck.get(1));
center.getChildren().add(card2);
Card card3 = new Card(deck.get(2));
center.getChildren().add(card3);
Card card4 = new Card(deck.get(3));
center.getChildren().add(card4);
HBox bottom = new HBox(10);
Label expression = new Label("Please Enter the expression: ");
TextField tfExpress = new TextField();
LinkedList<Object> expInput = new LinkedList<>();
ArrayList<Character> signs = new ArrayList<>();
signs.add('/');
signs.add('+');
signs.add('(');
signs.add(')');
signs.add('-');
signs.add('^');
signs.add('*');
signs.add('%');
String str = tfExpress.getText();
char tempStor[] = str.toCharArray();
for(char c: tempStor){
expInput.add(c);
}
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
expInput.removeIf(p-> p.equals(signs));
Button btVerify = new Button("Verify");
btVerify.setOnAction(
(ActionEvent e) -> {
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3)){
if(express == 24){
result.set("Correct");
}
else
result.set("Incorrect");
}
else
result.set("The numbers in the expression don't "
+ "match the numbers in the set.");
});
pane.setTop(top);
pane.setCenter(center);
pane.setBottom(bottom);
Scene scene = new Scene(pane);
primaryStage.setTitle("24 card game");
primaryStage.setScene(scene);
primaryStage.show();
}
public class Card extends Pane {
public int cardVal;
Card(int card){
Image cardImage;
cardImage = new Image("card/"+ card +".png");
cardVal = card;
}
public int CardValue(){
int card = 0;
if(cardVal <= 13){
card = cardVal;
}
else if(cardVal > 13 && cardVal <= 26){
card = cardVal - 13;
}
else if(cardVal > 26 && cardVal <= 39){
card = cardVal - 26;
}
else if(cardVal > 39 && cardVal <= 52){
card = cardVal - 39;
}
return card;
}
}
public static void main(String[] args) {
launch(args);
}
}
If str being empty is an acceptable behavior for your code, you need to define a default value for express if that is the case. If the default value were -1, for example, you would do:
int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;
And then later, you should treat the -1 case accordingly.
You need to initialize express like this, so it is effectively final and can be used in the lambda expression.
Instead of
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
try
final int express = (tfExpress.getText() != null && !tfExpress.getText().equals("")) : Integer.parseInt(str) : 0;
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Can someone explain why I'm getting this error and how to solve it? Also try to keep it simple. I'm new to coding. (Also i know the answer to the question exists, but i don't know how to implement it to my code)
It gives NullPointerException error when rows are deleted. Also when the blocks move down, the blocks are still counted as 0 so new blocks go through them. (i guess its only the top row, other rows are working as intended) But the actual error is more important: (but i'd be happy if you help to solve this too)
package application;
import java.util.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.input.*;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Tetris extends Application {
public static final int MOVE_AMOUNT = 25;
public static final int SIZE = 25;
public static int XLIMIT = SIZE * 10;
public static int YLIMIT = SIZE * 24;
public static int[][] GRID = new int[XLIMIT/SIZE][YLIMIT/SIZE];
private static Pane group = new Pane();
private static Shape object;
private static Scene scene = new Scene(group, XLIMIT, YLIMIT);
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) throws Exception {
for(int[] a: GRID){
Arrays.fill(a, 0);
}
for(int i = 0; i <= XLIMIT; i+= SIZE){
Line a = new Line(i, 0, i, YLIMIT);
group.getChildren().add(a);
}
for(int i = 0; i <= YLIMIT; i+= SIZE){
Line a = new Line(0, i, XLIMIT, i);
group.getChildren().add(a);
}
for(int i = 0; i <= YLIMIT; i+= SIZE){
Text a = new Text("" + i);
a.setY(i);
group.getChildren().add(a);
}
for(int i = SIZE; i < XLIMIT; i+= SIZE){
Text a = new Text("" + i);
a.setY(10);
a.setX(i);
group.getChildren().add(a);
}
Shape a = TetrisHolder.createRect();
group.getChildren().addAll(a.a, a.b, a.c, a.d);
moveOnKeyPress(scene, a.a, a.b, a.c, a.d);
object = a;
stage.setScene(scene);
stage.show();
Timer myTimer=new Timer();
TimerTask task =new TimerTask() {
#Override
public void run() {
Platform.runLater(new Runnable(){
public void run(){
CheckDown(object);
}
});
}
};
myTimer.schedule(task,0,300);
}
private void moveOnKeyPress(Scene scene, Rectangle rect, Rectangle rect2, Rectangle rect3, Rectangle rect4) {
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override public void handle(KeyEvent event) {
Shape shape = new Shape(rect, rect2, rect3, rect4);
switch (event.getCode()) {
case RIGHT:
TetrisHolder.CheckRight(shape);
break;
case DOWN:
CheckDown(shape);
break;
case LEFT:
TetrisHolder.CheckLeft(shape);
break;
case UP:
//TetrisHolder.CheckTurn(shape);
break;
}
}
});
}
private void CheckTurn(Shape shape){
}
private void DeleteRows(Pane pane){
ArrayList<Node> rects = new ArrayList<Node>();
ArrayList<Integer> lines = new ArrayList<Integer>();
int full = 0;
for(int i = 0; i < GRID[0].length; i++){
for(int j = 0; j < GRID.length; j++){
if(GRID[j][i] == 1)
full++;
}
if(full == GRID.length)
lines.add(i/*+lines.size()*/);
full = 0;
}
for(Node node: pane.getChildren()) {
if(node instanceof Rectangle) {
rects.add(node);
}
}
if(lines.size() > 0)
do{
for(Node node: rects){
Rectangle a = (Rectangle)node;
if(a.getY() == lines.get(0)*SIZE){
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 0;
pane.getChildren().remove(node);
}
if(a.getY() < lines.get(0)*SIZE){
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 0;
a.setY(a.getY() + SIZE);
GRID[(int)a.getX()/SIZE][(int)a.getY()/SIZE] = 1;
}
}
lines.remove(0);
rects.clear();
for(Node node: pane.getChildren()) {
if(node instanceof Rectangle) {
rects.add(node);
}
}
} while(lines.size() > 0);
}
private void CheckDown(Shape shape){
if((shape.c.getY() == YLIMIT - SIZE) || checkA(shape) || checkB(shape) || checkC(shape) || checkD(shape)){
GRID[(int)shape.a.getX()/SIZE][(int)shape.a.getY()/SIZE] = 1;
GRID[(int)shape.b.getX()/SIZE][(int)shape.b.getY()/SIZE] = 1;
GRID[(int)shape.c.getX()/SIZE][(int)shape.c.getY()/SIZE] = 1;
GRID[(int)shape.d.getX()/SIZE][(int)shape.d.getY()/SIZE] = 1;
DeleteRows(group);
Shape a = TetrisHolder.createRect();
object = a;
group.getChildren().addAll(a.a, a.b, a.c, a.d);
moveOnKeyPress(shape.a.getScene(), a.a, a.b, a.c, a.d);
}
if(shape.c.getY() + MOVE_AMOUNT < YLIMIT){
int checka = GRID[(int)shape.a.getX()/SIZE][((int)shape.a.getY()/SIZE) + 1];
int checkb = GRID[(int)shape.b.getX()/SIZE][((int)shape.b.getY()/SIZE) + 1];
int checkc = GRID[(int)shape.c.getX()/SIZE][((int)shape.c.getY()/SIZE) + 1];
int checkd = GRID[(int)shape.d.getX()/SIZE][((int)shape.d.getY()/SIZE) + 1];
if(checka == 0 && checka == checkb && checkb == checkc && checkc == checkd){
shape.a.setY(shape.a.getY() + MOVE_AMOUNT);
shape.b.setY(shape.b.getY() + MOVE_AMOUNT);
shape.c.setY(shape.c.getY() + MOVE_AMOUNT);
shape.d.setY(shape.d.getY() + MOVE_AMOUNT);
}
}
}
private boolean checkA(Shape shape){
return (GRID[(int)shape.a.getX()/SIZE][((int)shape.a.getY()/SIZE) + 1] == 1);
}
private boolean checkB(Shape shape){
return (GRID[(int)shape.b.getX()/SIZE][((int)shape.b.getY()/SIZE) + 1] == 1);
}
private boolean checkC(Shape shape){
return (GRID[(int)shape.c.getX()/SIZE][((int)shape.c.getY()/SIZE) + 1] == 1);
}
private boolean checkD(Shape shape){
return (GRID[(int)shape.d.getX()/SIZE][((int)shape.d.getY()/SIZE) + 1] == 1);
}
}
The error:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at application.Tetris.moveOnKeyPress(Tetris.java:70)
at application.Tetris.CheckDown(Tetris.java:147)
at application.Tetris.access$1(Tetris.java:137)
at application.Tetris$1$1.run(Tetris.java:60)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Why are you getting the scene from a shape if you still have a reference to a static scene at the top?
I'd say try switching the following out at line 70:
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
to this:
this.scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
You are trying to access a shape which is null.
In your case, if you look at line 70, you are trying to perform scene.setOnKeyPressed, but scene is null.
You are calling in 2 places the moveOnKeyPress method.
Where your problem is calling this method at line 147, where you do shape.a.getScene(). That call to getScene() is null.
Furthermore, if you look where you call CheckDown, you have them in 2 places, but your problematic call is at line 60.
Not sure what you do at line 48 (Shape a = TetrisHolder.createRect();), but I suspect there might be something wrong with setting up the scene
What I did here is translate your stacktrace:
at application.Tetris.moveOnKeyPress(Tetris.java:70)
at application.Tetris.CheckDown(Tetris.java:147)
at application.Tetris.access$1(Tetris.java:137)
at application.Tetris$1$1.run(Tetris.java:60)
I am trying to make an app that alike vocabulary card.
I have an Answer array(array size = 4).
I am creating random an english word then I am adding true value of english word in answer array and I am removing true value of english word in turkish array in order to not use again in random.I am doing same things to other answer array include wrong value.
Problem is that array size is going to 0.for example my total array 20 .when I remove true value,array size is going to 19-18-17... per click then program close.
Here is my code:
package de.murattekinlive.pwords;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WordsActivity extends AppCompatActivity {
TextView textView;
TextView deneme;
DataBase dataBase;
Button btn_r1,btn_r2,btn_r3,btn_r4;
String [] TR_WORDS;
String [] EN_WORDS;
String [] Answer;
int control_id = 0;
int random ;
Random control;
Random rnd;
int tr,en;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words);
textView = (TextView) findViewById(R.id.textView);
deneme = (TextView) findViewById(R.id.textView3);
dataBase = new DataBase(getApplicationContext());
rnd= new Random();
btn_r1 = (Button)findViewById(R.id.button_random1);
btn_r1.setOnClickListener(new myClickListener());
btn_r2 = (Button)findViewById(R.id.button_random2);
btn_r2.setOnClickListener(new myClickListener());
btn_r3 = (Button)findViewById(R.id.button_random3);
btn_r3.setOnClickListener(new myClickListener());
btn_r4 = (Button)findViewById(R.id.button_random4);
btn_r4.setOnClickListener(new myClickListener());
ArrayList<Words> enWordlist = (ArrayList<Words>) dataBase.allEnWords();
ArrayList<Words> trWordlist =(ArrayList<Words>) dataBase.allTrWords();
TR_WORDS = new String[trWordlist.size()];
EN_WORDS = new String[enWordlist.size()];
for(int i=0;i<enWordlist.size();i++){
EN_WORDS[i] =enWordlist.get(i).getWORD().toString();
TR_WORDS[i] =trWordlist.get(i).getTR1().toString();
}
tr = new Random().nextInt(TR_WORDS.length);
/*btn_r1.setText(TR_WORDS[en]);
btn_r2.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r3.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r4.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);*/
ReStart();
}
private class myClickListener implements View.OnClickListener{
public void onClick(View v){
switch ( v.getId() ) {
case R.id.button_random1:
break;
case R.id.button_random2:
break;
case R.id.button_random3:
break;
case R.id.button_random4:
break;
default:
break;
}
WordsActivity.this.ReStart();
}
}
public void ReStart(){
Answer = new String[4];
control = new Random();
control_id = control.nextInt(4);
en = new Random().nextInt(EN_WORDS.length);
final List<String> newTRList = new ArrayList<>();
textView.setText(EN_WORDS[en]);
final int sayi1,sayi2;
sayi1 = TR_WORDS.length;
Collections.addAll(newTRList,TR_WORDS);
// I added true turkish word in answer array
for(int i=0;i<TR_WORDS.length;i++){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
TR_WORDS = newTRList.toArray(new String[newTRList.size()]);
//I added another values in answer array and I want to remove values that is used because
//I dont want to see same value in answer array.
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
sayi2 =TR_WORDS.length;
deneme.setText(sayi1+"/"+sayi2);
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
for(int j=0;j<=3;j++){
if(j==0){
btn_r1.setText(Answer[j].toString());
}
else if(j==1){
btn_r2.setText(Answer[j].toString());
}
else if(j==2){
btn_r3.setText(Answer[j].toString());
}
else if(j==3){
btn_r4.setText(Answer[j].toString());
}
}
}
}
Change your for loop to:
for(int i=TR_WORDS.length; i >=0 ;i--){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
And all the other ones that include a remove in a similar a fashion.
My program won't go inside of this block of code
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3))
{
if(express == 24){
display.setText("Correct");
}
else
display.setText("Incorrect");
}
I think it is because I am trying to get the card value of card1 when the cards that are appearing are just random cards out of my deck. What could I use to evaluate the new cards that appear? Here is my full code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.image.ImageView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList<Integer> deck;
deck = new ArrayList<>();
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
final AtomicReference<String> result = new AtomicReference<>("go.");
Collections.shuffle(deck);
BorderPane pane = new BorderPane();
HBox top = new HBox(10);
Label display = new Label(result.toString());
Button btShuffle = new Button("Shuffle");
top.getChildren().add(display);
top.getChildren().add(btShuffle);
HBox center = new HBox(10);
Card card1 = new Card(deck.get(0));
center.getChildren().add(card1);
Card card2 = new Card(deck.get(1));
center.getChildren().add(card2);
Card card3 = new Card(deck.get(3));
center.getChildren().add(card3);
Card card4 = new Card(deck.get(4));
center.getChildren().add(card4);
btShuffle.setOnAction(
e -> {
Collections.shuffle(deck);
center.getChildren().clear();
center.getChildren().add(new Card(deck.get(0)));
center.getChildren().add(new Card(deck.get(1)));
center.getChildren().add(new Card(deck.get(2)));
center.getChildren().add(new Card(deck.get(3)));
});
HBox bottom = new HBox(10);
Label expression = new Label("Please Enter the expression: ");
TextField tfExpress = new TextField();
ArrayList<Character> signs = new ArrayList<>();
signs.add('/');
signs.add('+');
signs.add('(');
signs.add(')');
signs.add('-');
signs.add('^');
signs.add('*');
signs.add('%');
String str = tfExpress.getText();
int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;
// expInput.removeIf(p-> p.equals(signs));
Button btVerify = new Button("Verify");
bottom.getChildren().add(expression);
bottom.getChildren().add(tfExpress);
bottom.getChildren().add(btVerify);
btVerify.setOnAction(
(ActionEvent e) ->
{
LinkedList<Character> expInput = new LinkedList<Character>();
for(char c: tfExpress.getText().toCharArray()){
expInput.add(c);
}
expInput.removeIf(p-> p.equals(signs));
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3))
{
if(express == 24){
display.setText("Correct");
}
else
display.setText("Incorrect");
}
else
display.setText("The numbers in the expression don't "
+ "match the numbers in the set.");
});
pane.setTop(top);
pane.setCenter(center);
pane.setBottom(bottom);
Scene scene = new Scene(pane);
primaryStage.setTitle("24 card game");
primaryStage.setScene(scene);
primaryStage.show();
}
public class Card extends Pane {
public int cardVal;
Card(int card){
Image cardImage;
cardImage = new Image("card/"+ card +".png");
getChildren().add(new ImageView(cardImage));
cardVal = card;
}
public int CardValue(){
int card = 0;
if(cardVal <= 13){
card = cardVal;
}
else if(cardVal > 13 && cardVal <= 26){
card = cardVal - 13;
}
else if(cardVal > 26 && cardVal <= 39){
card = cardVal - 26;
}
else if(cardVal > 39 && cardVal <= 52){
card = cardVal - 39;
}
return card;
}
}
public static void main(String[] args) {
launch(args);
}
}
You are comparing the character value of a number with an integer value. Those don't match. To make this visually clear:
String numbers = "0123456789";
for(char c: numbers.toCharArray()){
System.out.println( c);
}
produces
0 1 2 3 4 5 6 7 8 9
But if you cast the character value to an integer like you do in your program, you'll get this
48 49 50 51 52 53 54 55 56 57
Which are the ascii values of your characters.
In other words: For the character "1" and card value 1 you are comparing if 1 == 49.
Solution: You need to parse the characters instead of casting them to int, e. g. using
Character.getNumericValue(...)
As a general note: The easiest way to find out what's wrong with your code is to use a debugger. Alternatively a simple logging output would show you what's wrong.
Edit: fyi, you have a bug:
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
will result in the last card being lost.
I started with a class that has all the methods and constructors which are doing all the work for the bingo game. Then had a "tester class" which would print out and update the bingo card through the use of System.out.print. Now I need to add some graphic for the bingo game. I am supposed to use my first to classes to support a new class to draw the card every time there is an update.
I was able to do the first iteration of the bingo card graphics with a separate code from my original 2:
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Ellipse2D;
public class BingoComponent extends JComponent {
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
Rectangle box = new Rectangle(28,105,80,80);
for(int j = 0;j<5;j++){
g2.draw(box);
for(int i = 0;i<4;i++){
box.translate(80,0);
g2.draw(box);
}
box.translate(-320,80);
}
g2.setPaint(Color.BLUE);
g2.setFont(new Font("Arial", Font.BOLD,44));
g2.drawString("B",50,100);
g2.drawString("I",140,100);
g2.drawString("N",215,100);
g2.drawString("G",290,100);
g2.drawString("O",370,100);
g2.setPaint(Color.RED);
Ellipse2D.Double ellipse = new Ellipse2D.Double(198,275,60,60);
g2.draw(ellipse);
g2.fill(ellipse);
Bingo_Card test_card = new Bingo_Card();
g2.setPaint(Color.BLACK);
g2.setFont(new Font("Times", Font.PLAIN,24));
int x_location = 60;
int y_location = 150;
int number_value;
for(int j = 0;j<5;j++){
number_value = test_card.get_number(j);
g2.drawString(""+number_value,x_location,y_location);
x_location += 80;
}
x_location = 60;
y_location += 80;
for(int j = 5;j<10;j++){
number_value = test_card.get_number(j);
g2.drawString(""+number_value,x_location,y_location);
x_location += 80;
}
x_location = 60;
y_location += 80;
for(int j = 10;j<15;j++){
number_value = test_card.get_number(j);
if(number_value!=0){
g2.drawString(""+number_value,x_location,y_location);
}
x_location += 80;
}
x_location = 60;
y_location += 80;
for(int j = 15;j<20;j++){
number_value = test_card.get_number(j);
g2.drawString(""+number_value,x_location,y_location);
x_location += 80;
}
x_location = 60;
y_location += 80;
for(int j = 20;j<25;j++){
number_value = test_card.get_number(j);
g2.drawString(""+number_value,x_location,y_location);
x_location += 80;
}
}
}
which I used with this code:
public class makecard {
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(800,800);
frame.setTitle("BINGO Card");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BingoComponent component = new BingoComponent();
frame.add(component);
frame.setVisible(true);
}
}
but what i dont understand is how to implement this into my original two codes.
Which are:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Ellipse2D;
public class Bingo_Card {
private ArrayList<Integer> bingo_card;
public boolean bingo = false;
public Bingo_Card(){
/*ArrayList<Integer>*/ bingo_card = new ArrayList<>();
ArrayList<Integer> columnBlist = new ArrayList<>();
for(int i = 1;i<=15;i++){
columnBlist.add(i);
}
Collections.shuffle(columnBlist);
ArrayList<Integer> columnB = new ArrayList<>();
for(int j = 0;j<5;j++){
columnB.add(columnBlist.get(j));
}
ArrayList<Integer> columnIlist = new ArrayList<>();
for(int i = 16;i<=30;i++){
columnIlist.add(i);
}
Collections.shuffle(columnIlist);
ArrayList<Integer> columnI = new ArrayList<>();
for(int j = 0;j<5;j++){
columnI.add(columnIlist.get(j));
}
List<Integer> columnNlist = new ArrayList<>();
for(int i = 31;i<=45;i++){
columnNlist.add(i);
}
Collections.shuffle(columnNlist);
ArrayList<Integer> columnN = new ArrayList<>();
for(int j = 0;j<4;j++){
columnN.add(columnNlist.get(j));
}
columnN.add(2,0);
List<Integer> columnGlist = new ArrayList<>();
for(int i = 46;i<=60;i++){
columnGlist.add(i);
}
Collections.shuffle(columnGlist);
ArrayList<Integer> columnG = new ArrayList<>();
for(int j = 0;j<5;j++){
columnG.add(columnGlist.get(j));
}
List<Integer> columnOlist = new ArrayList<>();
for(int i = 61;i<=75;i++){
columnOlist.add(i);
}
Collections.shuffle(columnOlist);
ArrayList<Integer> columnO = new ArrayList<>();
for(int j = 0;j<5;j++){
columnO.add(columnOlist.get(j));
}
for(int x=0;x<5;x++){
bingo_card.add(columnB.get(x));
bingo_card.add(columnI.get(x));
bingo_card.add(columnN.get(x));
bingo_card.add(columnG.get(x));
bingo_card.add(columnO.get(x));
}
}
public int get_number(int index){
int number = bingo_card.get(index);
return(number);
}
public void print_card(){
System.out.println(" B I N G O ");
System.out.println("----------------");
for(int a = 0;a<5;a++){
if(bingo_card.get(a)<10){
System.out.print("| "+bingo_card.get(a));
}
else{
System.out.print("| "+bingo_card.get(a));
}
}
System.out.println();
System.out.println("----------------");
for(int b = 5;b<10;b++){
if(bingo_card.get(b)<10){
System.out.print("| "+bingo_card.get(b));
}
else{
System.out.print("| "+bingo_card.get(b));
}
}
System.out.println();
System.out.println("----------------");
for(int c = 10;c<15;c++){
if(bingo_card.get(c)<10){
System.out.print("| "+bingo_card.get(c));
}
else{
System.out.print("| "+bingo_card.get(c));
}
}
System.out.println();
System.out.println("----------------");
for(int d = 15;d<20;d++){
if(bingo_card.get(d)<10){
System.out.print("| "+bingo_card.get(d));
}
else{
System.out.print("| "+bingo_card.get(d));
}
}
System.out.println();
System.out.println("----------------");
for(int e = 20;e<25;e++){
if(bingo_card.get(e)<10){
System.out.print("| "+bingo_card.get(e));
}
else{
System.out.print("| "+bingo_card.get(e));
}
}
System.out.println();
System.out.println("----------------");
}
public void check_match(int call_number){
for(int i = 0; i<(bingo_card.size());i++){
if(call_number == bingo_card.get(i)){
bingo_card.set(i,0);
}
}
}
public boolean check_bingo(){
if(bingo_card.get(0)==0&bingo_card.get(1)==0&bingo_card.get(2)==0&bingo_card.get(3)==0&bingo_card.get(4)==0){
bingo = true;
}
else if(bingo_card.get(5)==0&bingo_card.get(6)==0&bingo_card.get(7)==0&bingo_card.get(8)==0&bingo_card.get(9)==0){
bingo = true;
}
else if(bingo_card.get(10)==0&bingo_card.get(11)==0&bingo_card.get(12)==0&bingo_card.get(13)==0&bingo_card.get(14)==0){
bingo = true;
}
else if(bingo_card.get(15)==0&bingo_card.get(16)==0&bingo_card.get(17)==0&bingo_card.get(18)==0&bingo_card.get(19)==0){
bingo = true;
}
else if(bingo_card.get(20)==0&bingo_card.get(21)==0&bingo_card.get(22)==0&bingo_card.get(23)==0&bingo_card.get(24)==0){
bingo = true;
}
else if(bingo_card.get(0)==0&bingo_card.get(5)==0&bingo_card.get(10)==0&bingo_card.get(15)==0&bingo_card.get(20)==0){
bingo = true;
}
else if(bingo_card.get(1)==0&bingo_card.get(6)==0&bingo_card.get(11)==0&bingo_card.get(16)==0&bingo_card.get(21)==0){
bingo = true;
}
else if(bingo_card.get(2)==0&bingo_card.get(7)==0&bingo_card.get(12)==0&bingo_card.get(17)==0&bingo_card.get(22)==0){
bingo = true;
}
else if(bingo_card.get(3)==0&bingo_card.get(8)==0&bingo_card.get(13)==0&bingo_card.get(18)==0&bingo_card.get(23)==0){
bingo = true;
}
else if(bingo_card.get(4)==0&bingo_card.get(9)==0&bingo_card.get(14)==0&bingo_card.get(19)==0&bingo_card.get(24)==0){
bingo = true;
}
else if(bingo_card.get(0)==0&bingo_card.get(6)==0&bingo_card.get(12)==0&bingo_card.get(18)==0&bingo_card.get(24)==0){
bingo = true;
}
else if(bingo_card.get(4)==0&bingo_card.get(8)==0&bingo_card.get(12)==0&bingo_card.get(16)==0&bingo_card.get(20)==0){
bingo = true;
}
else{
bingo = false;
}
return(bingo);
}
and the tester:
public class BINGOFINAL {
public static void main(String args[]){
Bingo_Card test_card = new Bingo_Card();
test_card.print_card();
while(test_card.check_bingo() == false){
System.out.println("Please input the called out number: ");
Scanner input = new Scanner(System.in);
int call_out = input.nextInt();
test_card.check_match(call_out);
test_card.check_bingo();
test_card.print_card();
}
System.out.println("BINGO!");
}
}
i need to implement the BingoComponent into the original two and have the card update each time.
The basic idea remains the same.
You need some kind of model which is maintaining the state of the bingo card, you need some kind of view that displays this model and some kind of control/manager which managers the updates to the model...
In you BingoComponent's paintComponent method, you do this ... Bingo_Card test_card = new Bingo_Card();...
I would say this is a bad idea, as you are restting the state of the card/model each time the component is painted, this isn't what you want. Instead, you want to maintain a single reference to the card, which you then use the paintComponent to render...
Instead, I'd be tempted to do something like this instead...
public class BingoComponent extends JComponent {
private Bingo_Card test_card;
public BingoComponent(Bingo_Card card) {
test_card = card;
}
/*...*/
}
This means that that instance doesn't change, but each time we change it's state, we can re-render it.
The next part will come down to how you want to implement it. If it was me, I would add ChangeListener support to the Bingo_Card, so that the UI could monitor for changes to the card and update itself accordingly, but this might be a little out of your reach just now.
You are going to need some way for the user enter a value into your UI. For this you could use a JTextField. You can either attach an ActionListener directly to the field, so that each time the user presses Enter you will receive notification about it and/or add a JButton, which the user could click (with an attached ActionListener so you know when the user clicks the button).
At this point, you need to take the value and update the model, just like you have in your BINGOFINAL class, but instead, you would to update the UI...
For example...
public void actionPerformed(ActionEvent evt) {
try {
// inputField is a JTextField
// testCard is an instance of Bingo_Card which you
// need to create. It is also the same instance
// you passed to your BingoComponent
int callOut = Integer.parseInt(inputField.getText());
test_card.check_match(call_out);
test_card.check_bingo();
test_card.print_card();
// bingoComponent is an instance of BingoComponent
// which is begin displayed on the screen...
bingoComponent.repaint();
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(this, inputField.getText() +
" is not a valid number", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Now, personally, I'd prefer it if the model provided some kind of notification about changes to it's internal state, but lets try and keep it simpler for the time begin...
Check out Creating a GUI with Swing for more details
hi I am pretty new to java. I need to make a game name Ratsuk witch is pretty much like chess but it only has the knight. So when the knight no longer has space to move the player loses.
I did a array of buttons for this
import java.awt.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tablero {
private JButton[][] mesa;
public Tablero() {
mesa = new JButton[8][8];
}
public void cuadriculado(JFrame ventana) {
JPanel panel = new JPanel(new GridLayout(8, 8, 4, 4));
for (int i = 0; i < mesa.length; i++) {
for (int j = 0; j < mesa[0].length; j++) {
mesa[i][j] = new JButton();
mesa[i][j].setPreferredSize(new Dimension(40, 40));
panel.add(mesa[i][j]);
}
}
for (int r = 0; r < mesa.length; r++) {
for (int t = 0; t < mesa[0].length; t++) {
if (r % 2 == 0 || r == 0) {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.BLACK);
} else {
mesa[r][t].setBackground(Color.WHITE);
}
} else {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.WHITE);
} else {
mesa[r][t].setBackground(Color.BLACK);
}
}
}
}
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton(image);
}
}
The file compiles but the image I am trying to set in the button mesa[0][0] does not appear. How can i fix this?
You should not create new JButton for mesa[0][0] again. But should set the icon for that existing JButton object.
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
Try this:
try {
Icon image = ImageIO.read(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton();
mesa[0][0].setIcon(new ImageIcon(image ));
} catch (IOException ex) {
}
You are creating new JButton object instead of adding the image to the existing JButton object, so the problem exists.
Setting mesa[0][0]=new JButton(image) will not make already added JButton object to the JFrame to be replaced. You should refresh the fundamentals of Java once.
Use JButton#setIcon(Icon img) method to add image to the already existing JButton object.
`mesa[0][0].setIcon(image);`
And also since, you are adding the image after setting the frame visible, you may have to refresh your frame by calling JFrame#repaint() or so...
Or change your code like this instead:
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);