I have got an array of 30 buttons []. I have a variable buttonClicked. When I press the button how can I get the index and store the index number in the buttonClicked?
Thanks :)
JButton [] buttons = new JButton[30];
for(int i = 1; i <= 30; i++)
{
int btnNumber = (i > 10 && i <= 20) ? (31 - i) : i;
System.out.printf("i = %d, btnNumber = %d%n", i, btnNumber);
buttons[btnNumber - 1] = new JButton("label " + btnNumber);
//buttons[btnNumber - 1].setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttons[btnNumber - 1].setBorder(BorderFactory.createEtchedBorder());
buttons[btnNumber - 1].setOpaque(true);
buttons[btnNumber - 1].setBackground(Color.white);
//Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10
if ((btnNumber - 1) < 10)
{
if (((btnNumber - 1) % 2) == 0)
{
buttons[btnNumber - 1].setIcon(piece1);
}
else
{
buttons[btnNumber - 1].setIcon(piece2);
}
}
centerPanel.add(buttons[btnNumber - 1]);
}
//Below is what I am attempting to do, I know is not correct.
public void move()
{
Move = dice.getDiceResult();
int buttonClicked = 0;
if(playerOneTurn =true)
{
buttonclicked + diceResult();
}
//revised
public class MyActionListener implements ActionListener {
Dice dice;
private boolean playerOneTurn = true;
private boolean playerTwoTurn = false;
#Override
public void actionPerformed(ActionEvent e)
{
String num = e.getActionCommand();
int index = Integer.parseInt(num);
int move = dice.getDiceResult();
int positionLanding = 0;
if(playerOneTurn = true)
{
positionLanding = index + move;
positionLanding.setIcon("piece1");//how can I set the image Icon to this position?
}
}
}
1) putClientProperty
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
and getClientProperty
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
2) ActionCommand
You can find the button in ActionEvent.getSource(). To find the index it is just a matter of iterating through the array, looking for that particular button.
The prettiest way is using Component.setName. Then you don't even need to maintain variables with your components - you can go straight off of the name
I prefer the strategy suggested by aioobe, but here is another way.
buttons[btnNumber - 1] = new JButton("label " + btnNumber);
buttons[btnNumber - 1].setActionCommand("" + btnNumber);
// ...
// ...later.. in the actionPerformed() method
String num = actionEvent.getActionCommand();
int index = Integer.parseInt(num);
// ..proceed..
Related
I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}
here i attach the picture of my apps so I want to create an app that can be use and install for me and my friends on laptop. What this app will do :
1. this app will have 20 numbers and the initial numbers will be "0" before they click the start button.
The first 10 numbers in the textbox, users can insert any numbers thats the range only between 0-9 only but for the last 10 numbers, users cannot insert any numbers.
this app have 2 buttons which are save and start button.
when the users click start button even the users didnt insert anything in the first 10 textbox, the 1st number will start counting from 0-9, after the 1st number finish count until 9, the second number will continue counting from 0-9 and 3rd-20th number will also do the same until all the 20 numbers in the textbox become 9999999999999999999, then it will stop counting.
when the users insert numbers in first three textbox and press start button, the number will start counting from the 4th textbox, until 20th numbers and until the 4-20th numbers become ***999999999999999999.
but every time the numbers changing, for example, when 1st number start counting like 100000000000000000000, users will click save button and it will save the numbers in the textarea which is located in the middle of this app and at the same time it will automatically create a folder in the users computer and the numbers will also save in that folder.
when the users transfer that folder from their laptop to their phone, all the numbers will save automatically as contact numbers in their phone.
here in my code, I dont know how to make the start button to run the numbers automatically once the start button click, in my code, the number will only change everytime when the start button click, i just want to click the start button only one time and the number will count automatically,anyone know how to do it? and the save button also i have no idea how to do it.`[ import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class b extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
JTextField t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20;
JButton start, save;
JTextArea ta;
public b() {
Container pane = getContentPane();
pane.setLayout(new GridLayout(3, 1));
panel.setLayout(new FlowLayout());
panel.add(t1 = new JTextField(("0"), 2));
panel.add(t2 = new JTextField(("0"), 2));
panel.add(t3 = new JTextField(("0"), 2));
panel.add(t4 = new JTextField(("0"), 2));
panel.add(t5 = new JTextField(("0"), 2));
panel.add(t6 = new JTextField(("0"), 2));
panel.add(t7 = new JTextField(("0"), 2));
panel.add(t8 = new JTextField(("0"), 2));
panel.add(t9 = new JTextField(("0"), 2));
panel.add(t10 = new JTextField(("0"), 2));
panel.add(t11 = new JTextField(("0"), 2));
panel.add(t12 = new JTextField(("0"), 2));
panel.add(t13 = new JTextField(("0"), 2));
panel.add(t14 = new JTextField(("0"), 2));
panel.add(t15 = new JTextField(("0"), 2));
panel.add(t16 = new JTextField(("0"), 2));
panel.add(t17 = new JTextField(("0"), 2));
panel.add(t18 = new JTextField(("0"), 2));
panel.add(t19 = new JTextField(("0"), 2));
panel.add(t20 = new JTextField(("0"), 2));
t11.setEditable(false);
t12.setEditable(false);
t12.setEditable(false);
t13.setEditable(false);
t14.setEditable(false);
t15.setEditable(false);
t16.setEditable(false);
t17.setEditable(false);
t18.setEditable(false);
t19.setEditable(false);
t20.setEditable(false);
ta = new JTextArea();
ta.setEditable(false);
panel1.setLayout(new FlowLayout());
panel1.add(save = new JButton("Save"));
panel1.add(start = new JButton("Start"));
pane.add(panel);
pane.add(ta);
pane.add(panel1);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
t5.addActionListener(this);
t6.addActionListener(this);
t7.addActionListener(this);
t8.addActionListener(this);
t9.addActionListener(this);
t10.addActionListener(this);
t11.addActionListener(this);
t12.addActionListener(this);
t13.addActionListener(this);
t14.addActionListener(this);
t15.addActionListener(this);
t16.addActionListener(this);
t17.addActionListener(this);
t18.addActionListener(this);
t19.addActionListener(this);
t20.addActionListener(this);
save.addActionListener(this);
start.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
int count = Integer.parseInt(t1.getText());
if (obj == start) {
if (count < 9) {
count++;
t1.setText("" + count);
}
else {
count = 0;
t1.setText("" + count);
count = Integer.parseInt(t2.getText());
if (count < 9) {
count++;
t2.setText("" + count);
}
else {
count = 0;
t2.setText("" + count);
count = Integer.parseInt(t3.getText());
if (count < 9) {
count++;
t3.setText("" + count);
}
else {
count = 0;
t3.setText("" + count);
count = Integer.parseInt(t4.getText());
if (count < 9) {
count++;
t4.setText("" + count);
}
else {
count = 0;
t4.setText("" + count);
count = Integer.parseInt(t5.getText());
if (count < 9) {
count++;
t5.setText("" + count);
}
else {
count = 0;
t5.setText("" + count);
count = Integer.parseInt(t6.getText());
if (count < 9) {
count++;
t6.setText("" + count);
}
else {
count = 0;
t6.setText("" + count);
count = Integer.parseInt(t7.getText());
if (count < 9) {
count++;
t7.setText("" + count);
}
else {
count = 0;
t7.setText("" + count);
count = Integer.parseInt(t8.getText());
if (count < 9) {
count++;
t8.setText("" + count);
}
else {
count = 0;
t8.setText("" + count);
count = Integer.parseInt(t9.getText());
if (count < 9) {
count++;
t9.setText("" + count);
}
else {
count = 0;
t9.setText("" + count);
count = Integer.parseInt(t10.getText());
if (count < 9) {
count++;
t10.setText("" + count);
}
else {
count = 0;
t10.setText("" + count);
count = Integer.parseInt(t11.getText());
if (count < 9) {
count++;
t11.setText("" + count);
}
else {
count = 0;
t11.setText("" + count);
count = Integer.parseInt(t12.getText());
if (count < 9) {
count++;
t12.setText("" + count);
}
else {
count = 0;
t12.setText("" + count);
count = Integer.parseInt(t13.getText());
if (count < 9) {
count++;
t13.setText("" + count);
}
else {
count = 0;
t13.setText("" + count);
count = Integer.parseInt(t14.getText());
if (count < 9) {
count++;
t14.setText("" + count);
}
else {
count = 0;
t14.setText("" + count);
count = Integer.parseInt(t15.getText());
if (count < 9) {
count++;
t15.setText("" + count);
}
else {
count = 0;
t15.setText("" + count);
count = Integer.parseInt(t16.getText());
if (count < 9) {
count++;
t16.setText("" + count);
}
else {
count = 0;
t16.setText("" + count);
count = Integer.parseInt(t17.getText());
if (count < 9) {
count++;
t17.setText("" + count);
}
else {
count = 0;
t17.setText("" + count);
count = Integer.parseInt(t18.getText());
if (count < 9) {
count++;
t18.setText("" + count);
}
else {
count = 0;
t18.setText("" + count);
count = Integer.parseInt(t19.getText());
if (count < 9) {
count++;
t19.setText("" + count);
}
else {
count = 0;
t19.setText("" + count);
count = Integer.parseInt(t20.getText());
if (count < 9) {
count++;
t20.setText("" + count);
}
else {
count = 0;
t20.setText("0");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public static void main (String[] args) {
b frame1 = new b();
frame1.setTitle("bb");
frame1.setSize(650, 400);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
}
]2`
I am creating a program to take in 1 or more 8 bit binary sequences and convert them into 12 bit hamming binary sequences. The code works and achieves everything right up until it tries to put the information into the JTextField at which point it converts the 8-bit stream into 1111 1111 and converts the 12 bit stream into 0000 0000 0000 (spacing for easier reading). I have tried stepping through the code and at every point it thinks the list is correct, right until i turn it into a string. Im not sure if im incorrectly using something but hopefully someone can help.
As an example for those who dont understand hamming codes. If you put in "10101010" no spaces, the system should spit out "Your original bit-stream was: 1010 1010 Your new Hamming bit-stream is: 1010 0101 1000"
But instead it will say "Your original bit-stream was: 1111 1111 Your new Hamming bit-stream is: 0000 0000 0000"
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
#SuppressWarnings("serial")
public class MainProgram extends JPanel {
private static final String INITIAL_TITLE = "Please enter your next 8 bits. "
+ "Do not enter more than 8 bits.\n"
+ "Press Enter when done";
private static final String ARE_YOU_FINISHED = "Are you finished entering streams?";
private static final String CALCULATING = "Just one moment while the code is generated...";
private static final String YES = "YES";
private static final String ENTER = "ENTER";
private static final String NO = "NO";
private static final String CONTINUE = "CONTINUE";
private static int GAP = 12;
private static final int COLUMNS = 35;
private static int TEMP_STREAM = 0;
static int numberOfStreams = 0;
static int counter = 0;
static String OriBuild;
static String NewBuild;
// this is a JTextArea built to look like a JLabel
private JTextArea topTextArea = new JTextArea(2, COLUMNS);
private JTextField dataEntryField = new JTextField(COLUMNS);
private JTextArea dataPrinter = new JTextArea(2,2);
private JButton yesEnterButton = new JButton(ENTER);
private JButton noButton = new JButton(NO);
private JButton contButton = new JButton(CONTINUE);
private boolean enteringData = true;
private boolean dataValidYet = false;
java.util.List<Integer> streamSplit = new ArrayList<>();
java.util.List<Integer> tempEight = new ArrayList<>();
java.util.List<Integer> finalStream = new ArrayList<>();
public MainProgram(){
yesEnterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yesEnterButtonActionPerfromed(e);
}
});
noButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
noButtonActionPerfromed(e);
}
});
contButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
contButtonActionPerfromed(e);
}
});
topTextArea.setWrapStyleWord(true);
topTextArea.setLineWrap(true);
topTextArea.setFocusable(false);
topTextArea.setEditable(false);
topTextArea.setOpaque(false);
topTextArea.setText(INITIAL_TITLE);
JPanel innerButtonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
innerButtonPanel.add(yesEnterButton);
innerButtonPanel.add(contButton);
innerButtonPanel.add(noButton);
contButton.setVisible(false);
noButton.setVisible(false);
JPanel outerButtonPanel = new JPanel();
outerButtonPanel.add(innerButtonPanel);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topTextArea, BorderLayout.PAGE_START);
add(dataEntryField, BorderLayout.LINE_END);
dataPrinter.setVisible(false);
add(dataPrinter, BorderLayout.LINE_START);
add(outerButtonPanel, BorderLayout.PAGE_END);
}
protected void noButtonActionPerfromed(ActionEvent e) {
if(!dataValidYet){
enteringData = true;
topTextArea.setText(INITIAL_TITLE);
noButton.setVisible(false);
dataEntryField.setVisible(true);
return;
}
// Pressing no allows more entry
}
private void yesEnterButtonActionPerfromed(ActionEvent e) {
if (enteringData) {
topTextArea.setText(ARE_YOU_FINISHED);
yesEnterButton.setText(YES);
yesEnterButton.setActionCommand(YES);
noButton.setVisible(true);
TEMP_STREAM = checkInput();
enteringData = false;
dataEntryField.setText("");
dataEntryField.setVisible(false);
streamAdd();//This function adds the stream (example: 10101010) to a list creating individual digits of 1,0,1,0,1,0,1,0
return;
}//pressing enter takes the value in box. Pressing yes causes the system to move on
else{
dataValidYet = true;
yesEnterButton.setVisible(false);
noButton.setVisible(false);
logicLaunch();//converts the 8 digit binary into a 12 digit hamming code
contButton.setVisible(true);
}
}
private void contButtonActionPerfromed(ActionEvent e) {
//This groups the 8 original individual digits, that were seperated into a list, back into a string for printing purposes
if(counter < numberOfStreams) {
dataPrinter.setVisible(true);
dataEntryField.setVisible(false);
OriBuild = ("Your original bit-stream was: "
+ streamSplit.get(counter * 0)
+ streamSplit.get(counter * 1)
+ streamSplit.get(counter * 2)
+ streamSplit.get(counter * 3) + " "
+ streamSplit.get(counter * 4)
+ streamSplit.get(counter * 5)
+ streamSplit.get(counter * 6)
+ streamSplit.get(counter * 7));
NewBuild = ("Your new Hamming bit-stream is: "
//This groups the 12 new individual digits, that were seperated into a list, back into a string for printing purposes
+ finalStream.get(counter * 0)
+ finalStream.get(counter * 1)
+ finalStream.get(counter * 2)
+ finalStream.get(counter * 3) + " "
+ finalStream.get(counter * 4)
+ finalStream.get(counter * 5)
+ finalStream.get(counter * 6)
+ finalStream.get(counter * 7) + " "
+ finalStream.get(counter * 8)
+ finalStream.get(counter * 9)
+ finalStream.get(counter * 10)
+ finalStream.get(counter * 11));
System.out.println(OriBuild + " " + NewBuild);
dataPrinter.setText(OriBuild + "\n" + NewBuild);
counter++;
//Prints the strings to the screen so that the user can retrieve wanted information. Then adds 1 to the counter incase more than 1 stream was entered to cycle
} else {
dataPrinter.setText("Program complete. Close and relaunch to re-use");
contButton.setVisible(false);
//Once out of streams program finishes on this informing user that its reached the end of its usefulness and require re-launching.
}
}
private static void createAndShowGui() {
MainProgram mainPanel = new MainProgram();
JFrame frame = new JFrame("HammingCode");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public int checkInput()
{
String temp1 = dataEntryField.getText();
int temp = Integer.parseInt(temp1);
return temp;
}
public void streamAdd(){
do {
streamSplit.add(TEMP_STREAM % 10);
TEMP_STREAM /= 10;
} while (TEMP_STREAM != 0);
}
public void logicLaunch(){
topTextArea.setText(CALCULATING);
int arrayLength = streamSplit.size();
int bufferLength = 8 - arrayLength % 8;
if (bufferLength != 8)
{
numberOfStreams = arrayLength / 8 + 1;
} else
{
numberOfStreams = arrayLength / 8;
}
int tempStreams = numberOfStreams;
System.out.println(numberOfStreams + "<Streams Buffer>" + bufferLength);
while (bufferLength > 0 && bufferLength != 8)
{
streamSplit.add(0);
bufferLength--;
}
while (tempStreams > 0)
{
for (int i = 0; i < 8; i++)
{
tempEight.add(streamSplit.get(i));
}
if ((tempEight.get(0) + tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6)) % 2 == 0)
{
tempEight.add(0, 0);
} else
{
tempEight.add(0, 1);
}
if ((tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6) + tempEight.get(7)) % 2 == 0)
{
tempEight.add(1, 0);
} else
{
tempEight.add(1, 1);
}
if ((tempEight.get(3) + tempEight.get(4) + tempEight.get(5) + tempEight.get(9)) % 2 == 0)
{
tempEight.add(3, 0);
} else
{
tempEight.add(3, 1);
}
if ((tempEight.get(7) + tempEight.get(8) + tempEight.get(9) + tempEight.get(10)) % 2 == 0)
{
tempEight.add(7, 0);
} else
{
tempEight.add(7, 1);
}
tempStreams--;
for (int i = 0; i < 12; i++)
{
finalStream.add(tempEight.get(0));
tempEight.remove(0);
}
}
Collections.reverse(streamSplit);
}//Runs all the logic to generate the 12 bit code, this part is working fine. Reverse is for formatting purposes
}
I haven't figured out the code entirely, but it appears your use of counter in contButtonActionPerfromed is incorrect. When counter is 0, it will get element 0 every time; when 1 it will get 0, 1, 2, etc.; when 2 it will get 0, 2, 4, etc. Then there's something about exiting the program after the first time, so maybe you don't go through it a second time (and a third time would likely generate an error attempting to access a non-existent element).
You really ought to be able to debug that method...
I'm writing a program in Java that is supposed to function as a truth table generator for a boolean expression. However, I'm having a lot of trouble with the brackets. The errors start when a pair of brackets enclose the entire expression (produces a runtime error), or if there aren't enough brackets in the expression (producing the wrong result).
Here's all my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.Math;
public class BooleanAlgebra
{
public static void main(String[] args)
{
new BooleanAlgebra();
}
private JFrame frame;
private JPanel panel;
private JTextField textField;
private JButton and;
private JButton or;
private JButton not;
private JButton nor;
private JButton nand;
private JButton xor;
private JButton xnor;
private JPanel panel2;
private JButton generate;
private JButton close;
private ArrayList<Character> variables;
private char[] chars;
public BooleanAlgebra()
{
frame = new JFrame("Boolean Algebra");
frame.setSize(new Dimension(800, 800));
textField = new JTextField("(x+y)");
and = new JButton("AND [ x & y ]");
or = new JButton("OR [ x + y ]");
not = new JButton("NOT [ ! x ]");
nor = new JButton("NOR [ ! ( x + y ) ]");
nand = new JButton("NAND [ ! ( x & y ) ]");
xor = new JButton("XOR [ ( x & ! y ) + ( ! x & y ) ]");
xnor = new JButton("XNOR [ ( x & y ) + ( ! x & ! y ) ]");
generate = new JButton("Generate Table");
close = new JButton("Exit");
ButtonHandler buttons = new ButtonHandler();
and.addActionListener(buttons);
or.addActionListener(buttons);
not.addActionListener(buttons);
nor.addActionListener(buttons);
nand.addActionListener(buttons);
xor.addActionListener(buttons);
xnor.addActionListener(buttons);
generate.addActionListener(buttons);
close.addActionListener(buttons);
panel2 = new JPanel();
panel2.setLayout(new GridLayout(1, 2));
panel2.add(generate);
panel2.add(close);
panel = new JPanel();
panel.setLayout(new GridLayout(9, 1));
panel.add(textField);
panel.add(and);
panel.add(or);
panel.add(not);
panel.add(nor);
panel.add(nand);
panel.add(xor);
panel.add(xnor);
panel.add(panel2);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private boolean isLetter(char a)
{
if((a > 64 && a < 91) || (a > 96 && a < 123))
{
return true;
}
return false;
}
private void generate()
{
chars = ("(" + textField.getText() + ")").toCharArray();
variables = new ArrayList<Character>();
for(int i = 0; i < chars.length; i++)
{
if(isLetter(chars[i]))
{
if(!variables.contains(chars[i]))
{
variables.add(chars[i]);
}
}
}
Collections.sort(variables);
String[] heads = new String[variables.size() + 1];
for(int i = 0; i < heads.length - 1; i++)
{
heads[i] = variables.get(i).toString();
}
heads[heads.length - 1] = textField.getText();
int row = (int)Math.pow(2, variables.size());
int column = variables.size() + 1;
int count = 0;
int max = 1;
Integer[][] array = new Integer[row][column];
for(int a = column - 2; a >= 0; a--)
{
for(int b = 0; b < row; b++)
{
if(count < max)
{
array[b][a] = 0;
count++;
}
else if(count >= max)
{
array[b][a] = 1;
count++;
if(count == max * 2)
{
count = 0;
}
}
}
max = max * 2;
}
for(int i = 0; i < row; i++)
{
array[i][column - 1] = 0;
}
int[][] arrayCopy = new int[row][column];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
arrayCopy[i][j] = array[i][j];
}
}
for(int i = 0; i < row; i++)
{
array[i][column - 1] = calculate(arrayCopy[i]);
}
JTable table = new JTable(array, heads);
JFrame frame2 = new JFrame(textField.getText());
frame2.add(new JScrollPane(table));
frame2.pack();
frame2.setVisible(true);
table.setEnabled(false);
}
private int calculate(int[] array)
{
Stack<Character> ops = new Stack<Character>();
Stack<Integer> values = new Stack<Integer>();
for(int i = 0; i < chars.length; i++)
{
char s = chars[i];
if (s == '(') ;
else if (s == '+') ops.push(s);
else if (s == '&') ops.push(s);
else if (s == '!') ops.push(s);
else if (s == ')')
{
char operation = ops.pop();
int v = values.pop();
if (operation == '+') v = or(values.pop(), v);
else if (operation == '&') v = and(values.pop(), v);
else if (operation == '!') v = not(v);
values.push(v);
}
else if(isLetter(s))
{
values.push(array[variables.indexOf(s)]);
}
}
return values.pop();
}
private int and(int a, int b)
{
if(a == 1 && b == 1)
{
return 1;
}
return 0;
}
private int or(int a, int b)
{
if(a == 0 && b == 0)
{
return 0;
}
return 1;
}
private int not(int a)
{
if(a == 1)
{
return 0;
}
return 1;
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == and)
{
textField.setText(textField.getText() + "(x&y)");
textField.requestFocus(true);
}
if(event.getSource() == or)
{
textField.setText(textField.getText() + "(x+y)");
textField.requestFocus(true);
}
if(event.getSource() == not)
{
textField.setText(textField.getText() + "(!x)");
textField.requestFocus(true);
}
if(event.getSource() == nor)
{
textField.setText(textField.getText() + "!(x+y)");
textField.requestFocus(true);
}
if(event.getSource() == nand)
{
textField.setText(textField.getText() + "!(x&y)");
textField.requestFocus(true);
}
if(event.getSource() == xor)
{
textField.setText(textField.getText() + "(x&(!y))+(((!x)&y))");
textField.requestFocus(true);
}
if(event.getSource() == xnor)
{
textField.setText(textField.getText() + "(x&y)+(((!x)&(!y)))");
textField.requestFocus(true);
}
if(event.getSource() == generate)
{
generate();
}
if(event.getSource() == close)
{
System.exit(0);
}
}
}
}
I need help making this work without the user having to input the brackets correctly themselves (I want the program to fix up the expression, or somehow evaluate it without waiting for a close bracket like I did here).
To test the code and see the errors, input the following when running it:
(x+y) --> runtime error because brackets surround the whole expression
x+y+z --> incorrect output table
x+y --> works
x&y --> works
!!x --> incorrect output table
Please explain this to me. Thanks!
In your generate method you have declared the following thing:
chars = ("(" + textField.getText() + ")").toCharArray();
However, from your GUI there is actually an entry coming with braces, like (x+y) which basically change the value of chars to ((x+y)).
In calculate you pop however on closing ) characters which on the second brace returns an EmptyStackException. If you remove the braces either from the text-fields in general or from the line quoted above your table should print out fine.
Regarding the input-failure at (!!x): You pop only a single operation from the stack ignoring if there are multiple operations available.
As you asked for how to solve your issue that only one operator is used:
You can try to break down an equation like a && b || (c && d) && !e into its own segments and evaluate each term and combine all those terms at the end to a result similar to an earlier post I did which presents a simple rule engine in plain Java. Note however, that I did not guarantee binding-strength correctness nor did I include braces in this sample - therefore its just a very basic demo of a rule engine!
Following OO principley, you could create an Expression class which And, Or, Not, Term, ... are children of and include a boolean evaluate() method which propagates the call down to the respective term and its binding.
The equation from above therefore could be expressed with a more code like approach similar to this f.e:
Expression terms = new Or(
new And(new Term("a", ...), new Term("b", ...)),
new And(new Term("c", ...),
new And(new Term("d", ...), new Not(new Term("e", ...))
)
);
boolean value = terms.evaluate();
To obtain a structure like the one from above, you basically start with an empty stack and iterate through all tokens from the equation. The stack will hold currently open expressions. Therefore, you start by retrieving the first character and decide if it is an operand (( or !) or a letter. If an expression was found you can create a new class representation for it and add it to the stack otherwise create a term object based on the letter and assign the corresponding array[variables.indexOf(s)] value which is either 0 or 1 (false or true) to the term.
Then check if there is an element on the stack (peek will return the topmost element from the stack without removing it) and if so add the term to the operand otherwise store it temporarily so you can add it till you hit the operand and add it thereafter. If an operand has all of its fields filled you need to pop it from the stack and assign it (if not already done) to the new topmost element on the stack. This way you achieve nested structure.
However, you have to also consider the binding-order of operations. A brace binds stronger than an and-operation which further binds stronger than an or-operation. Therefore, on hitting a new operation you also need to check the topmost element on the stack if the binding order is stronger than the binding order of the current element. F.e. while iterating through the sample from above the stack currently holds the And operation for a and b and we are currently processing the Or operation. As this binds weaker than And we need to pop this element from the stack and assign it to the left element of the Or operation and push it onto the stack.
This is similar for braces. However, they can have multiple expressions contained and need to be popped from the stack only if a closing brace was parsed.
I hope this gives you enough insights to continue your journey.
i'm posting a simple game code, written in java. It took my hours today to write this but now i'm stuck! The problem is, in the second level of this game (after failure or success) i can't see the red tiles. It works only the first time.
games logic:
it starts up with a 3x3 matrix and rebound the dimension of this matrix in case of success (testing the ability of memory, memorising the coordinates of red tiles in 1200 ms). So we show the red tiles first, than we check the estimations. If there became a wrong try, failure!. If it is a bigger matrix than 3x3, it gets smaller.
the code is a little bit long but just one class, so it is so easy yo execute it. If you have time i would be appreciate.
So there it goes:
package skeleton;
public class Memory extends JFrame implements ActionListener {
private static final long serialVersionUID = 5963518754230629235L;
private static int minDimX = 3, minDimY = 3;
private static int maxDimX = 15, maxDimY = 15;
private static int counter = 13;
private static int memoriseTime = 1200; // milliseconds
private static int memGridWidthX = 60;
private static int memGridWidthY = 60;
private JPanel centerPanel;
private JButton memTile;
private Random generator;
private int memGridDimX, memGridDimY, coef, numberOfMemTilesToGuess;
int[][] memTileCoordinates;
int[] randomNums;
Border grayBorder = LineBorder.createGrayLineBorder();
public Memory(int xDim, int yDim) {
waitALittleBit(1300);
memGridDimX = xDim;
memGridDimY = yDim;
coef = 3;
numberOfMemTilesToGuess = memGridDimX*memGridDimY / coef;
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(memGridDimY, memGridDimX, 0, 0));
add(centerPanel, BorderLayout.CENTER);
System.out.println("int[" + memGridDimX + "][" + memGridDimY + "] array is created ");
randomNums = new int[numberOfMemTilesToGuess];
for (int i = 0 ; i < numberOfMemTilesToGuess ; i ++) {
System.out.println("> we are in for the "+ (i+1) +". time!");
int randomNum;
boolean randomNumberAlreadySelected = false;
do {
randomNum = calculateARandomNumber(memGridDimX * memGridDimY);
if (i != 0) { //for the first time, we don't need to compare any numbers
randomNumberAlreadySelected = isThisRandomNumberExistInAlreadyFoundRandomNumbersArray(randomNum, randomNums, i);
if (randomNumberAlreadySelected)
System.out.println("######## RECALCULATING RANDOM NUMBER !! ##########");
else
System.out.println("They are not equal, go on!");
}
} while (randomNumberAlreadySelected);
randomNums[i] = (Integer)randomNum;
}
//show the memory tiles
setMemTiles(randomNums, true);
waitALittleBit(memoriseTime);
//hide the memory tiles
setMemTiles(randomNums, false);
}
private int calculateARandomNumber(int limit) {
generator = new Random();
System.out.println("* Calculating random number which is smaller than " + memGridDimX * memGridDimY);
int randomNum = generator.nextInt() % (memGridDimX * memGridDimY);
System.out.println("- Calculated random number: " + randomNum);
if (randomNum < 0) {
System.out.println(".. it is negative, so we add: " + memGridDimX * memGridDimY);
randomNum += memGridDimX * memGridDimY;
}
System.out.println(".. and we add 1 to have a grid array between 1 and 12");
randomNum += 1;
System.out.println(".. and our new random number is: " + randomNum);
return randomNum;
}
private boolean isThisRandomNumberExistInAlreadyFoundRandomNumbersArray(int number, int[] numberArr, int numberArrSize) {
for (int j = 0 ; j < numberArrSize ; j ++) {
System.out.println("# Comparing random number: " + number + " and " + (j+1) + ". random number selected earlier: " + numberArr[j]);
if (number == numberArr[j])
return true;
}
return false;
}
private void setMemTiles(int[] randomNums, boolean showMemTiles) {
centerPanel.removeAll();
memTileCoordinates = new int[randomNums.length][2];
for (int i = 1 ; i <= memGridDimY ; i ++) {
for (int j = 1 ; j <= memGridDimX ; j ++) {
int rnX = -1;
int rnY = -1;
boolean isMemTile = false;
for (int k = 0 ; k < randomNums.length ; k ++) {
int rn = randomNums[k];
if (rn % memGridDimX == 0) {
rnY = rn / memGridDimX;
rnX = memGridDimX;
} else {
rnY = rn / memGridDimX + 1;
rnX = rn % memGridDimX;
}
if (i == 1 && j == 1 && !showMemTiles) { //do it once
System.out.println("********* ************");
System.out.println("Random label number: " + rn + " and it's position in the grid: " + rnX + "," + rnY);
memTileCoordinates[k][0] = rnX;
memTileCoordinates[k][1] = rnY;
System.out.println("> Memory Tiles coordinates: " + memTileCoordinates[k][0] + "," + memTileCoordinates[k][1]);
System.out.println("> Memory Tiles length: " + memTileCoordinates.length);
System.out.println("********* ************");
}
if (rnX == j && rnY == i)
isMemTile = true;
}
memTile = new JButton();
if (isMemTile) {
update(getGraphics());
if (showMemTiles) {
memTile.setBackground(Color.red);
System.out.println("%%%% PAINTING MEM TILES IN RED %%%%");
} else
memTile.setBackground(Color.white);
update(getGraphics());
} else
memTile.setBackground(Color.white);
if (!showMemTiles) // we listen actions after the memory tiles disappears
memTile.addActionListener(this);
centerPanel.add(memTile);
update(getGraphics());
}
}
setJPanelSettings();
}
private void setJPanelSettings() {
setSize(memGridDimX * memGridWidthX, memGridDimY * memGridWidthY);
setTitle("Memory :: " + memGridDimX + "x" + memGridDimY);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
private void waitALittleBit(long waitingMillisSeconds) {
long t0 = System.currentTimeMillis();
long t1 ;
do {
t1 = System.currentTimeMillis();
} while (t1 - t0 < waitingMillisSeconds);
}
public static void main(String[] args) {
new Memory(minDimX,minDimY);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(">>> An action came >>>");
JButton memTile = (JButton) e.getSource();
Dimension size = memTile.getSize();
int chosenMemTileDimX = memTile.getX();
int chosenMemTileDimY = memTile.getY();
int chosenMemTilePosX = chosenMemTileDimX / size.width + 1; // we add 1 becausee we present our tile numbers as 1:1, 1:2, ... ( instead of 0:0,0:1, ... )
int chosenMemTilePosY = chosenMemTileDimY / size.height + 1;
System.out.println("Chosen Tile's x dimension: " + chosenMemTileDimX + " ans y dimension: " + chosenMemTileDimY);
System.out.println("Chosen Tile's width: " + size.width + " and height: " + size.height);
System.out.println("Chosen Tile's coordinates: " + chosenMemTilePosX + ", " + chosenMemTilePosY);
boolean tileIsMemTile = false;
System.out.println("Memory Tiles Coordinates: ");
for (int i = 0 ; i < memTileCoordinates.length ; i ++) {
int memTileDimX = memTileCoordinates[i][0];
int memTileDimY = memTileCoordinates[i][1];
System.out.println("x: " + memTileDimX + ", y: " + memTileDimY);
if (chosenMemTilePosX == memTileDimX && chosenMemTilePosY == memTileDimY)
tileIsMemTile = true;
}
if (tileIsMemTile) {
System.out.println("!!! Right Tile !!!");
memTile.setBackground(Color.red);
numberOfMemTilesToGuess -= 1;
System.out.println("It rest " + numberOfMemTilesToGuess + " tiles to guess");
} else {
System.out.println("!!! Wrong Tile !!!");
Icon falseTileIcon;
try {
falseTileIcon = new ImageIcon(getClass().getResource("wrong.png"));
if (falseTileIcon.getIconHeight() > 0)
memTile.setIcon(falseTileIcon);
} catch (Exception e1) {
memTile.setBackground(Color.black);
}
update(getGraphics()); // good trick!!
waitALittleBit(1000);
//TODO !!! FAILED IN LEVEL MESSAGE !!!
dispose();
if (memGridDimX == minDimX && ( memGridDimY == minDimY || memGridDimY == minDimY + 1))
new Memory(minDimX, minDimY);
else if (memGridDimX == memGridDimY)
new Memory(memGridDimX - 1, memGridDimY);
else
new Memory(memGridDimX, memGridDimY -1);
}
System.out.println(">>> Action processed >>>");
if (numberOfMemTilesToGuess == 0) {
System.out.println("\n END OF THE LEVEL");
System.out.println("Congratulations, you guessed all the tiles without error !! \n");
dispose();
//TODO !!!! SHOW INTERLEVEL INFORMATION !!!!
if (memGridDimX != maxDimX && memGridDimY != maxDimY) {
if (memGridDimX == memGridDimY)
new Memory(memGridDimX, memGridDimY + 1);
else
new Memory(memGridDimX + 1, memGridDimY);
} else
System.out.println("You have a really good memory my friend!");
}
}}
I used update(getGraphics()); many times, it was just for a test...
Thanks in advance.
You where told in your last posting to NOT use the update() method.
do
{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < waitingMillisSeconds);
Also, never use a tight loop like that. Its just as bad as using Thread.sleep(...);
You where given suggestions in your last posting!
I think you can use LWJGL, which is a java game library.
https://www.lwjgl.org
Some of the issues may be due to the thread on which the various bit of code run. The first time through you are running on the "Main" thread, and to be completely correct calls to update the AWT/Swing GUI should be done using the "Event Dispatcher Thread".
The actionPerformed method is called from the "Event Dispatcher Thread" and so then the second time you call into the constructor for Memory you are in this thread.
Also, aside from the fact you have implemented a delay with a spin-loop, which is not efficient; you should not delay the "Event Dispatcher Thread".
See this short overview: http://www.javamex.com/tutorials/threads/swing_ui.shtml