Java Gett variable from within a loop in another class? - java

I was wondering how it is possible to get the value of a variable/boolean that is inside of a loop in a different class.
I would have a variable in one class and want get that in another one:
Class1:
public void mainLoop()
{
while(!Display.isCloseRequested)
{
frames++
if(frames == 200)
{
key = 5
run = false;
}
if(frames == 400)
{
key = 10
run = true;
}
}
}
and in my other Class2 I want to acess the changed varibles:
public Class2()
{
public void printVariables(int key)
{
if(key == 5) { System.out.println("KEY 5"); }
if(key == 10) { System.out.println("KEY 10"); }
if(run == false) { System.out.println("RUN FALSE"); }
if(run == true) { System.out.println("RUN TRUE"); }
}
}
How?
Thanks for any Help!

Add it as a parameter to the method:
public Class2()
{
public void printVariables(int key)
{
if(key == 5) { System.out.println("KEY 5"); }
if(key == 10) { System.out.println("KEY 10"); }
if(run == false) { System.out.println("RUN FALSE"); }
if(run == true) { System.out.println("RUN TRUE"); }
}
}
And then call that method with an instance of the class:
public void mainLoop()
{
Class2 cls2 = new Class2();
while(someCondition == true)
{
frames++
if(frames == 200)
{
key = 5
run = false;
}
if(frames == 400)
{
key = 10
run = true;
}
cls2.printVariables(key);
}
}
Or, if you can, make the method static and call it statically (i.e. Class2.printVariables(key)).

Related

Tic Tac Toe Client Server Interaction

I am currently trying to code a Tic Tac Toe game in Java that is playable across networks. I'm using socket programming in Java and for the UI I am using JavaFX. Upon launching the server and 2 clients, the client connects to the server, pairs players and creates the game. When trying to execute the actual Tic Tac Toe game the GUI gets stuck. I believe it may have something to do with threading but after countless hours of trying different solutions I haven't been able to figure it out.
Below is a video of the issue
https://www.youtube.com/watch?v=dCIxRkGJlCI&t=2s
My GitHub Repo:
https://github.com/Stinny/Tic-Tac-Toe
The issue I believe resides in the TicTacToeController.java class
Any info would be greatly appreciated!
This is my TicTacToeController Class
public class TicTacToeController implements Initializable {
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private static Image Circle = new Image("./Circle.png");
private static Image Cross = new Image("./Cross.png");
private static ImageView icon, opponentIcon;
#FXML
Button topLeft, topRight, topCenter,
midLeft, midCenter, midRight,
botLeft, botMid, botRight;
#FXML
Button play;
public void initialize(URL url, ResourceBundle rb) {
}
public void buttonClickHandler(ActionEvent evt) throws Exception{
Button clickedButton = (Button) evt.getTarget();
evt.getEventType();
String button =((Control)evt.getSource()).getId();
System.out.println(button);
if(button.equals("play")){
clickedButton.setDisable(true);
play();
}
else if (button.equals("topLeft")) {
out.print("MOVE0");
//do something
} else if (button.equals("topRight")) {
//do something
out.print("MOVE2");
} else if (button.equals("topCenter")) {
//do something
out.print("MOVE1");
} else if (button.equals("midLeft")) {
//do something
out.print("MOVE3");
} else if (button.equals("midCenter")) {
//do something
out.print("MOVE4");
} else if (button.equals("midRight")) {
//do something
out.print("MOVE5");
} else if (button.equals("botLeft")) {
//do something
out.print("MOVE6");
} else if (button.equals("botMid")) {
//do something
out.print("MOVE7");
} else if (button.equals("botRight")) {
//do something
out.print("MOVE8");
}
}
public void play() throws IOException {
String response;
try {
connectToServer();
response = in.readLine();
System.out.println("Send to server" + in);
char mark = response.charAt(7);
System.out.println("You are " + mark);
if (mark == 'X') {
icon = new ImageView(Circle);
opponentIcon = new ImageView(Cross);
} else {
icon = new ImageView(Cross);
opponentIcon = new ImageView(Circle);
}
//frame.setTitle("Tic Tac Toe - Player " + mark);
while (true) {
response = in.readLine();
if (response != null) {
System.out.println(response);
if (response.startsWith("VALID_MOVE")) {
int location = Integer.parseInt(response.substring(5));
if (location == 0) {
handleButtonClick(topLeft, icon);
} else if (location == 1) {
handleButtonClick(topLeft, icon);
} else if (location == 2) {
handleButtonClick(topLeft, icon);
} else if (location == 3) {
handleButtonClick(topLeft, icon);
} else if (location == 4) {
handleButtonClick(topLeft, icon);
} else if (location == 5) {
handleButtonClick(topLeft, icon);
} else if (location == 6) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 7) {
handleButtonClick(topLeft, icon);
} else if (location == 8) {
handleButtonClick(topLeft, icon);
}
} else if (response.startsWith("OPPONENT_MOVED")) {
int location = Integer.parseInt(response.substring(15));
if (location == 0) {
handleButtonClick(topLeft, opponentIcon);
} else if (location == 1) {
handleButtonClick(topCenter, opponentIcon);
} else if (location == 2) {
handleButtonClick(topRight, opponentIcon);
} else if (location == 3) {
handleButtonClick(midLeft, opponentIcon);
} else if (location == 4) {
handleButtonClick(midCenter, opponentIcon);
} else if (location == 5) {
handleButtonClick(midRight, opponentIcon);
} else if (location == 6) {
handleButtonClick(botLeft, opponentIcon);
} else if (location == 7) {
handleButtonClick(botMid, opponentIcon);
} else if (location == 8) {
handleButtonClick(botRight, opponentIcon);
}
} else if (response.startsWith("VICTORY")) {
//messageLabel.setText("You win");
break;
} else if (response.startsWith("DEFEAT")) {
//messageLabel.setText("You lose");
break;
} else if (response.startsWith("TIE")) {
//messageLabel.setText("You tied");
break;
}
}
}
out.println("QUIT");
}
finally {
socket.close();
}
}
public void handleButtonClick(Button button, ImageView mark){
button.setGraphic(mark);
}
public static void connectToServer(){
try {
socket = new Socket("localhost", 7777);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e + " fuck");
}
}
}
This is my server class:
public class Server {
private static ServerSocket serverSocket;
private static ArrayList<Socket> sockets;
private static Socket socket;
public static void main(String[] args) throws Exception {
try {
serverSocket = new ServerSocket(7777);
sockets = new ArrayList<>();
for(int i = 1; i < 3; i++){
socket = serverSocket.accept();
System.out.println("Player " + i + " connected");
sockets.add(socket);
}
Game game = new Game();
System.out.println("Created game, waiting for players to connect");
Game.PlayerHandler playerX = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'X');
Game.PlayerHandler playerO = game.new PlayerHandler(sockets.remove(sockets.size()-1), 'O');
game.currentPlayer = playerX;
playerX.start();
playerO.start();
System.out.println("Game started");
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class Game{
private PlayerHandler[] board = {
null, null, null,
null, null, null,
null, null, null
};
PlayerHandler currentPlayer;
public boolean isFull(){
for(int i = 0; i < board.length; i++) {
if(board[i] == null){
return false;
}
}
return true;
}
public boolean hasWinner() {
if (checkHorizontalWin() || checkVerticalWin() || checkDiagonalWin()) {
return true;
} else {
return false;
}
}
public boolean checkHorizontalWin() {
if (board[0] != null && board[0] == board[1] && board[0] == board[2]) {
return true;
} else if(board[3] != null && board[3] == board[4] && board[3] == board[5]) {
return true;
} else if(board[6] != null && board[6] == board[7] && board[6] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkVerticalWin() {
if (board[0] != null && board[0] == board[3] && board[0] == board[6]) {
return true;
} else if(board[1] != null && board[1] == board[4] && board[1] == board[7]) {
return true;
} else if(board[2] != null && board[2] == board[5] && board[2] == board[8]) {
return true;
} else {
return false;
}
}
public boolean checkDiagonalWin() {
if (board[0] != null && board[0] == board[4] && board[0] == board[8]) {
return true;
} else if (board[2] != null && board[2] == board[4] && board[2] == board[6]) {
return true;
} else {
return false;
}
}
public synchronized boolean move(PlayerHandler player, int location) { //A player moves based on their assigned Piece
System.out.println("Player moved at location " + location);
if(board[location]==null){
board[location] = player;
currentPlayer = currentPlayer.opponent;
currentPlayer.opponentMoved(location);
return true;
}
return false;
}
class PlayerHandler extends Thread{
char mark;
private String name;
private Socket socket;
PlayerHandler opponent;
BufferedReader in;
PrintWriter out;
public PlayerHandler(Socket socket, char mark) {
this.socket = socket;
this.mark = mark;
try{
// initialize input and output streams
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("WELCOME" + mark);
} catch(IOException e){
}
}
public void setOpponent(PlayerHandler opponent){
this.opponent = opponent;
}
public void opponentMoved(int location){
out.println("OPPONENT_MOVED" + location);
out.println(
hasWinner() ? "DEFEAT" : isFull() ? "TIE" : "");
}
public void run() {
try {
if (mark == 'X') {
out.println("MESSAGE Your move");
}
while (true) {
String command = in.readLine();
if (command != null) {
if (command.startsWith("MOVE")) {
int location = Integer.parseInt(command.substring(5));
System.out.println(location);
if (move(this, location)) {
out.println("VALID_MOVE" + "location");
out.println(hasWinner() ? "VICTORY"
: isFull() ? "TIE"
: "");
} else {
out.println("MESSAGE ?");
}
}
}
}
}catch(IOException e) {
System.out.println("Player died: " + e);
} finally {
try {socket.close();} catch(IOException e){}
}
}
}
}

Java RPi GPIO issue at runtime

My Code Is This
package me.Andrew.Keypad.Listener;
import java.util.HashMap;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import me.Andrew.Keypad.Main;
public class ButtonInput {
public boolean isRunning = false;
public GpioController gpio = GpioFactory.getInstance();
Main MA = Main.getInstance();
public HashMap<String, GpioPinDigitalInput> ColPins = null;
public HashMap<String, GpioPinDigitalOutput> RowPins = null;
public void start() {
isRunning = true;
ButtonListener();
}
public void stop() {
isRunning = false;
}
private int ScanRow(int row) {
int Col = 0;
RowPins.get(String.valueOf(row)).high();
if (ColPins.get("1").isHigh()) {
Col = 1;
} else if (ColPins.get("2").isHigh()) {
Col = 2;
} else if (ColPins.get("3").isHigh()) {
Col = 3;
} else if (ColPins.get("4").isHigh()) {
Col = 4;
}
return Col;
}
private void ButtonListener() {
Main.GPIOMeths.setupPins();
RowPins = Main.store.RowPins;
ColPins = Main.store.ColPins;
int Response = 0;
while (isRunning == true) {
if (isRunning) {
Response = ScanRow(1);
if (Response == 1) {
stop();
buttonPressEvent("1");
break;
}else if (Response == 2) {
stop();
buttonPressEvent("2");
break;
}else if (Response == 3) {
stop();
buttonPressEvent("3");
break;
}else if (Response == 4) {
stop();
buttonPressEvent("A");
break;
}
int Responsee = ScanRow(2);
if (Responsee != 0) {
stop();
String BP = Main.Meths.getButton(2, Responsee);
buttonPressEvent(BP);
break;
}
int Responseee = ScanRow(3);
if (Responseee != 0) {
stop();
String BP = Main.Meths.getButton(3, Responseee);
buttonPressEvent(BP);
break;
}
int Responseeee = ScanRow(4);
if (Responseeee != 0) {
stop();
String BP = Main.Meths.getButton(4, Responseeee);
buttonPressEvent(BP);
break;
}
}
}
}
public void buttonPressEvent(String ButtonPressed) {
// String ButtonPressed = Main.Meths.getButton(Row, Col);
if (ButtonPressed.equalsIgnoreCase("*")) {
System.out.println("Code Logging Started");
Main.store.CodeMode = true;
Main.store.CodeEntered = "";
} else if (ButtonPressed.equalsIgnoreCase("#")) {
System.out.println("Code Logging Ended");
if (Main.Meths.CompareCodes()) {
System.out.println("Code Correct");
} else {
System.out.println("Code Incorrect");
}
Main.store.CodeMode = false;
} else {
if (Main.store.CodeMode == false) {
System.out.println("Code Logging Not Running: " + ButtonPressed);
} else {
Main.store.CodeEntered = Main.store.CodeEntered + ButtonPressed;
System.out.println("Code Entered: " + Main.store.CodeEntered);
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
} finally {
start();
}
}
}
But when i run it and press 1,2,3,A All of the top row i get this response
root#raspberrypi:/home/pi# java -jar /home/pi/keypad.jar
Code Logging Not Running: 7
Code Logging Not Running: 0
Code Logging Not Running: 9
Code Logging Not Running: A
Code Logging Not Running: 7
Code Logging Not Running: 5
Code Logging Not Running: 3
Code Logging Not Running: A
Added
RowPins.get(String.valueOf(row)).low();
At the end of scan row

AVL tree in java

The program that I am writing simulates a road charging system which reads several lines of inputs, each one representing a different command until I reach the EOF (\n).
This commands simulate a road charging system, where the input reads as follows:
PASS 44AB55 I -> where the first word is the command the program receives, the second word is the number plate of the car (44AB55) and the second is the status of the car (Regular or Irregular).
There are three types of commands:
“PASS 00AA00 R” – Increments the number of times that the car has passed in the system and marks its status has Regular or Irreguar. If the car isnt still in the database, it inserts the car as Regular and starts the counter with one passage.
“UNFLAG 00AA00” – Flags the car as Regular if it exists in the database. If the car doesnt exist in the database ignores the command.
“STATUS 00AA00” – Retrieves the status of the car (Regular or Irregular) and the number of passages of the car in the system. If it the car doesnt exist in the database, prints a "NO RECORD" message.
To solve this problem, I am using AVL trees and using the following code:
import java.util.ArrayList;
import java.util.Scanner;
public class TP2_probB {
static No raiz = null;
static double numRotacoes = 0;
static double numAtravessos = 0;
public static class No {
private String matricula;
private int porticos;
private boolean estadoRegular;
private No pai;
private No filhoEsq;
private No filhoDir;
private int balanco;
public No(String matricula, int porticos, boolean estadoRegular) {
this.matricula = matricula;
this.porticos = porticos;
this.estadoRegular = estadoRegular;
this.pai = null;
this.filhoDir = null;
this.filhoEsq = null;
this.balanco = 0;
}
public void setEstadoRegular(boolean estadoRegular) {
this.estadoRegular = estadoRegular;
}
public void setPai(No pai) {
this.pai = pai;
}
public void setFilhoEsq(No filhoEsq) {
this.filhoEsq = filhoEsq;
}
public void setFilhoDir(No filhoDir) {
this.filhoDir = filhoDir;
}
public void atribuiNoEsq(No noEsq) {
this.filhoEsq = noEsq;
}
public void atribuiNoDir(No noDir) {
this.filhoDir = noDir;
}
public void atribuiPai(No noPai) {
this.pai = noPai;
}
public void aumentaPortico() {
porticos++;
}
public String getMatricula() {
return matricula;
}
public boolean isEstadoRegular() {
return estadoRegular;
}
public No getPai() {
return pai;
}
public No getFilhoEsq() {
return filhoEsq;
}
public No getFilhoDir() {
return filhoDir;
}
#Override
public String toString() {
String estado;
if (estadoRegular == true) {
estado = "R";
} else {
estado = "I";
}
return matricula + " " + porticos + " " + estado;
}
}
public static No duplaRotacaoFilhoEsq(No k3)
{
k3.filhoEsq = rotacaoFilhoDir(k3);
return rotacaoFilhoEsq(k3);
}
public static No duplaRotacaoFilhoDir(No k3)
{
k3.filhoDir = rotacaoFilhoEsq(k3);
return rotacaoFilhoDir(k3);
}
public static No rotacaoFilhoDir(No k1) {
No k2 = k1.filhoDir;
k2.pai=k1.pai;
k1.filhoDir = k2.filhoEsq;
if(k1.filhoDir!=null)
{
k1.filhoDir.pai=k1;
}
k2.filhoEsq = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static No rotacaoFilhoEsq(No k1) {
No k2 = k1.filhoEsq;
k2.pai=k1.pai;
k1.filhoEsq = k2.filhoDir;
if(k1.filhoEsq!=null)
{
k1.filhoEsq.pai=k1;
}
k2.filhoDir = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static int pesagem(No aux)
{
if(aux==null)
{
return -1;
}
if(aux.filhoEsq == null && aux.filhoDir == null)
{
return 0;
}
else if ((aux.filhoEsq == null))
{
return (pesagem(aux.filhoDir) + 1);
}
else if ((aux.filhoDir == null))
{
return (pesagem(aux.filhoEsq) + 1);
}
else
return (Math.max(pesagem(aux.filhoEsq), pesagem(aux.filhoDir)) + 1);
}
public static void balanco(No tmp)
{
tmp.balanco = pesagem(tmp.filhoDir)-pesagem(tmp.filhoEsq);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String linha;
String[] aux;
ArrayList<String> output = new ArrayList<String>();
int x = 0;
while (true) {
linha = input.nextLine();
if (linha.isEmpty())
{
break;
}
else
{
aux = linha.split(" ");
if (aux[0].compareTo("PASS") == 0) {
No novo;
if (aux[2].compareTo("R") == 0) {
novo = new No(aux[1], 1, true);
} else {
novo = new No(aux[1], 1, false);
}
if (raiz == null) {
raiz = novo;
balanco(raiz);
} else {
procuraNo(novo);
}
} else if (aux[0].compareTo("UNFLAG") == 0) {
if (raiz != null) {
No no = new No(aux[1], 0, false);
mudaEstado(no);
}
} else if (aux[0].compareTo("STATUS") == 0) {
if (raiz == null) {
output.add(aux[1] + " NO RECORD");
} else {
No no = new No(aux[1], 0, false);
output.add(procuraRegisto(no));
}
}
}
}
for (int i = 0; i < output.size(); i++) {
System.out.println(output.get(i));
}
System.out.println("Número de Rotações: "+numRotacoes+"\nNúmero de atravessias: "+numAtravessos);
}
public static void procuraNo(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.aumentaPortico();
aux.setEstadoRegular(novo.isEstadoRegular());
equilibra(aux);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
novo.setPai(aux);
aux.setFilhoDir(novo);
aux=aux.filhoDir;
equilibra(aux);
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
novo.setPai(aux);
aux.setFilhoEsq(novo);
aux=aux.filhoEsq;
equilibra(aux);
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static void equilibra(No tmp) {
balanco(tmp);
int balanco = tmp.balanco;
System.out.println(balanco);
if(balanco==-2)
{
if(pesagem(tmp.filhoEsq.filhoEsq)>=pesagem(tmp.filhoEsq.filhoDir))
{
tmp = rotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
else if(balanco==2)
{
if(pesagem(tmp.filhoDir.filhoDir)>=pesagem(tmp.filhoDir.filhoEsq))
{
tmp = rotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
if(tmp.pai!=null)
{
equilibra(tmp.pai);
}
else
{
raiz = tmp;
}
}
public static void mudaEstado(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.setEstadoRegular(true);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static String procuraRegisto(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
return aux.toString();
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
}
The problem is that I am getting a stack overflow error:
Exception in thread "main" java.lang.StackOverflowError
at TP2_probB.pesagem(TP2_probB.java:174)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
(...)
at TP2_probB.pesagem(TP2_probB.java:177)
Here is a link with two files with inputs used to test the program:
https://drive.google.com/folderview?id=0B3OUu_zQ9xlGfjZHRlp6QkRkREc3dU82QmpSSWNMRlBuTUJmWTN5Ny1LaDhDN3M2WkVjYVk&usp=sharing

Assign int to JButtons to make method more efficient?

I'm making a game with 9 JButtons that each do basically the same function. How can I make it so that these buttons each have an int (0-8) attached to them so I don't have to write the same method 9 times? Here is the method as it is currently:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cardOne) {
if(boardArray.get(0).selected == false) {
getPath(0);
buttons[0].setIcon(selectedIcon);
boardArray.get(0).selected = true;
}else{
boardArray.get(0).selected = false;
buttons[0].setIcon(boardArray.get(0).cardImage);
}
}
if(e.getSource() == cardTwo) {
if(boardArray.get(1).selected == false) {
getPath(1);
buttons[1].setIcon(selectedIcon);
boardArray.get(1).selected = true;
}else{
boardArray.get(1).selected = false;
buttons[1].setIcon(boardArray.get(1).cardImage);
}
}
if(e.getSource() == cardThree) {
if(boardArray.get(2).selected == false) {
getPath(2);
buttons[2].setIcon(selectedIcon);
boardArray.get(2).selected = true;
}else{
boardArray.get(2).selected = false;
buttons[2].setIcon(boardArray.get(2).cardImage);
}
}
if(e.getSource() == cardFour) {
if(boardArray.get(3).selected == false) {
getPath(3);
buttons[3].setIcon(selectedIcon);
boardArray.get(3).selected = true;
}else{
boardArray.get(3).selected = false;
buttons[3].setIcon(boardArray.get(3).cardImage);
}
}
if(e.getSource() == cardFive) {
if(boardArray.get(4).selected == false) {
getPath(4);
buttons[4].setIcon(selectedIcon);
boardArray.get(4).selected = true;
}else{
boardArray.get(4).selected = false;
buttons[4].setIcon(boardArray.get(4).cardImage);
}
}
if(e.getSource() == cardSix) {
if(boardArray.get(5).selected == false) {
getPath(5);
buttons[5].setIcon(selectedIcon);
boardArray.get(5).selected = true;
}else{
boardArray.get(5).selected = false;
buttons[5].setIcon(boardArray.get(5).cardImage);
}
}
if(e.getSource() == cardSeven) {
if(boardArray.get(6).selected == false) {
getPath(6);
buttons[6].setIcon(selectedIcon);
boardArray.get(6).selected = true;
}else{
boardArray.get(6).selected = false;
buttons[6].setIcon(boardArray.get(6).cardImage);
}
}
if(e.getSource() == cardEight) {
if(boardArray.get(7).selected == false) {
getPath(7);
buttons[7].setIcon(selectedIcon);
boardArray.get(7).selected = true;
}else{
boardArray.get(7).selected = false;
buttons[7].setIcon(boardArray.get(7).cardImage);
}
}
if(e.getSource() == cardNine) {
if(boardArray.get(8).selected == false) {
getPath(8);
buttons[8].setIcon(selectedIcon);
boardArray.get(8).selected = true;
}else{
boardArray.get(8).selected = false;
buttons[8].setIcon(boardArray.get(6).cardImage);
}
}
You could...
Associate each JButton with an int via a Map of some kind...
private Map<JButton, Integer> mapButtons;
//...
mapButtons = new HashMap<JButton, Integer>(25);
mapButtons.put(cardOne, 1);
Then you could just extract the integer value within the ActionListener
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
int value = mapButtons.get(btn);
If you don't want to introduce another object into your code...
You could...
Associate a value via the buttons clientProperty property...
btn.putClientProperty("value", 1);
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
value = (Integer)btn.getClientProperty("value");
You could...
Use the buttons actionCommand property, which expects a String, but you could cast it to a int value. It's a little more messy, but would get the job done...
You can use setActionCommand() to set to each button its corresponding number and in the actionPerformed method call e.getActionCommand() and parse that String to an int
Another possibility is to create an inner class that implements ActionListener like so:
public class ButtonActionListener implements ActionListener {
private final int boardElement;
ButtonActionListener(int boardElement) {
this.boardElement = boardElement;
}
#Override
public void actionPerformed(ActionEvent e) {
if (boardArray.get(boardElement).selected == false) {
getPath(boardElement);
buttons[boardElement].setIcon(selectedIcon);
boardArray.get(boardElement).selected = true;
} else {
boardArray.get(boardElement).selected = false;
buttons[boardElement].setIcon(boardArray.get(boardElement).cardImage);
}
}
}
Then when you create the JButton objects, add an instance of this action listener with the required index:
// Just an example, it's not clear to me how the buttons[] array is created
for (int i = 0; i < boardArray.size(); ++i) {
buttons[i] = new JButton();
// Other stuff as needed
buttons[i].addActionListener(new ButtonActionListener(i));
}

JFormattedTextfield in an applet is inserting spaces

I've got an applet that pops up a dialog to enter credit card details.
I'm using four JFormattedTextField classes to allow the user to input each 4 digit fragment of the credit card. I've got code in place to auto tab to the next field as the user is typing out the CC number. The problem is that when the dialog is launched from an applet running in IE8 using ( I'm restricted to using Java 7 update 13), if the user types in the number quickly, spaces appear to be inserted apparently at random even though a mask is applied to only allow alpha-numerics.
The code below is are the listeners on the the JFormattedTextField class where I suspect the issue resides.
super.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent event) {
EntryField field = (EntryField)event.getSource();
if (_initialPosition > 0) {
// if the initial position is set externally. This will happen when the caret is being set during
// the initial load of the dialog.
field.select(0, 0);
field.setCaretPosition(_initialPosition);
_initialPosition = -1;
}
else if (event.getOppositeComponent() == field.getNextControl()) {
field.select(0, 0);
field.setCaretPosition(field.getMaxCharacters()-1);
}
else {
field.select(0, 0);
field.setCaretPosition(0);
}
}
#Override
public void focusLost(FocusEvent event) {}
});
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent keyEvent) {
if(keyEvent.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == 0 && field.hasPreviousControl()) {
field.backtrackFocus(true);
}
}
else if(Character.isLetterOrDigit(keyEvent.getKeyChar())) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == field.getMaxCharacters() - 1) {
field.moveFocus();
}
}
else if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == 0 && field.hasPreviousControl()) {
field.backtrackFocus(false);
}
}
else if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
EntryField field = (EntryField) keyEvent.getSource();
if(field.getCaretPosition() == field.getMaxCharacters() - 1 && field.hasNextControl()) {
field.moveFocus();
}
}
else if(keyEvent.isControlDown() && keyEvent.getKeyChar() == 'c') {
EntryField field = (EntryField) keyEvent.getSource();
field.paste();
}
}
#Override
public void keyTyped(KeyEvent keyEvent) {
if (_checkAmEx && Character.isLetterOrDigit(keyEvent.getKeyChar())) {
EntryField field = (EntryField)keyEvent.getSource();
int pos = field.getCaretPosition();
if (pos == 2 && creditCardIsAmex()) {
field.moveFocus();
}
}
else if(keyEvent.getKeyChar() == KeyEvent.VK_DELETE) {
EntryField field = (EntryField) keyEvent.getSource();
field.setCaretPosition(field.getCaretPosition() - 1);
field.shiftTextLeft();
}
else if(keyEvent.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
EntryField field = (EntryField) keyEvent.getSource();
field.shiftTextLeft();
}
}
#Override
public void keyReleased(KeyEvent keyEvent) {}
});

Categories