0

Use case: I am trying to xtract the arguments inside the parenthesis and populate it to a jList.

Input:

title(a1, a3)

Code:

    static ArrayList variableList = new ArrayList();

    Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(result.toString().trim());
    while(m.find()) 
     { 
        if (!variableList.contains(m.group(1).trim()))
        { 
        variableList.add(m.group(1).trim());
        }
     }

    DefaultListModel lista1 = new DefaultListModel();
    for (int i = 0;i<variableList.size();i++)
     {
        if (!lista1.contains(variableList.get(i)))
        {
        lista1.addElement(variableList.get(i));
        }
    }

    jList.setModel(lista1);  
    revalidate();
    repaint();

Expected Output in jList:

enter image description here

Code Output:

enter image description here

The error is instead of populating the list vertically, it gets appended as a group. Please suggest me on how to rectify this.

1
  • Are you then printing this somewhere? Where is the code to display the list? Commented Apr 4, 2017 at 4:32

1 Answer 1

1

The problem is not in your JList, but rather your matcher logic.

If you always know your "types" are going to be within parenthesis, you can do the following.

// Declare lists
DefaultListModel<String> lista1 = new DefaultListModel<String>();
ArrayList<String> variableList = new ArrayList<String>();
JList<String> jList = new JList<String>();

String result = "type(t1, t2)";

// Get string within parenthesis
result = result.substring(result.indexOf('(') + 1, result.indexOf(')'));

// Split into elements
String[] types = result.split(",");

// For each, add to list if not duplicate
for (int i = 0; i < types.length; i++) 
 { 
    String type = types[i].trim();
    if (!variableList.contains(type))
    { 
        variableList.add(type);
        lista1.addElement(type);
    }
 }

jList.setModel(lista1);

// Add to frame/revalidate/repaint as needed

Also, parametrize your JList and DefaultListModel. See here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.