unable to check if button is pressed - java

I am trying to check if a jbutton is pressed, but idk how to do it. This is how i am trying it right now.
private void checker() {
int first=0;
int second=0;
for (int i = 0; i < buttonList.size(); i++) {
if(buttonList.get(i).getModel().isPressed()){
first++;
}
if(buttonList.get(i).getModel().isPressed()){
second++;
}
}
if((first==2)||(second==2)){
for(int i=0;i<buttonList.size();i++){
if(buttonList.get(i).getModel().isPressed()){
}else{
buttonList.get(i).setEnabled(false);
}
}
}
}

Related

Lambda error in code

public static void buttonAdd(boolean[][] coord) {
for (int col = 0; col < SIZE; col++) {
for (int row = 0; row < SIZE; row++) {
Button square = new Button(coord[col][row]);
square.addActionListener((ActionEvent e) -> {
if (bombOrNot) { //if bomb is true
JOptionPane lose = new JOptionPane();
lose.setMessage("You Lose");
frame.add(lose);
System.exit(0);
} else { //if bomb is false
frame.remove(square);
}
frame.add(square);
}
}
}
This code is not compiling, it seems like there is something wrong with the lambda. It says that the closing bracket for the lambda is expected to be a ")".
indenting the way the compiler sees the indentation of your code and commenting where the error happens (obviously the compiler does not see your code in that way since it get converted to a stream of tokens - without any indentation)
// wrong code, just re-indented to clarify
public static void buttonAdd(boolean[][] coord) {
for (int col = 0; col < SIZE; col++) {
for (int row = 0; row < SIZE; row++) {
Button square = new Button(coord[col][row]);
square.addActionListener(
(ActionEvent e) -> {
if (bombOrNot) { //if bomb is true
JOptionPane lose = new JOptionPane();
lose.setMessage("You Lose");
frame.add(lose);
System.exit(0);
} else { //if bomb is false
frame.remove(square);
}
frame.add(square);
}
} // missing ) to close addActionListener(
}
since you probably don't want to add square inside the lambda, you should close it '}' and close the addActionListener with ');` before that line.
...
} else { //if bomb is false
frame.remove(square);
}
} ); // this line is somehow missing in your code
frame.add(square);
...
The Lambda is passed in a call to the method addActionListener((ActionEvent e) -> which has only one argument
meaning that after the Lambda you need ); So...
public static void buttonAdd(boolean[][] coord) {
for (int col = 0; col < SIZE; col++) {
for (int row = 0; row < SIZE; row++) {
Button square = new Button(coord[col][row]);
square.addActionListener((ActionEvent e) -> {
if (bombOrNot) { //if bomb is true
JOptionPane lose = new JOptionPane();
lose.setMessage("You Lose");
frame.add(lose);
System.exit(0);
} else { //if bomb is false
frame.remove(square);
}
}); // <<<<<<<<< here Note: added } in edit
frame.add(square);
}
}
}

Change the background of a panel multiple times in the same method

Hi i'm trying to change the background of a panel to create something similar to the Simon color games.
Here's what I have for code. The problem I seem to be finding is that the only time the background physically changes only at the end of the button being pressed. I have tried using Repaint(); and it has had no effect.
private void ClickRandomColorActionPerformed(java.awt.event.ActionEvent evt) {
Random gen = new Random();
for(int i = 0; i < 5; i++){
int CaseNum = 0;
CaseNum = gen.nextInt(3) +1;
ChangeBackground(CaseNum);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(Testerino.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void ChangeBackground(int i){
System.out.println(i);
if(i == 1){
RandColor.setBackground(blue);
}
else if (i == 2){
RandColor.setBackground(black);
}
else if(i == 3){
RandColor.setBackground(magenta);
}
}

Memory game does not call compare function correctly

I have coded a simple memory game. Card values are added to two arrays and after that, a compare function is called. But there is a problem with the logic of the compare function.
The specific problem seems related to the fact that the compare function is called on the third button click. So on first click it adds first value to first array , on second click second value to second array. But I must click for yet a third time to call the compare function to compare the match of two arrays.
The main problem is that after all cards are inverted (10 matches in 5x4 memory game), it does not show the result.
I have uploaded full code here : http://uloz.to/xcsJkYUK/memory-game-rar .
public class PEXESO5x4 extends JFrame implements ActionListener {
private JButton[] aHracieTlactika = new JButton[20];
private ArrayList<Integer> aHodnoty = new ArrayList<Integer>();
private int aPocitadlo = 1;
private int[] aTlacitkoIden = new int[2];
private int[] aHodnotaTlac = new int[2];
private JButton aTlacitkoExit;
private JButton aTlacitkoReplay;
private JButton[] aHracieTlacitko = new JButton[20];
private int aPocetTahov = 0;
public void vkladanieHodnot() {
for (int i = 0; i < 2; i++) {
for (int j = 1; j < (this.aHracieTlactika.length / 2) + 1; j++) {
this.aHodnoty.add(j);
}
}
Collections.shuffle(this.aHodnoty);
}
public boolean zhoda() {
if (this.aHodnotaTlac[0] == this.aHodnotaTlac[1]) {
return true;
}
return false;
}
public void zapisCislaDoSuboru() {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Semestralka.txt", true)))) {
out.println("haha");
//more code
out.println("hahahahha");
//more code
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
public void actionPerformed(ActionEvent e) {
int match = 0;
if (this.aTlacitkoExit == e.getSource()) {
System.exit(0);
}
if (this.aTlacitkoReplay == e.getSource()) {
}
for (int i = 0; i < this.aHracieTlactika.length; i++) {
if (this.aHracieTlactika[i] == e.getSource()) {
this.aHracieTlactika[i].setText("" + this.aHodnoty.get(i));
this.aHracieTlactika[i].setEnabled(false);
this.aPocitadlo++;
this.aPocetTahov += 1;
if (this.aPocitadlo == 3) {
if (this.zhoda()) {
match+=1;
if (match==10)
{
System.out.println("You win");
}
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(false);
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(false);
} else {
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[0]].setText("");
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[1]].setText("");
}
this.aPocitadlo = 1;
}
if (this.aPocitadlo == 1) {
this.aTlacitkoIden[0] = i;
this.aHodnotaTlac[0] = this.aHodnoty.get(i);
}
if (this.aPocitadlo == 2) {
this.aTlacitkoIden[1] = i;
this.aHodnotaTlac[1] = this.aHodnoty.get(i);
}
}
}
}
}

Java - referencing variables from inner class must be final / effectively final loop

I am trying to develop a GUI for a Chess / Checkers game. When attempting to add ActionListeners to the buttons, Netbeans seems to give me a whole bunch of errors with suggestions that doesn't seem to solve the problem.
Here is the part of the code in question:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
squares[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!pressed) {
pressed = true;
fromR = i;
}
throw new UnsupportedOperationException("Not supported yet.");
}
});
}
}
squares[][] is the array all the buttons are stored in; the error occurs on the line fromR = i;
Is there a better way to add ActionListeners into buttons stored in arrays altogether?
The problem is that you are referring to i inside the action listener and its continuously changing.
One option is to copy i to a new int like iValue here:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
final int iValue = i;
squares[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!pressed) {
pressed = true;
fromR = iValue;
}
throw new UnsupportedOperationException("Not supported yet.");
}
});
}
}
This is clumsy though.
A cleaner alternative is to extract a method:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
addActionListenerTo(squares[i][j], i);
}
}
Here is that method:
private void addActionListenerTo(WhateverThisIs square, int i) {
square.addActionListener(e -> {
if (!pressed) {
pressed = true;
fromR = i;
}
throw new UnsupportedOperationException("Not supported yet.");
});
}
Another alternative would be to have all the squares know their rank and file:
final class Square {
final int rank;
final int file:
Square(int rank, int file) {
this.rank = rank;
this.file = file;
}
}
Put those in a Collection and then you could do this:
squares.stream().forEach(square -> {
square.addActionListener(e -> {
if (!pressed) {
pressed = true;
fromR = square.rank;
}
throw new UnsupportedOperationException("Not supported yet.");
});
});

ArrayIndexOutOfBounds Exception in TicTacToe game

I'm getting an error that I don't realy understand why. It is a tictactoe game(n x n)
here is the table class
public class Table {
private int columns;
private int rows;
private int wincells;
private PieceType[][] table;
public Table() {
}
public Table(int rows, int columns, int wins) {
this.columns = columns;
this.rows = rows;
this.wincells = wins;
table = new PieceType[rows][columns];
fillEmpty();
}
public void fillEmpty() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
table[i][j] = PieceType.None;
}
}
}
public PieceType getElement(int i, int j) {
return table[i][j];
}
its the getElement() method giving the error after i call the function with
game.move(e.x, e.y);
public void widgetSelected(SelectionEvent e) {
Button button = (Button) e.getSource();
MoveResult moveResult = game.move(e.x, e.y);
if (game.getCurrentPlayer().getPieceType() == PieceType.Cross)
button.setText("x");
else
button.setText("0");
switch (moveResult) {
case ValidMove: {
buttonTable[gridData.horizontalIndent][gridData.verticalIndent]
.setText("X");
game.changePlayer();
}
case WinMatch:
disableButtons();
case Draw:
disableButtons();
}
this is where the x and Y get the value
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j) {
gridData.heightHint = 45;
gridData.widthHint = 45;
Button button = new Button(buttonpanel, SWT.PUSH);
button.setLayoutData(gridData);
button.setData(new Cell(i,j));
buttonTable[i][j] = button;
buttonTable[i][j]
.addSelectionListener(new buttSelectionListener());
any ideas on what the problem can be? is it from the game.move(e.x, e.y)? Am I not calling it properly?
StackTrace?:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at backview.Table.getElement(Table.java:42)
at backview.Game.move(Game.java:56)
at frontview.MainGui$buttSelectionListener.widgetSelected(MainGui.java:159)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at frontview.MainGui.<init>(MainGui.java:55)
at main.Main.main(Main.java:18)
here is the method calling
if(table.getElement(x, y) != PieceType.None) return MoveResult.InvalidMove;
You probably want to get the Cell from the Button data and use the i,j coordinates to call getElement().
Note: A couple of comments on your Table class. The default constructor doesn't make sense if you already know the initial size of the table. If that is the case, make columns, rows and wincells final so they cannot be modified during the game. Also, check that the coordinates provided in getElement() are within the array bounds:
public PieceType getElement(int i, int j) {
if ((i < 0) || (i >= rows) ||
(j < 0) || (j >= columns)) {
return null;
}
return table[i][j];
}
The e.x and e.y of the SelectionEvent e are the coordinate of the click of the mouse, and not the grid. You should get the Cell from the Button data, and then use it for your game move.
You can fix your widgetSelected method like that:
Cell c = (Cell) button.getData();
// Then use i and j of the cell for the game move
game.move(c.i, c.j); // or something similar
import java.util.Scanner;
public class TicTacToe_Game {
public static void main(String[] args) {
Scanner Myinput = new Scanner(System.in);
char[][] board = new char[3][3];
boolean Gameover;
Gameover = CalculateWinner(board);
while(!Gameover){
displayBoard(board);
System.out.println("Enter row and column for player X");
int rowX, columnX;
rowX=Myinput.nextInt();
columnX= Myinput.nextInt();
boolean successX = setMove(rowX , columnX ,board,'X');
while(!successX){
System.out.println("INVALID MOVE FOR PLAYER X");
System.out.println("Re-Enter row and column for player X");
rowX=Myinput.nextInt();
columnX= Myinput.nextInt();
successX = setMove(rowX , columnX ,board,'X');
}
Gameover= CalculateWinner(board);
displayBoard(board);
System.out.println();
System.out.println("Enter row and column for player O");
int rowO, columnO;
rowO=Myinput.nextInt();
columnO= Myinput.nextInt();
boolean successO= setMove(rowO , columnO ,board,'O');
while(!successO){
System.out.println("invalid Move");
System.out.println("Re-Enter row and column for player O");
rowO=Myinput.nextInt();
columnO= Myinput.nextInt();
successO = setMove(rowO , columnO ,board,'0');
}
Gameover=CalculateWinner(board);
}
}
public static boolean setMove(int row, int column,char[][] board,char player){
if(board[row][column]== 'X' || board[row][column]== 'O' ){
return false;
}
else if (player =='X'){
board[row][column] = 'X';
return true;
}
else{
board[row][column] = 'O';
return true;
}
}
public static void displayBoard(char[][]board){
System.out.println("-------------------");
System.out.println("|"+board[0][0]+"|"+board[0][1]+"|"+board[0][2]+"|");
System.out.println("-------------------");
System.out.println("|"+board[1][0]+"|"+board[1][1]+"|"+board[1][2]+"|");
System.out.println("-------------------");
System.out.println("|"+board[2][0]+"|"+board[2][1]+"|"+board[2][2]+"|");
System.out.println("-------------------");
}
public static boolean CalculateWinner(char[][] board){
boolean filled =false;
for(int column=0; column<=2; column++){
for(int row =0; row<=2; row++){
if (board[column][row]!='X'&& board[column][row]!='O'){
filled = false;
}
else
{ filled = true;
}
}
}
if (filled){
return true;
}else {
return false;
}
}
}

Categories