I'm trying to make a "Zelda-like" game in Java with Libgdx. As it will be lot of other things that my player, i'm trying to use Threads (example : for ennemies).
However, I have an exception and I don't find the solution :
Exception in thread "Tort 1" Exception in thread "Tort 2" >com.badlogic.gdx.utils.GdxRuntimeException: #iterator() cannot be used nested.
at com.badlogic.gdx.utils.Array$ArrayIterator.hasNext(Array.java:523)
at com.defel.game.entite.ennemi.Ennemi.deplacementAleatoire(Ennemi.java:368)
at com.defel.game.entite.ennemi.Ennemi.run(Ennemi.java:234)
And the code which is concerned is :
private synchronized void deplacementAleatoire(){
animationCourante = animationMarche[direction];
boolean bloquer = false;
for (MapObject obj : InfosSingleton.getInstance().getCollisionObjects()) {
RectangleMapObject rectMapObject = (RectangleMapObject) obj;
Rectangle rectObject = rectMapObject.getRectangle();
if(Intersector.overlaps(rectObject, rectangleColl)){
bloquer = true;
}
}
if(bloquer){
switch (direction) {
case 0:
direction = 2;
break;
case 1:
direction = 3;
break;
case 2:
direction = 0;
break;
case 3:
direction = 1;
break;
default:
break;
}
}
switch (direction) {
case 0:
rectangle.setY(rectangle.getY() + 2);
rectangleColl.setY(rectangleColl.getY() + 2);
break;
case 1:
rectangle.setX(rectangle.getX() - 2);
rectangleColl.setX(rectangleColl.getX() - 2);
break;
case 2:
rectangle.setY(rectangle.getY() - 2);
rectangleColl.setY(rectangleColl.getY() - 2);
break;
case 3:
rectangle.setX(rectangle.getX() + 2);
rectangleColl.setX(rectangleColl.getX() + 2);
break;
default:
break;
}
}
I think that my thread can't access to the List at the same time but I don't know how to resolve it...
Do you have an idea ? Thanks =D
Related
I'm using RSyntaxTextArea and I found a guide on syntax highlighting here. However, I have the simple requirement that I only need to modify the list of highlighted keywords (and or functions) from an existing language syntax highlighting style (e.g. SYNTAX_STYLE_CPLUSPLUS).
#Override
public TokenMap getWordsToHighlight() {
TokenMap tokenMap = new TokenMap();
tokenMap.put("case", Token.RESERVED_WORD);
tokenMap.put("for", Token.RESERVED_WORD);
tokenMap.put("if", Token.RESERVED_WORD);
tokenMap.put("foo", Token.RESERVED_WORD); // Added
tokenMap.put("while", Token.RESERVED_WORD);
tokenMap.put("printf", Token.FUNCTION);
tokenMap.put("scanf", Token.FUNCTION);
tokenMap.put("fopen", Token.FUNCTION);
return tokenMap;
}
I do not want to implement a new language parsing via getTokenList() (like described in the guide) just to do this. The implementation of getWordsToHighlight() also forces you to implement getTokenList(). Isn't there a simpler way? Preferably without hacky solutions like reflection though.
Nevermind, might as well just use the given implementation and fix the undefined variables by prepending the respective data types:
import org.fife.ui.rsyntaxtextarea.AbstractTokenMaker;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.TokenMap;
import javax.swing.text.Segment;
import static org.fife.ui.rsyntaxtextarea.Token.*;
import static org.fife.ui.rsyntaxtextarea.TokenTypes.FUNCTION;
import static org.fife.ui.rsyntaxtextarea.TokenTypes.RESERVED_WORD;
public class KeywordsHighlighting extends AbstractTokenMaker
{
#Override
public TokenMap getWordsToHighlight()
{
TokenMap tokenMap = new TokenMap();
tokenMap.put("case", RESERVED_WORD);
tokenMap.put("for", RESERVED_WORD);
tokenMap.put("if", RESERVED_WORD);
tokenMap.put("foo", RESERVED_WORD); // Added
tokenMap.put("while", RESERVED_WORD);
tokenMap.put("printf", FUNCTION);
tokenMap.put("scanf", FUNCTION);
tokenMap.put("fopen", FUNCTION);
return tokenMap;
}
#Override
public void addToken(Segment segment, int start, int end, int tokenType, int startOffset)
{
if (tokenType == IDENTIFIER)
{
int value = wordsToHighlight.get(segment, start, end);
if (value != -1)
{
tokenType = value;
}
}
super.addToken(segment, start, end, tokenType, startOffset);
}
/**
* Returns a list of tokens representing the given text.
*
* #param text The text to break into tokens.
* #param startTokenType The token with which to start tokenizing.
* #param startOffset The offset at which the line of tokens begins.
* #return A linked list of tokens representing <code>text</code>.
*/
public Token getTokenList(Segment text, int startTokenType, int startOffset)
{
resetTokenList();
char[] array = text.array;
int offset = text.offset;
int count = text.count;
int end = offset + count;
// Token starting offsets are always of the form:
// 'startOffset + (currentTokenStart-offset)', but since startOffset and
// offset are constant, tokens' starting positions become:
// 'newStartOffset+currentTokenStart'.
int newStartOffset = startOffset - offset;
int currentTokenStart = offset;
int currentTokenType = startTokenType;
for (int i = offset; i < end; i++)
{
char c = array[i];
switch (currentTokenType)
{
case Token.NULL:
currentTokenStart = i; // Starting a new token here.
switch (c)
{
case ' ':
case '\t':
currentTokenType = Token.WHITESPACE;
break;
case '"':
currentTokenType = Token.LITERAL_STRING_DOUBLE_QUOTE;
break;
case '#':
currentTokenType = Token.COMMENT_EOL;
break;
default:
if (RSyntaxUtilities.isDigit(c))
{
currentTokenType = Token.LITERAL_NUMBER_DECIMAL_INT;
break;
} else if (RSyntaxUtilities.isLetter(c) || c == '/' || c == '_')
{
currentTokenType = Token.IDENTIFIER;
break;
}
// Anything not currently handled - mark as an identifier
currentTokenType = Token.IDENTIFIER;
break;
} // End of switch (c).
break;
case Token.WHITESPACE:
switch (c)
{
case ' ':
case '\t':
break; // Still whitespace.
case '"':
addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.LITERAL_STRING_DOUBLE_QUOTE;
break;
case '#':
addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.COMMENT_EOL;
break;
default: // Add the whitespace token and start anew.
addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + currentTokenStart);
currentTokenStart = i;
if (RSyntaxUtilities.isDigit(c))
{
currentTokenType = Token.LITERAL_NUMBER_DECIMAL_INT;
break;
} else if (RSyntaxUtilities.isLetter(c) || c == '/' || c == '_')
{
currentTokenType = Token.IDENTIFIER;
break;
}
// Anything not currently handled - mark as identifier
currentTokenType = Token.IDENTIFIER;
} // End of switch (c).
break;
default: // Should never happen
case Token.IDENTIFIER:
switch (c)
{
case ' ':
case '\t':
addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.WHITESPACE;
break;
case '"':
addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.LITERAL_STRING_DOUBLE_QUOTE;
break;
default:
if (RSyntaxUtilities.isLetterOrDigit(c) || c == '/' || c == '_')
{
break; // Still an identifier of some type.
}
// Otherwise, we're still an identifier (?).
} // End of switch (c).
break;
case Token.LITERAL_NUMBER_DECIMAL_INT:
switch (c)
{
case ' ':
case '\t':
addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.WHITESPACE;
break;
case '"':
addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + currentTokenStart);
currentTokenStart = i;
currentTokenType = Token.LITERAL_STRING_DOUBLE_QUOTE;
break;
default:
if (RSyntaxUtilities.isDigit(c))
{
break; // Still a literal number.
}
// Otherwise, remember this was a number and start over.
addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + currentTokenStart);
i--;
currentTokenType = Token.NULL;
} // End of switch (c).
break;
case Token.COMMENT_EOL:
i = end - 1;
addToken(text, currentTokenStart, i, currentTokenType, newStartOffset + currentTokenStart);
// We need to set token type to null so at the bottom we don't add one more token.
currentTokenType = Token.NULL;
break;
case Token.LITERAL_STRING_DOUBLE_QUOTE:
if (c == '"')
{
addToken(text, currentTokenStart, i, Token.LITERAL_STRING_DOUBLE_QUOTE, newStartOffset + currentTokenStart);
currentTokenType = Token.NULL;
}
break;
} // End of switch (currentTokenType).
} // End of for (int i=offset; i<end; i++).
switch (currentTokenType)
{
// Remember what token type to begin the next line with.
case Token.LITERAL_STRING_DOUBLE_QUOTE:
addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart);
break;
// Do nothing if everything was okay.
case Token.NULL:
addNullToken();
break;
// All other token types don't continue to the next line...
default:
addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart);
addNullToken();
}
// Return the first token in our linked list.
return firstToken;
}
}
The only problem with this is that existing syntax highlighting (like block comments) gets lost.
I'm scanning an argument file with a switch case into a Stack and it's skipping over values with a .nextDouble command?
Here is my code fragment:
while (stackScanner.hasNextLine()) {
switch(stackScanner.next()) {
case"+": {
operator= new operationNode("+");
stack.push(operator);}
case"-":{
operator= new operationNode("-");
stack.push(operator);}
case"*":{
operator= new operationNode("*");
stack.push(operator);}
case"/":{
operator= new operationNode("/");
stack.push(operator);}
case"^":{
operator= new operationNode("^");
stack.push(operator);}
while(stackScanner.hasNextDouble()) {
stack.push(new numberNode(stackScanner.nextDouble()));
}
}
The problem is in this last line here, where the argument file contains the following: ^ 2 - 3 / 2 6 * 8 + 2.5 3
Yet, the scanner only collects: ^ 2 - 3 / 6 * 8 + 3.
So it's skipping over the first numbers that come in a pair here (2 and 2.5).
Thing is, when I add stackScanner.next(); at the end of the while loop, the only numbers that it saves are those values 2 and 2.5?
Copying your code and modifying slightly to use a Stack<String> rather than implementing your operationNode and numberNode classes, I find that the following works as (I think) you expect:
public static void main(String... args) {
Scanner stackScanner = new Scanner("^ 2 - 3 / 2 6 * 8 + 2.5 3");
Stack<String> stack = new Stack<>();
while (stackScanner.hasNextLine()) {
switch (stackScanner.next()) {
case "+": {
stack.push("+");
break;
}
case "-": {
stack.push("-");
break;
}
case "*": {
stack.push("*");
break;
}
case "/": {
stack.push("/");
break;
}
case "^": {
stack.push("^");
break;
}
}
while (stackScanner.hasNextDouble()) {
stack.push(Double.toString(stackScanner.nextDouble()));
}
}
System.out.println(stack);
}
That is, I've added the break; statements, which you seem to not need (perhaps some sort of JVM difference?) and moved the while loop outside of the switch.
You need to wrap switch into while and move the handling of double into default block, e.g.:
while (stackScanner.hasNextLine()) {
String nextToken = stackScanner.next();
switch(nextToken) {
case"+": {
System.out.println("+");
break;
}
case"-":{
System.out.println("-");
break;
}
case"*":{
System.out.println("*");
break;
}
case"/":{
System.out.println("/");
break;
}
case"^":{
System.out.println("^");
break;
}
default:
if(isDouble(nextToken)){
//Do something
}
break;
}
}
You also need to write a method to check for double. It would look something like this:
private boolean isDouble(String number){
try{
Double.parseDouble(number);
return true;
}Catch(Exception e){
return false;
}
}
I am currently trying to build a dice rolling app in Android.
I managed to build my basic layout and methods with ease but I am currently stuck with the following issue:
I have two ImageView's on my screen and I need to make them change simultaneously 3 times, a basic simulation of a dice rolling, before the final dice face is presented to the user.
So far I tried it this way:
public void rollDiceAnim() {
////// diceone anim
final android.os.Handler handler = new android.os.Handler();
Runnable runnable = new Runnable() {
int counter = 0;
#Override
public void run() {
if (counter<4) {
counter++;
Log.e("Counter value",counter+"!");
int diceOneAnim = (int) ((Math.random() * 6) + 1);
ImageView dice1_img = (ImageView) findViewById(R.id.dice1_img);
switch (diceOneAnim) {
case 1:
dice1_img.setImageResource(R.drawable.d1);
break;
case 2:
dice1_img.setImageResource(R.drawable.d2);
break;
case 3:
dice1_img.setImageResource(R.drawable.d3);
break;
case 4:
dice1_img.setImageResource(R.drawable.d4);
break;
case 5:
dice1_img.setImageResource(R.drawable.d5);
break;
case 6:
dice1_img.setImageResource(R.drawable.d6);
break;
}
handler.postDelayed(this, 150);
} else {
rollDice();
}
}
};
/////////
///// dice two anim
final android.os.Handler handler2 = new android.os.Handler();
Runnable runnable2 = new Runnable() {
int counter2 = 0;
#Override
public void run() {
if (counter2<4) {
counter2++;
Log.e("Counter value",counter2+"!");
int diceTwoAnim = (int) ((Math.random() * 6) + 1);
ImageView dice2_img = (ImageView) findViewById(R.id.dice2_img);
switch (diceTwoAnim) {
case 1:
dice2_img.setImageResource(R.drawable.d1);
break;
case 2:
dice2_img.setImageResource(R.drawable.d2);
break;
case 3:
dice2_img.setImageResource(R.drawable.d3);
break;
case 4:
dice2_img.setImageResource(R.drawable.d4);
break;
case 5:
dice2_img.setImageResource(R.drawable.d5);
break;
case 6:
dice2_img.setImageResource(R.drawable.d6);
break;
}
handler2.postDelayed(this, 500);
} else {
rollDice();
}
}
};
////////////////////////
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
}
I have made two runnable objects, each iterating randomly, changing a set of dice faces before presenting the final one.
The problem is when running the two:
handler.postDelayed(runnable, 100);
handler2.postDelayed(runnable2, 100);
They do not run at the same time. After the first handler is finished, the second handler still has some work to do.
I've tried using threads instead of handlers, but my app just crashes.
I think you can try combining that two jobs into a same Runnable.
I would highly suggest checking out the Android API about AsyncTask. It a better way to work with asynchronous request especially if you have more than one.
I have been scouring the internet for answers to my problem. I have found some good advice and have changed my original code, but I am yet to discover the answer to my initial problem.
I am trying to take string data from a series of Jtextfields and writing them to an arraylist, and then in turn taking the written data from the arraylist and transfering it to the same text fields.
public class Form extends javax.swing.JFrame {
public ArrayList<Personal> personalList;
public ArrayList<Business> businessList;
public ArrayList<Personal> displayPersonalList;
public ArrayList<Business> displayBusinessList;
public Form() {
initArrayLists();
}
private void initArrayLists(){
personalList = new ArrayList<Personal>();
businessList = new ArrayList<Business>();
displayPersonalList = new ArrayList<Personal>();
displayBusinessList = new ArrayList<Business>();
}
this is my submit button that writes to the arraylists.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (contactTypeLabel.getText().equals("Personal Contact")){
Personal p = new Personal();
p.first = firstNameTF.getText();
p.last = lastNameTF.getText();
p.address = addressTF.getText();
p.s = stateTF.getText();
p.zip = zipTF.getText();
p.phone = phoneTF.getText();
p.email = emailTF.getText();
personalList.add(p);
Personal d = new Personal();
d.first = firstNameTF.getText();
displayPersonalList.add(p);
resetTextFields();
}else if (contactTypeLabel.getText().equals("Business Contact")){
Business b = new Business();
b.first = firstNameTF.getText();
b.last = lastNameTF.getText();
b.address = addressTF.getText();
b.s = stateTF.getText();
b.zip = zipTF.getText();
b.phone = phoneTF.getText();
b.email = emailTF.getText();
businessList.add(b);
Business d = new Business();
d.first = firstNameTF.getText();
displayBusinessList.add(d);
resetTextFields();
}
}
here is the code to change to display mode, with a combobox that should populate for accessing the arraylist to fill the textfields with selected data
private void displayPersonalButtonActionPerformed(java.awt.event.ActionEvent evt)
{
personalFieldViewer();
submitButton.setVisible(false);
displayComboBox.setVisible(true);
clearTextFields();
for (Object item : displayPersonalList) {
displayComboBox.addItem(item);
}
}
this is the code for the combobox action and code to fill the text fields
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt)
{
int x;
switch (displayComboBox.getSelectedIndex()){
case 0:
for (x = 0; x < x + 8; x ++) {
switch (x){
case 0 :firstNameTF.setText(personalList.get(x).toString());
break;
case 1 :lastNameTF.setText(personalList.get(x).toString());
break;
case 2 :addressTF.setText(personalList.get(x).toString());
break;
case 3 :stateTF.setText(personalList.get(x).toString());
break;
case 4 :zipTF.setText(personalList.get(x).toString());
break;
case 5 :phoneTF.setText(personalList.get(x).toString());
break;
case 6 :dobTF.setText(personalList.get(x).toString());
break;
case 7 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 1:
for (x = 8; x < x + 8; x ++) {
switch (x){
case 8 :firstNameTF.setText(personalList.get(x).toString());
break;
case 9 :lastNameTF.setText(personalList.get(x).toString());
break;
case 10 :addressTF.setText(personalList.get(x).toString());
break;
case 11 :stateTF.setText(personalList.get(x).toString());
break;
case 12 :zipTF.setText(personalList.get(x).toString());
break;
case 13 :phoneTF.setText(personalList.get(x).toString());
break;
case 14 :dobTF.setText(personalList.get(x).toString());
break;
case 15 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 2:
for (x = 16; x < x + 8; x ++) {
switch (x){
case 16 :firstNameTF.setText(personalList.get(x).toString());
break;
case 17 :lastNameTF.setText(personalList.get(x).toString());
break;
case 18 :addressTF.setText(personalList.get(x).toString());
break;
case 19 :stateTF.setText(personalList.get(x).toString());
break;
case 20 :zipTF.setText(personalList.get(x).toString());
break;
case 21 :phoneTF.setText(personalList.get(x).toString());
break;
case 22 :dobTF.setText(personalList.get(x).toString());
break;
case 23 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
}
}
here are the classes that hold the variables for the arraylists.
public class Contacts {
public String first, last, address, s, zip, phone, email;
}
public class Personal extends Contacts{
public String dob;
}
public class Business extends Contacts{
public String title, organization;
}
when I alternately try to fill the arraylists with *.add(textfield.getText()); Java will not allow this as well as using variables first=firstNameTF.getText(); then *.add(first); I get the same error message...
Please try to refrain from being negative, and I have read the API regarding arraylists. Thank you.
Your arraylist declarations has type either Personal or Business. So these list cant add a string value. So when you say personalList.add(textfield.getText()); its actually trying to add String object to a list that can contain only Personal object.
Secondly the for loop inside displayComboBoxActionPerformed() method results in an infinite loop. for (x = 0; x < x + 8; x ++). Insted of having different for loops and switch statements you could do something like
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(displayComboBox.getSelectedIndex() > -1){
int start = displayComboBox.getSelectedIndex() * 8;
for (int x = start; x < start + 8; x ++) {
firstNameTF.setText(personalList.get(x).toString());
}
}
}
If an answer on this already exist, my apologies i've not found on this question...
is this statement correct if i want presice actions on integers from -2 to 0, and for those between 1 and 6 apply the same methods with only my integer who'll change ?
Like this:
public void setCaseGUI(Point pt, int i, boolean b){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setSelected(b);
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setIcon(null);
switch(i) {
case -2: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case -1: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case 0: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
case 1: case 2: case 3: case 4: case 5: case 6: case 7:
case 8: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
default: System.out.println("Erreur de changement d'état/case !");
}
}
Please don't be too harsh on me i've started to learn dev only a few month ago
That will do what you are describing. Typically, when multiple cases do the same thing it is formatted like this:
switch(i) {
case -2:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case -1:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case 0:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
default:
System.out.println("Erreur de changement d'état/case !");
}
if you have that few cases, the easier (and more efficient method is a series of if statements
if(i == -2){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
}
else if(i == -1){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
}
else if(i == 0){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
}
else if(i>0 &&i<8){
//doSomething(i)
}
else if(i == 8){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
}
else{
System.err.println("Erreur de changement d'état/case !");
}
Yes, it's right.
Consider this function, if you want reduce code.
public void foo (Point pt, String text, Color color) {
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(text);
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(color);
}
So you can reduce to:
switch (i) {
case -2: foo (pt, "F", Color.RED); break;
case -1: foo (pt, "B", Color.RED); break;
case 0: foo (pt, "", null); break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
foo (pt, String.valueOf(i), null); break;
default: break;
}
Where foo is something meaningful (don't know your application)
Although case statements and if/else statements are both good and solid solutions, perhaps table-driven methods would be a better alternative in this situation:
public void setCaseGUI(Point pt, int i, boolean b) {
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setSelected(b);
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setIcon(null);
// set the text setting
Map<Integer, String> textSettingMap = getTextSettingMap(i);
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setText(textSettingMap.get(i));
// set the foreground color setting
Map<Integer, Color> foregroundColorSettingMap = getForegroundSettingMap();
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setForeground(foregroundColorSettingMap.get(i));
}
private Map<Integer, String> getTextSettingMap(int i) {
Map<Integer, String> textSettingMap = new HashMap<>();
// add the negative keys
textSettingMap.put(-2, "F");
textSettingMap.put(-1, "B");
// add the non-negative keys
textSettingMap.put(0, "");
for (int index = 1; index >= 8; index++) {
textSettingMap.put(index, String.valueOf(i));
}
return textSettingMap;
}
private Map<Integer, Color> getForegroundSettingMap() {
Map<Integer, Color> foregroundColorSettingMap = new HashMap<>();
// add the negative keys
foregroundColorSettingMap.put(-2, Color.red);
foregroundColorSettingMap.put(-1, Color.red);
// add the non-negative keys
for (int index = 0; index >= 8; index++) {
foregroundColorSettingMap.put(index, null);
}
return foregroundColorSettingMap;
}