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.
Related
In teaching myself Android programming (using Android Studio) I am working on a basic calculator app. My eval method uses Dijkstra's shunting-yard algorithm to parse a string expression and calculate the result. I got the idea for this from this SO question.
The code for my Evaluator class is as follows:
class Evaluator {
private static Evaluator instance = new Evaluator();
private Stack< String > mOperators;
private Stack< Double > mOperands;
public static Evaluator getInstance() {
return instance;
}
private Evaluator() {
mOperands = new Stack< Double >();
mOperators = new Stack< String >();
}
public Double eval( String expression ) {
Stack stack = convertExpressionToStack( expression );
buildOperationStacks( stack );
return doEval();
}
private Double doEval() {
while ( !mOperators.isEmpty() ) {
String op = mOperators.pop();
Double v = mOperands.pop();
switch ( op ) {
case "+":
v = mOperands.pop() + v;
break;
case "-":
v = mOperands.pop() - v;
break;
case "*":
v = mOperands.pop() * v;
break;
case "/":
v = mOperands.pop() / v;
break;
}
mOperands.push( v );
}
return mOperands.pop();
}
private void buildOperationStacks( Stack stack ) {
while ( !stack.isEmpty() ) {
String s = ( String ) stack.pop();
switch ( s ) {
case "+":
case "-":
case "*":
case "x":
case "X":
case "/":
case "÷":
if ( s.equals( "x" ) || s.equals( "X" ) ) {
s = "*";
} else if ( s.equals( "÷" ) ) {
s = "/";
}
mOperators.push( s );
break;
default:
try {
if ( !stack.isEmpty() && stack.peek().equals ( "." ) ) {
s += stack.pop();
s += stack.pop();
}
mOperands.push( Double.parseDouble( s ) );
} catch ( Exception e ) {
Log.e( "Error", e.getMessage() );
}
}
}
}
private Stack convertExpressionToStack( String expression ) {
Stack< String > s = new Stack< String >();
for ( char c : expression.toCharArray() ) {
s.push( String.valueOf( c ) );
}
return s;
}
}
So my issue is in the doEval method. When I pop the elements off each stack I am getting the first elements added to each stack. I was of the impression that stacks were a First In Last Out structure.
So what might I be doing wrong? Do I need to somehow reverse each stack?
Thank you.
EDIT
So for example, I input 5+3*2. I would expect the execution to be
pass 1: value1 = 2, Operator1 = *, value2 = 3 result = 6
pass 2: Value1 = 6 (result of pass 1) Operator1 = +, value2 = 5 result = 11
However, when I debug this, I am seeing:
pass 1: value1 = 5, Operator1 = +, value2 = 3, result = 8
pass 2: value1 = 8 (result of pass 1), operator1 = *, value2 = 2, result = 16
Your convertExpressionToStack() method is building an operand stack in the correct order, and then your buildOperstionStack() method is inverting it, by popping one and pushing the other.
You don't really need this second method anyway: just change the evaluation method to understand x as multiplication, etc.
Your understanding of Stack is correct. It's First In, Last Our or Last In, First Out.
About your code:
while ( !mOperators.isEmpty() ) {
String op = mOperators.pop();
Double v = mOperands.pop();
switch ( op ) {
case "+":
v = mOperands.pop() + v;
break;
case "-":
v = mOperands.pop() - v;
break;
case "*":
v = mOperands.pop() * v;
break;
case "/":
v = mOperands.pop() / v;
break;
}
mOperands.push( v );
}
Since, you have not mentioned, how exactly is it behaving, so, let me explain. Suppose, mOperators has +,- where + was added first and - on top of +
mOperands has 3,6,2,1
This is how your code will and should behave.
For the first iteration of while loop:
op = -
v = 1
v = 2-1 = 1 // since it's a -
mOperands is now: 3,6
and after call, mOperands.push(v), since v now is 1, your mOperands will be:
3,6,1
Second iteration of while loop:
op = +
v = 1
v = 6+1 = 7 // since op is +
Your mOperands now looks like: 3
And once it breaks from switch, it will make mOperands as:
3,7
P.S: You should debug your application to see values of mOperands at each and every step to get better idea, why it's behaving like it is.
In short, the user will input a number (say 1 through 3). This will decide which range of numbers the loop should search through.
switch(input){
case 1:
searchTerm = "i<10 && i>5";
case 2:
searchTerm = "i>=10 && i<19";
case 3:
searchTerm = "i>19 && i<24";
}
while(searchTerm){
//some function
}
Is this possible? I I've not been able to find a way to use a string as search parameters.
EDIT: I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters? For example:
case 1:
searchTerm = "i<5"
case 2:
searchTerm = "i>25 && i<29"
case 3:
searchTerm = "(i<50 && i>25) && (i>55 && i<75)"
case 4:
searchTerm = "(i<20 && i>15) && (i>300 && i<325) && (i>360 && i<380)
Then how does one do it? Multiple loops that call the same function?
The correct way to do this is to not use a string at all:
int min, max;
switch(input){
case 1: // i<10 && i>5
min = 6;
max = 10;
break; // to avoid follow-through to the next case
case 2: // i>=10 && i<19
min = 10;
max = 20;
break;
case 3: // i>19 && i<24
min = 20;
max = 25;
break;
default:
// You need something here in case the value entered wasn't 1-3
}
for (int i = min; i < max; ++i) {
// ...
}
Re your edit:
I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters?
In that case, you'll have to use an expression evaluator (or write one, which is a non-trivial task). There's one in Spring, for instance (not recommending, just happened to hear about it). A search for "Java expression evaluator" should turn up some options.
Another alternative, which is somewhat amusing given that some folks mistook your question for a JavaScript question, is to use the JavaScript evaluator built into Java (either Rhino or Nashorn). E.g.: Live Example
import javax.script.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String searchTerm = "i >= 19 && i <= 24";
int i;
try {
i = 19;
engine.put("i", i);
while ((boolean)engine.eval(searchTerm)) {
System.out.println("i = " + i);
++i;
engine.put("i", i);
}
System.out.println("Done");
} catch (ScriptException scriptException) {
System.out.println("Failed with script error");
}
}
}
...but you'll still have the problem of determining what initial value to use for i, which I've hardcoded above.
In Java 8 you can select a lambda instead of String:
Predicate<Integer> searchTerm = (Integer v) -> false;
switch (input) {
case 1:
searchTerm = (Integer v) -> v < 10 && v > 5;
break;
case 2:
searchTerm = (Integer v) -> v >= 10 && v < 19;
break;
case 3:
searchTerm = (Integer v) -> v > 19 && v < 24;
break;
}
while (searchTerm.test(i)) {
...
}
You can create an enumeration as below.
public enum SearchTerms {
None(""),
Between6And9("i<10 && i>5"),
Between10And18("i>=10 && i<19"),
Between20And23("i>19 && i<24");
private final String stringValue;
SearchTerms(String stringValue) {
this.stringValue = stringValue;
}
public String getStringValue() {
return stringValue;
}
public static SearchTerms fromStringValue(String stringValue) {
for (SearchTerms searchTerm : values()) {
if (searchTerm.getStringValue().equalsIgnoreCase(stringValue)) {
return searchTerm;
}
}
return SearchTerms.None;
}
}
Usage:
SearchTerms searchTerm = SearchTerms.fromStringValue("i<10 && i>5");
switch(searchTerm) {
case Between6And9:
//dosomething
break;
}
You can use .eval() of JavaScript.
Also don't forget break; at the end of each case:
Check out this fiddle.
Here is the snippet.
function test(input, i) {
switch (input) { //input=1
case 1:
searchTerm = "i<10 && i>5"; //this will be 'searchTerm'
break;
case 2:
searchTerm = "i>=10 && i<19";
break;
case 3:
searchTerm = "i>19 && i<24";
break;
}
while (eval(searchTerm)) { //'searchTerm' converted to boolean expression
alert(i); // alert for i=7,8,9
i++;
}
}
test(1, 7); //pass input=1 and i=7
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
This program reads from a file and types its contents out line by line or at the ends of sentences depending on config settings. It uses Java.awt.Robot to do this, and all the keyboard characters can be typed except the apostrophe and quotation characters. The key is function on my keyboard and other scripts can type it. I can't figure out why this program cannot type it correctly.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class SmartRobot extends Robot {
public int count70=0;
public SmartRobot() throws AWTException {
super();
}
public void keyType(int keyCode) {
if(keyCode == -1)
return;
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
}
public void keyType(int keyCode, int keyCodeModifier) {
keyPress(keyCodeModifier);
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
keyRelease(keyCodeModifier);
}
public void type(String text) {
if(text.length()>1 && text.substring(0, 1).equals("\\")){
Driver.codeTimeEnd = System.nanoTime();
delay(Integer.parseInt(text.substring(2, text.length()))-(int) (Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
String textUpper = text.toUpperCase();
for (int i=0; i<text.length(); ++i) {
typeChar(textUpper.charAt(i));
}
if(!Driver.enterAtPeriods || !Driver.enterUnder60)keyPress(KeyEvent.VK_ENTER);
Driver.codeTimeEnd = System.nanoTime();
if(!Driver.enterUnder60)
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd- Driver.codeTimeStart)/1000000000);
else
delay(2);
}
public void typeChar(char c) {
boolean shift = true;
int keyCode;
switch (c) {
case '~':keyCode = (int)'`';break;
case '!':keyCode = (int)'1';break;
case '#':keyCode = (int)'2';break;
case '#':keyCode = (int)'3';break;
case '$':keyCode = (int)'4';break;
case '%':keyCode = (int)'5';break;
case '^':keyCode = (int)'6';break;
case '&':keyCode = (int)'7';break;
case '*':keyCode = (int)'8';break;
case '(':keyCode = (int)'9';break;
case ')':keyCode = (int)'0';break;
case ':':keyCode = (int)';';break;
case '_':keyCode = (int)'-';break;
case '+':keyCode = (int)'=';break;
case '|':keyCode = (int)'\\';break;
case '"':keyCode = (int)'\'';break;
case '?':keyCode = (int)'/';break;
case '{':keyCode = (int)'[';break;
case '}':keyCode = (int)']'; break;
case '<':keyCode = (int)',';break;
case '>':keyCode = (int)'.';break;
case '“':keyCode = (int)'\'';break;
case '”':keyCode = (int)'\'';break;
case '…':keyCode = (int)' ';break;
case '‘':keyCode = (int)'\'';break;
case '’':keyCode = (int)'\'';break;
default:
// System.out.println(c);
keyCode = (int)c;
// System.out.println(keyCode);
shift = false;
}
if(Driver.enterUnder60){
count70++;
if(count70>70)
if(c == ' '){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if(Driver.enterAtPeriods){
if(c == '.'){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if (shift){
keyType(keyCode, KeyEvent.VK_SHIFT);
System.out.println("works");
}
else
keyType(keyCode);
}
private int charToKeyCode(char c) {
switch (c) {
case ':':
return ';';
}
return (int)c;
}
}
The infile can be whatever you want it to be, and all characters will be shown, but the " will not be typed. I don't know if the type() method is ever accessed in its case.
Here is an example input:
"Hi, my name is koikoi."
The output comes out like this:
Hi, my name is koikoi.
When it should have the quotations on it. The typer does not recognize/read them. I can't find any flaws in my code and would like some advice. I can add the main method if requested.
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());
}
}
}