Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Might be a thread leak problem reading a file into an Array list.

  1. #1
    Junior Member rushtonjj's Avatar
    Join Date
    Jun 2012
    Posts
    2
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Might be a thread leak problem reading a file into an Array list.

    Hi,

    I am new to this forum. I'm also new to Java. I have a coder I am working with and I'm intergrating my reports to his application. When I go to returnReportData() my application fails when it is reading my .\\MECL_1.cvs. We are using a | separator because we are dealing with a legacy system that allows our users to put in commas and other extraneous characters. My coder provided me this code. It works fine on his system, but I cannot figure out why it is breaking on mine. We are using the same files. The main part of the application reads in a very large csv file, then a record or many records are passed for me to print, but we have to append more data onto those records so that the address can be added to a report.

    Here is my error:

    There is more, but those errors are symptomatic of this larger one. It seems pretty cut and dry, but you will see that the index is well over 11, its 25. And my file has plenty of columns. Its ludicris that this is not working for me, but works for him.

    If someone could have a look and tell me what you think I would appreciate it... I'm working the weekend so I can get this resolved. We have a deadline for next week.


    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 11
    at PCQ.SearchTest.returnReportData(SearchTest.java:86 7)
    at PCQ.SearchTest$3.actionPerformed(SearchTest.java:2 29)

    Here is my code:

    //SEARCH TEST BACKUP - HEAP SOLVED
    package PCQ;

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Point2D;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.LineNumberReader;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.regex.Pattern;

    import javax.print.attribute.AttributeSetUtilities;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;






    public class SearchTest implements ListSelectionListener, TableModelListener//, ActionListener
    {
    //Main Table Object
    JTable table;
    MyModel model;
    TextFieldPanel tfPanel;
    ArrayList<String> filtered;
    int [] filteredRows;
    ArrayList<String> toUse;

    int selRows;
    int row;
    int row2;
    RowFilter<TableModel, Object> svclabf = null;
    RowFilter<TableModel, Object> custf = null;
    RowFilter<TableModel, Object> modf = null;
    RowFilter<TableModel, Object> serialf = null;
    RowFilter<TableModel, Object> ecnf = null;
    RowFilter<TableModel, Object> subcustf = null;


    JLabel jlbPicture;
    String reportType = "Metcal_Form";
    RadioListener myListener = null;

    public TableRowSorter<TableModel> sorter ;


    //Search Field - Basic (Test)
    JTextField textField;

    //Test Sorter Field

    JTextField svclabt;
    JTextField custt;
    JTextField modt;
    JTextField serialt;
    JTextField ecnt;
    JTextField subcustt;

    TransparentButton mcb = new TransparentButton("Print Menu");
    TransparentButtonW print = new TransparentButtonW("PRINT", Color.WHITE);
    TransparentButton metcb = new TransparentButton("Get MetCal Form(s)");
    TransparentButton clearmc = new TransparentButton("Clear Print Selection");
    TransparentButton filter = new TransparentButton("Filter");
    JButton refresh = new JButton("Refresh Filter");
    TransparentButton all = new TransparentButton("Select All");

    //Search Function - Complete

    JButton bs;
    JCheckBox cECN;
    JCheckBox cCust;
    JCheckBox cMod;
    JCheckBox cSer;
    JCheckBox cNom;
    JCheckBox cSubCust;
    JTextField tECN;
    JTextField tCust;
    JTextField tMod;
    JTextField tSer;
    JTextField tNom;
    JTextField tSubCust;

    //Text Fields for Detail Tab: Key Fields
    JTextField dtECN;
    JTextField dtCust;
    JTextField dtMod;
    JTextField dtSer;
    JTextField dtNom;

    //Text Fields for Detail Tab: Auxiliary Fields

    JTextField dtMFR;
    JTextField dtPARTOF;
    JTextField dtSUBCUST;
    JTextField dtSCHEDLAB;
    JTextField dtSCAT;
    JTextField dtNSN;
    JTextField dtPLANTACCT;
    JTextField dtAPPRPROC;
    JTextField dtSVCLAB;
    JTextField dtMETCYCLE;
    JTextField dtPHASE;
    JTextField dtDTCOMPL;
    JTextField dtDTLASTSER;
    JTextField dtSERVLBL;
    JTextField dtDTNEXTDUE;
    JTextField dtSTATUS;
    JTextField dtONSITE;
    JTextField dtSHOP;
    JTextField dtWLNHRS;
    JTextField dtCLASSSTD;
    JTextField dtCALSTD;


    public SearchTest() throws IOException
    {

    tfPanel = new TextFieldPanel();

    table = getTable();
    table.setOpaque(false);

    //refresh.setForeground(Color.WHITE);
    final Color alphaZero = new Color(0, true);
    refresh.setBackground(alphaZero);
    refresh.setOpaque(false);
    refresh.setContentAreaFilled(true);

    //Search Function - Complete
    //Color bg = new Color(210, 222, 242);
    Color bg = new Color(224, 242, 252);
    bs = new JButton(" Search ");
    refresh.setToolTipText("Filter Table View for Current Selection");
    mcb.setToolTipText("Enter Print Menu for Current PRINT Checkbox Selection");
    metcb.setToolTipText("Get MetCal Form(s) for Current PRINT Selection");
    clearmc.setToolTipText("Clear the Current PRINT Selection");
    filter.setToolTipText("Filter Data");
    all.setToolTipText("Print Entire Current Filtered Selection");
    svclabt = new JTextField(10); svclabt.setBackground(bg); svclabt.setToolTipText("Filter by Servicing Lab");
    custt = new JTextField(10); custt.setBackground(bg); custt.setToolTipText("Filter by Customer Code");
    modt= new JTextField(10); modt.setBackground(bg); modt.setToolTipText("Filter by Model Number");
    serialt = new JTextField(10); serialt.setBackground(bg); serialt.setToolTipText("Filter by Serial Number");
    ecnt = new JTextField(10); ecnt.setBackground(bg); ecnt.setToolTipText("Filter by Equipment Control Number");
    subcustt = new JTextField(10); subcustt.setBackground(bg); subcustt.setToolTipText("Filter by Sub Custodian");

    cECN = new JCheckBox("ECN:");
    cCust = new JCheckBox("CUSTOMER:");
    cMod = new JCheckBox("MODEL:");
    cSer = new JCheckBox("SERIAL:");
    cNom = new JCheckBox("NOMENCLATURE:");
    cSubCust = new JCheckBox("SUB CUSTODIAN:");
    tECN = new JTextField(10);
    tCust = new JTextField(10);
    tMod = new JTextField(10);
    tSer = new JTextField(10);
    tNom = new JTextField(10);
    tSubCust = new JTextField(10);


    textField = new JTextField();
    textField.setBackground(bg);

    //Detail Tab - Key Field Text Boxes

    dtECN = new JTextField(15); dtECN.setEditable(false); dtECN.setBackground(bg);
    dtCust = new JTextField(15); dtCust.setEditable(false); dtCust.setBackground(bg);
    dtMod = new JTextField(15); dtMod.setEditable(false); dtMod.setBackground(bg);
    dtSer = new JTextField(15); dtSer.setEditable(false); dtSer.setBackground(bg);
    dtNom = new JTextField(15); dtNom.setEditable(false); dtNom.setBackground(bg);


    //Detail Tab - Auxiliary Field Text Boxes
    dtMFR = new JTextField(15); dtMFR.setEditable(false); dtMFR.setBackground(bg);
    dtPARTOF = new JTextField(15); dtPARTOF.setEditable(false); dtPARTOF.setBackground(bg);
    dtSUBCUST = new JTextField(15); dtSUBCUST.setEditable(false); dtSUBCUST.setBackground(bg);
    dtSCHEDLAB = new JTextField(15); dtSCHEDLAB.setEditable(false); dtSCHEDLAB.setBackground(bg);
    dtSCAT = new JTextField(15); dtSCAT.setEditable(false); dtSCAT.setBackground(bg);
    dtNSN = new JTextField(15); dtNSN.setEditable(false); dtNSN.setBackground(bg);
    dtPLANTACCT = new JTextField(15); dtPLANTACCT.setEditable(false); dtPLANTACCT.setBackground(bg);
    dtAPPRPROC = new JTextField(15); dtAPPRPROC.setEditable(false); dtAPPRPROC.setBackground(bg);
    dtSVCLAB = new JTextField(15); dtSVCLAB.setEditable(false); dtSVCLAB.setBackground(bg);
    dtMETCYCLE = new JTextField(15); dtMETCYCLE.setEditable(false); dtMETCYCLE.setBackground(bg);
    dtPHASE = new JTextField(15); dtPHASE.setEditable(false); dtPHASE.setBackground(bg);
    dtDTCOMPL = new JTextField(15); dtDTCOMPL.setEditable(false); dtDTCOMPL.setBackground(bg);
    dtDTLASTSER = new JTextField(15); dtDTLASTSER.setEditable(false); dtDTLASTSER.setBackground(bg);
    dtSERVLBL = new JTextField(15); dtSERVLBL.setEditable(false); dtSERVLBL.setBackground(bg);
    dtDTNEXTDUE = new JTextField(15); dtDTNEXTDUE.setEditable(false); dtDTNEXTDUE.setBackground(bg);
    dtSTATUS = new JTextField(15); dtSTATUS.setEditable(false); dtSTATUS.setBackground(bg);
    dtONSITE = new JTextField(15); dtONSITE.setEditable(false); dtONSITE.setBackground(bg);
    dtSHOP = new JTextField(15); dtSHOP.setEditable(false); dtSHOP.setBackground(bg);
    dtWLNHRS = new JTextField(15); dtWLNHRS.setEditable(false); dtWLNHRS.setBackground(bg);
    dtCLASSSTD = new JTextField(15); dtCLASSSTD.setEditable(false); dtCLASSSTD.setBackground(bg);
    dtCALSTD = new JTextField(15); dtCALSTD.setEditable(false); dtCALSTD.setBackground(bg);


    textField.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    search();
    }
    });

    bs.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    table.repaint();
    search2();
    }
    });

    print.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    try {
    returnReportData();
    //System.out.println(reportType);
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    }
    });


    mcb.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    printMenu();
    }
    });

    metcb.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    try {
    returnReportData();
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    }
    });

    clearmc.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    clearPrint();
    }
    });
    filter.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    newFilter();
    }
    });

    refresh.addActionListener(new ActionListener()
    {

    public void actionPerformed(ActionEvent e)
    {
    // get the hash value from the JTextField
    String[] hash = tfPanel.getHash();
    // update the model
    //System.out.println(hash[0]+hash[1]+hash[2]+hash[3]+hash[4]+hash[5]+hash[6]);
    //System.out.println(model);
    //System.out.println(table);

    int nb = model.use(hash);
    // update the label for number of match
    tfPanel.label.setText(nb + " matches found");
    // redraw the JTable
    table.tableChanged(new TableModelEvent(model));
    //System.out.print(filtered);
    //System.out.println(filtered.size());
    clearPrint(); //?
    }
    });

    all.addActionListener(new ActionListener()
    {

    public void actionPerformed(ActionEvent e) {
    filtPrint();

    }

    }
    );

    }

    //Get the JTable and return it
    JTable getTable() throws IOException {

    File f = new File("D:\\PCQ\\A_R06.csv");
    //File f = new File("D:\\PCQ\\SQUIGGLE.csv");
    Scanner s = new Scanner(f);

    String[] colNames = {
    "PRINT",
    "SERVICING_LAB",
    "CUSTOMER_ID",
    "MODEL_NO",
    "SERIAL_NO",
    "ECN",
    "NOMENCLATURE",
    "SUB_CUSTODIAN",
    "SCHED_LAB",
    "METRL_CYCLE",
    "MFR_CD",
    "UIC",
    "PROCEDURE_USED",
    "VALUE_FIXED",
    "NSN",
    "PART_OF",
    "ON_SITE_SERVICE",
    "CAL_STD",
    "SERVICE_LABEL_CD",
    "PLANT_ACCT",
    "SCAT_CD",
    "PHASE_ID",
    "APPROVED_PROCEDURE",
    "INV_SHOP_NO",
    "CLASS_STD",
    "TYPE_STD",
    "WIP_STATUS",
    "EQPMT_TYPE_CD",
    "ICN",
    "PRINT_METERCARD_FLG",
    "EQPMT_STATUS_CD",
    "DELAY_REASON_CD",
    "CONDITION_RECEIVED",
    "SPCL_INSTR_CD",
    "WORKLOAD_NORM_HRS",
    "BIN_LOCATION",
    "DT_SYS",
    "DT_RCVD",
    "DT_INDUCT",
    "DT_DELAY",
    "DT_REPTD",
    "DT_LSTCAL",
    "DT_NXT_DUE",
    "DT_RECALL",
    "DT_CMPL",
    "DT_CREATE",
    "COST",
    "CAT_CUS",
    "CAT_LAB",
    "LAB_TYPE",
    "ACC_CODE",
    "FLAG_OFFLN"//,
    //"DT_REIND"

    };


    LineNumberReader lnr = new LineNumberReader(new FileReader(f));
    lnr.skip(Long.MAX_VALUE);
    int ln = lnr.getLineNumber()-1; //subtract 1 to account for the skipped row

    //Import CSV File into table model
    ArrayList<String> al = new ArrayList<String>(ln);
    int c = 0;
    s.nextLine(); //advance the scanner to skip the first row
    while (c < ln ) {
    al.add(s.nextLine().replace("\"", ""));
    c++;
    }

    model = new MyModel(colNames, al);
    sorter = new TableRowSorter<TableModel>(model);

    final JTable table = new JTable(model){
    public boolean isCellEditable(int rowIndex, int mColIndex) {
    if(mColIndex > 0){
    return false;
    }
    else return true;
    }



    public Class getColumnClass(int col) {
    Object o = getValueAt(0, col);
    if(o == null){
    return Object.class;
    }
    else {
    return o.getClass();
    }
    }

    final Color alphaZero = new Color(0, true);
    public Component prepareRenderer(TableCellRenderer renderer,
    int rowIndex, int vColIndex) {
    setOpaque(false);
    Component c = super.prepareRenderer(renderer, rowIndex,
    vColIndex);
    if (isCellSelected(rowIndex, vColIndex)) {
    if (rowIndex % 2 == 0) {
    //c.setBackground(Color.LIGHT_GRAY );

    c.setBackground(alphaZero);

    } else {
    //c.setBackground(getSelectionBackground());
    c.setBackground(alphaZero);
    }
    } else {
    if (rowIndex % 2 == 0) {
    //c.setBackground(new Color(224, 242, 252));
    c.setBackground(alphaZero);
    } else {
    //c.setBackground(getBackground());
    c.setBackground(alphaZero);
    }
    };
    if(Pattern.matches("[a-zA-Z]+", (CharSequence) (model.getValueAt(rowIndex, 1)))){
    c.setBackground(new Color(174, 201, 230));
    }

    //int[] wipcols = {1,26,28,31,37,38,39,40};

    if(vColIndex == 1 || vColIndex == 26 ||
    vColIndex == 28 || vColIndex == 31 ||
    vColIndex == 37 || vColIndex == 38 ||
    vColIndex == 39){
    c.setFont (new Font("SansSerif", Font.BOLD, 12));
    }

    return c;
    }

    };

    table.getModel().addTableModelListener(new TableModelListener() {
    public void tableChanged(TableModelEvent e) {
    int row2 = e.getFirstRow();
    int column = e.getColumn();
    int columns = e.ALL_COLUMNS;
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object data = model.getValueAt(row2, column);
    Boolean val = getCBValueAt(row2, column);

    //System.out.println(row2);
    //System.out.println(column);
    //System.out.println(val);
    }

    private Boolean getCBValueAt(int row, int column) {
    return (Boolean) table.getModel().getValueAt(row, column);
    } }
    );
    table.setOpaque(false);
    table.convertRowIndexToView(row);
    table.setModel(model);
    table.getTableHeader().setBackground(new Color(174, 201, 230));
    table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 12));
    table.setRowSorter(sorter);

    //table.setAutoCreateRowSorter(true);
    //table.setDefaultRenderer(String.class, new CustomRenderer());
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_S ELECTION);
    ListSelectionModel listMod = table.getSelectionModel();
    listMod.setSelectionMode(ListSelectionModel.SINGLE _SELECTION);
    listMod.addListSelectionListener(this);
    //int index=0; for(String s1 : al) System.out.println((index)+": "+s1);
    return table;
    }

    // my tableModel as an inner class
    class MyModel extends AbstractTableModel {
    String[] colName;
    ArrayList<String> al;
    ArrayList<Boolean> first;
    String[][] hash; // the hashcode of each line
    // the selected rows
    String[] token; // last row read
    int cacheRow = -1; // not set
    // the arrayList to use. If I have filters, it will point to filtered
    // if I do not have filters it will point to al


    // constructor
    MyModel(String[] colName, ArrayList<String> al) {

    long start = System.nanoTime();
    this.colName = colName;
    this.al = al;
    filtered = new ArrayList<String>(); // init empty

    // Start by pointing to the ArrayList containing all the data (no filter)
    toUse = al;

    //ArrayList<Boolean> first;
    first = new ArrayList<Boolean>(al.size());
    for(int i = 0; i < al.size(); ++i)
    first.add(Boolean.valueOf(false));

    // build the hash-code for each row based on the 7 first columns
    hash = new String[al.size()][8];
    for(int i = 0; i < hash.length; ++i) {
    // split the data based on delimiter
    token = al.get(i).split("\\|", 8);
    for(int j = 0; j < 8; ++j) {
    hash[i][j] = token[j];
    }
    }
    long now = System.nanoTime();
    //System.out.println("TableModel constructed in: " + ((now-start) / 1000000L) + " milliseconds");

    }

    // Use a filter based on a hash-value coming from the JTextField
    int use(String[] hashValue) {
    cacheRow = -1; // clear cache
    filtered.clear(); // clear previous match data
    // save the length in an array to avoid to call 200000 * 7 times .length()
    int[] len = new int[hashValue.length];
    int total = 0;
    for(int i = 0; i < hashValue.length; ++i) {
    len[i] = hashValue[i].length();
    total += len[i];
    }
    // if all textfield empty
    if(total == 0) {
    toUse = al;
    return al.size();
    }
    filteredRows = new int[/*filtered.size()*/400000];
    // k we will have to test
    for(int i = 0; i < hash.length; ++i) {
    int j;
    for(j = 0; j < hashValue.length; ++j) {
    // empty test
    if(len[j] == 0)
    continue;
    // if does not start with break
    if(!hash[i][j].startsWith(hashValue[j]))
    break;
    }
    // if all matched
    if(j == hashValue.length)
    filtered.add(al.get(i));
    int z = i;


    }

    toUse = filtered;

    // returns the number of match to be displayed in the JLabel
    return toUse.size();
    }

    @Override
    public int getColumnCount() {
    return colName.length;
    }
    public String getColumnName(int col) {
    return colName[col];
    }

    @Override
    public int getRowCount() {
    return toUse.size();
    }

    @Override
    public Object getValueAt(int row, int col) {

    if(col == 0)
    return first.get(row);
    // if we are using the gig array and the column is the first ones
    // use the hash
    if(toUse == al && col < 8)
    return hash[row][col-1];

    if(row != cacheRow) {
    String line = toUse.get(row);//.replace("\"", "");
    token = line.split("\\|");
    cacheRow = row;
    }
    return token[col-1]; //-1
    }

    public void setValueAt(Object o, int row, int col) {
    // first column is the boolean
    if(col == 0) {
    first.set(row, (Boolean) o);
    return;
    }
    // other column
    String line = al.get(row).replace("\"", "");
    String[] token = line.split("\\|"); //DELIMITER - USE PIPE***
    token[row-1] = (String) o; // replace with new one
    StringBuilder sb = new StringBuilder(); // rebuild the String
    for(int i = 0; i < token.length-1; ++i)
    sb.append(token[i]).append("\\|"); // with the delimiter
    sb.append(token[token.length-1]); // but for the last one
    al.set(row, sb.toString()); // replace in ArrayList
    }



    }

    //Search method
    void search()
    {

    String target = textField.getText();
    for(int row = 1; row < table.getRowCount(); row++)
    for(int col = 1; col < table.getColumnCount() -1 ; col++)
    {
    String next = (String)table.getValueAt(row, col);
    if(next.equals(target))
    {
    showSearchResults(row, col);
    return;
    }
    }

    // reset table display after failed search> target null/not found <
    CustomRenderer renderer =
    (CustomRenderer)table.getDefaultRenderer(String.cl ass);
    renderer.setTargetCell(-1, -1);
    table.repaint();
    }

    private void newFilter()
    {
    List<RowFilter<TableModel,Object>> filters = new ArrayList<RowFilter<TableModel,Object>>();
    RowFilter<TableModel, Object> compoundRowFilter = null;
    try {
    svclabf = RowFilter.regexFilter("^" + svclabt.getText(), 1);
    custf = RowFilter.regexFilter("^" +custt.getText(), 2);
    modf = RowFilter.regexFilter("^" +modt.getText(), 3);
    serialf = RowFilter.regexFilter("^" +serialt.getText(), 4);
    ecnf = RowFilter.regexFilter("^" +ecnt.getText(), 5);
    subcustf = RowFilter.regexFilter("^" +subcustt.getText(), 7);

    filters.add(svclabf);
    filters.add(custf);
    filters.add(modf);
    filters.add(serialf);
    filters.add(ecnf);
    filters.add(subcustf);
    compoundRowFilter = RowFilter.andFilter(filters); // you may also choose the OR filter

    } catch (java.util.regex.PatternSyntaxException e) {
    return;
    }

    sorter.setRowFilter(compoundRowFilter);
    }

    void search2(){

    // reset table display after failed search
    CustomRenderer renderer = (CustomRenderer)table.getDefaultRenderer(String.cl ass);
    renderer.setTargetCell(-1, -1);
    table.repaint();

    String [] searchlist = new String[6];
    Boolean match; //use as toggle for search decision tree?
    String sECN = null; Boolean Ec = true;
    String sCust = null; Boolean Cc = true;
    String sMod = null; Boolean Mc = true;
    String sSer = null; Boolean Sc = true;
    String sNom = null; Boolean Nc = true;
    String sSubCust = null; Boolean Scc = true;

    //Only get Text Field value if Check box is checked
    if (cECN.isSelected()){
    sECN = tECN.getText();
    } else if(!cECN.isSelected()) {sECN = null;}; //if needed, catch null exception so "" won't be passed to search list? -- causes null pointer exception
    if (cCust.isSelected()){
    sCust = tCust.getText();
    }
    if (cMod.isSelected()){
    sMod = tMod.getText();
    }
    if (cSer.isSelected()){
    sSer = tSer.getText();
    }
    if (cNom.isSelected()){
    sNom = tNom.getText();
    }
    if (cSubCust.isSelected()){
    sSubCust = tSubCust.getText();
    }
    //After assigning String values from text fields based on check box confirmation, fill an array list with values
    searchlist[0] = sECN;
    searchlist[1] = sCust;
    searchlist[2] = sMod;
    searchlist[3] = sSer;
    searchlist[4] = sNom;
    searchlist[5] = sSubCust;

    //Need: array to hold table row values
    Object[] tbrowdata = new Object[8];
    TableModel tb = table.getModel();
    Object val;
    int selectedRow;

    for(int r = 0; r < table.getRowCount(); r++){
    selectedRow = r;

    for (int i= 1; i < 8 ; i++) {
    val = tb.getValueAt(r, i);
    tbrowdata [i-1] = val;

    }
    if(
    ((tbrowdata[4].equals(searchlist[0])) || searchlist[0] == null) &&
    ((tbrowdata[1].equals(searchlist[1])) || searchlist[1] == null) &&
    ((tbrowdata[2].equals(searchlist[2])) || searchlist[2] == null) &&
    ((tbrowdata[3].equals(searchlist[3])) || searchlist[3] == null) &&
    ((tbrowdata[5].equals(searchlist[4])) || searchlist[4] == null) &&
    ((tbrowdata[6].equals(searchlist[5])) || searchlist[5] == null)

    ){
    showSearchResults(r, 5);
    }

    }



    //test print values from GUI Text Fields when respective Check box is checked
    /*
    System.out.println(searchlist[0]);
    System.out.println(searchlist[1]);
    System.out.println(sMod);
    System.out.println(sSer);
    System.out.println(sNom);
    System.out.println(sSubCust);
    */
    }

    //clear Print Selection
    public void clearPrint(){
    TableModel tm2 = table.getModel();
    for (int i = 0; i<tm2.getRowCount(); i++){
    tm2.setValueAt(false, i, 0);
    table.repaint();
    }
    }

    //need: Method to set Print = true on current filtered selection called by JButton
    public void filtPrint(){

    int rows=toUse.size();
    String[] filtVals = new String[rows];
    TableModel tm2 = table.getModel();

    /*
    Color a = new Color(104, 106, 132);
    Color b = new Color(210, 226, 232);
    Color c = new Color(10, 77, 126);
    */

    if(rows > 3000){


    //v.1 - SIMPLE
    JFrame frame2 = new JFrame();
    frame2.getRootPane().setOpaque(false);

    frame2.setUndecorated(true);
    Color cm = new Color(210, 226, 232);
    frame2.getContentPane ().setBackground (cm);
    //Color cm = Color.cyan;
    UIManager um = new UIManager();
    um.put("OptionPane.background", cm);
    UIManager.put("Panel.background", cm);
    JOptionPane.showMessageDialog(frame2,
    "Current Filter Selection is too large. Please refine filter criteria.",
    "Refine Filter Selection",
    JOptionPane.WARNING_MESSAGE);

    }
    else{
    for(int i=0; i<toUse.size(); i++){
    String n = toUse.get(i);
    String[] filtrow = n.split("\\|");
    for(int j=0; j<filtrow.length; j++){
    filtVals[i] = filtrow[4];
    }
    //System.out.println(filtVals[i]);
    }


    for (int i = 0; i<tm2.getRowCount(); i++){
    for(int x = 0; x<filtVals.length; x++){
    //System.out.println(tm2.getValueAt(i, 5)+ " " +filtVals[i]);
    if(tm2.getValueAt(i, 5).equals(filtVals[x])){
    tm2.setValueAt(true, i, 0);
    table.repaint();
    }
    }
    }
    }
    //System.out.println(tm2.getValueAt(1, 5));
    //System.out.println(filtVals[1][4]);
    //System.out.println(filtered.size());
    //System.out.println(toUse.size());
    //System.out.println(Arrays.toString(filteredRows));

    }


    //returnReportData
    public Object[][] returnReportData() throws IOException{

    ////////////////////////MECL////////////////////////////////////////////
    File mf = new File("D:\\PCQ\\MECL_1.csv");
    Scanner ms = new Scanner(mf);

    String type = null; //ASSET, METCAL, MCARD, MCARD-P, MCARD-W, MCARD-Y, MCARD-G, MCARD-B,

    LineNumberReader lnr = new LineNumberReader(new FileReader(mf));
    lnr.skip(Long.MAX_VALUE);
    int ln = lnr.getLineNumber(); //subtract 1 to account for the skipped row

    //Import CSV File into 2d array
    ArrayList<Object[]> list = new ArrayList<Object[]>();
    ms.nextLine();
    while (ms.hasNextLine()) {
    Object[] line = ms.next().split("\\|");
    list.add(new Object[] {

    ((String) line[0]),
    ((String) line[1]),
    ((String) line[2]),
    ((String) line[3]),
    ((String) line[4]),
    ((String) line[5]),
    ((String) line[6]),
    ((String) line[7]),
    ((String) line[8]),
    ((String) line[9]),
    ((String) line[10]),
    ((String) line[11]),
    ((String) line[12]),
    ((String) line[13]),
    ((String) line[14]),
    ((String) line[15]),
    ((String) line[16]),
    ((String) line[17]),
    ((String) line[18]),
    ((String) line[19]),
    ((String) line[20]),
    ((String) line[21]),
    ((String) line[22]),
    ((String) line[23]),
    ((String) line[24]),
    ((String) line[25]) // ,
    // ((String) line[26]),

    });

    }
    ms.close();
    int rows = list.size();
    int cols = 26;

    Object[][] meclData = new Object[rows][cols];
    for (int i = 0; i < rows; i++) {
    meclData[i] = list.get(i);
    }
    ////////////////////////END MECL////////////////////////////////////////////

    TableModel tm2 = table.getModel();
    //Get count of rows with Print Box checked (counter = z) to initialize the reportData Object[][]
    int z = 0;
    for(int x = 0; x < tm2.getRowCount(); x++){
    if(((Boolean)tm2.getValueAt(x, 0)) == true){
    z++;
    }
    }
    //Initialize Object[][] reportData and store dimensions as tRow and tCol
    int nRow = tm2.getRowCount(), nCol = tm2.getColumnCount();
    Object[][] reportData = new Object[z][/*53*/ /*79*/ 105]; //79 = include space for MECL data


    //Populate reportData with table model data where Checkbox = Boolean.TRUE

    int index = 0;
    for (int i = 0 ; i < nRow ; i++){
    if(((Boolean)tm2.getValueAt(i, 0)) == true){
    for (int j = 0 ; j < nCol-1 ; j++){
    reportData[index][j] = tm2.getValueAt(i,j+1);
    }
    ++index;
    }
    }
    //AND append Customer MECL data

    for (int i = 0; i<reportData.length; i++){
    for(int d = 0; d < meclData.length; d++){
    if(reportData[i][1].equals(meclData[d][2]) ){
    // LOOP - CUSTOMER
    for(int m = 0; m < meclData[0].length; m++){
    reportData[i][m+53] = meclData[d][m];
    }
    }
    if(reportData[i][7].equals(meclData[d][2]) ){
    // LOOP - SCHED LAB
    for(int m = 0; m < meclData[0].length; m++){
    reportData[i][m+79] = meclData[d][m];
    }
    }
    }
    }
    /*
    //Test print reportData in rectangular form
    int ROWS = reportData.length;
    int COLS = reportData[0].length;

    for (int L = 0; L < ROWS; L++) {
    for (int M = 0; M < COLS; M++) {
    System.out.print(" " + reportData[L][M]);
    }
    System.out.print("\n");
    }
    */
    return reportData;
    }

    public void printMenu() {

    JFrame frame = new JFrame("PcInventoryQuery Print Menu");

    //frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE );
    frame.setLayout(new BorderLayout());
    frame.setResizable(false);
    JPanel p = new JPanel();
    frame.setContentPane(p);
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS ));

    JPanel panel1 = new JPanel(){
    protected void paintComponent(Graphics grphcs) {
    this.setBackground(new Color(114, 167, 226));
    Graphics2D g2d = (Graphics2D) grphcs;
    int arc = 10;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASI NG,
    RenderingHints.VALUE_ANTIALIAS_ON);
    GradientPaint gp = new GradientPaint(0, 0,
    getBackground().darker(), 0, getHeight(),
    getBackground().brighter().brighter());
    g2d.setStroke(new BasicStroke());
    g2d.setPaint(gp);
    g2d.fillRoundRect(0, 0, getWidth(), getHeight(), arc, arc);
    super.paintComponent(grphcs);
    }
    };
    panel1.setOpaque(false);

    JPanel panel2 = new JPanel(){
    protected void paintComponent(Graphics grphcs) {
    this.setBackground(new Color(114, 167, 226));
    Graphics2D g2d = (Graphics2D) grphcs;
    int arc = 10;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASI NG,
    RenderingHints.VALUE_ANTIALIAS_ON);
    GradientPaint gp = new GradientPaint(0, 0,
    getBackground().darker(), 0, getHeight(),
    getBackground().brighter().brighter());
    g2d.setStroke(new BasicStroke());
    g2d.setPaint(gp);
    g2d.fillRoundRect(0, 0, getWidth(), getHeight(), arc, arc);
    super.paintComponent(grphcs);
    }
    };
    panel2.setOpaque(false);
    Color fg = new Color(7, 116, 165);
    panel1.setForeground(fg);
    Font lfont = new Font("SansSerif", Font.BOLD, 11);





    JRadioButton metcalForm = new JRadioButton("Metcal Form");
    JLabel l1 = new JLabel("Print a METCAL Form.");
    l1.setFont(lfont);
    metcalForm.setForeground(Color.WHITE);
    //metcalForm.setMnemonic(KeyEvent.VK_A);
    metcalForm.setActionCommand("Metcal_Form");
    metcalForm.setSelected(true);
    metcalForm.setOpaque(false);

    JRadioButton paperMcard = new JRadioButton("Paper MeterCard");
    JLabel l2 = new JLabel("Print a Paper MeterCard.");
    l2.setFont(lfont);
    paperMcard.setForeground(Color.WHITE);
    //paperMcard.setMnemonic(KeyEvent.VK_B);
    paperMcard.setActionCommand("Paper_MeterCard");
    paperMcard.setOpaque(false);

    JRadioButton mCard = new JRadioButton("MeterCard Form");
    JLabel l3 = new JLabel("Print a MeterCard Form.");
    l3.setFont(lfont);
    mCard.setForeground(new Color(96, 96, 96));
    //mCard.setMnemonic(KeyEvent.VK_C);
    mCard.setActionCommand("MeterCard_Form");
    mCard.setOpaque(false);

    JRadioButton assetList = new JRadioButton("Asset List");
    JLabel l4 = new JLabel("Print an Asset List.");
    l4.setFont(lfont);
    assetList.setForeground(Color.DARK_GRAY);
    //mCard.setMnemonic(KeyEvent.VK_D);
    assetList.setActionCommand("Asset_List");
    assetList.setOpaque(false);

    // Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(metcalForm);
    group.add(paperMcard);
    group.add(mCard);
    group.add(assetList);

    RadioListener myListener = new RadioListener();
    metcalForm.addActionListener(myListener);
    paperMcard.addActionListener(myListener);
    mCard.addActionListener(myListener);
    assetList.addActionListener(myListener);


    panel1.setLayout(new GridLayout(5, 1));
    panel2.setLayout(new BorderLayout());

    panel1.add(metcalForm);
    panel1.add(paperMcard);
    panel1.add(mCard);
    panel1.add(assetList);
    panel2.add(print, BorderLayout.SOUTH);
    jlbPicture= new JLabel((new ImageIcon("D:\\PCQ\\Metcal_Form.jpg"))); //Set the Default Image
    jlbPicture.setPreferredSize(new Dimension(250, 180));
    panel2.add(jlbPicture, BorderLayout.CENTER);


    p.add(panel1);
    p.add(panel2);
    frame.setSize(538, 259);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    }


    //Show the search results using Custom Renderer
    private void showSearchResults(int row, int col)
    {
    //table.repaint();
    CustomRenderer renderer = (CustomRenderer)table.getCellRenderer(row, col);
    renderer.setTargetCell(row, col);
    Rectangle r = table.getCellRect(row, col, false);
    table.scrollRectToVisible(r);
    table.repaint();

    }

    //Main method for test purposes
    public void main(String[] args) throws IOException
    {
    SearchTest test = new SearchTest();
    JFrame f = new JFrame("-JQuery V_0.1 Beta-");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container cP = f.getContentPane();

    f.getContentPane().add(new JTabbedPane());
    f.getContentPane().add(new JScrollPane(test.table));
    f.getContentPane().add(test.textField, "North");
    f.setSize(600,400);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    test.textField.requestFocusInWindow();

    }




    //Mouse Event Listener for Row Selection into Detail Tab
    Object o;
    Object[] dtlist = new Object[52];
    public void valueChanged(ListSelectionEvent e) {
    Object value;
    if (!e.getValueIsAdjusting()) {
    selRows = table.getSelectedRow();
    row = selRows;

    // get Table data
    TableModel tm = table.getModel();
    if (row > -1) {
    row = table.convertRowIndexToModel(row);
    for (int i= 1; i < 52 ; i++) {
    value = tm.getValueAt(row,i);
    dtlist[i-1] = value;

    }
    //get test value in array dtlist
    o = Array.get(dtlist, 1);
    //System.out.println(selRows);
    //System.out.println(row);
    //Key Fields
    dtECN.setText((String) Array.get(dtlist, 4));
    dtCust.setText((String) Array.get(dtlist, 1));
    dtMod.setText((String) Array.get(dtlist, 2));
    dtSer.setText((String) Array.get(dtlist, 3));
    dtNom.setText((String) Array.get(dtlist, 5));

    //Auxiliary Fields
    dtMFR.setText((String) Array.get(dtlist, 10));
    dtPARTOF.setText((String) Array.get(dtlist, 14));
    dtSUBCUST.setText((String) Array.get(dtlist, 6));
    dtSCHEDLAB.setText((String) Array.get(dtlist, 7));
    dtSCAT.setText((String) Array.get(dtlist, 19));
    dtNSN.setText((String) Array.get(dtlist, 13));
    dtPLANTACCT.setText((String) Array.get(dtlist, 18));
    dtAPPRPROC.setText((String) Array.get(dtlist, 21));
    dtSVCLAB.setText((String) Array.get(dtlist, 0));
    dtMETCYCLE.setText((String) Array.get(dtlist, 8));
    dtPHASE.setText((String) Array.get(dtlist, 20));
    dtDTCOMPL.setText((String) Array.get(dtlist, 43));
    dtDTLASTSER.setText((String) Array.get(dtlist, 40));
    dtSERVLBL.setText((String) Array.get(dtlist, 17));
    dtDTNEXTDUE.setText((String) Array.get(dtlist, 41));
    dtSTATUS.setText((String) Array.get(dtlist, 35));
    dtONSITE.setText((String) Array.get(dtlist, 15));
    dtSHOP.setText((String) Array.get(dtlist, 22));
    dtWLNHRS.setText((String) Array.get(dtlist, 33));
    dtCLASSSTD.setText((String) Array.get(dtlist, 23));
    dtCALSTD.setText((String) Array.get(dtlist, 16));

    }
    }
    }

    @Override
    public void tableChanged(TableModelEvent e) {
    if (!((ListSelectionModel) e).getValueIsAdjusting()) {
    int index = e.getFirstRow();
    model.setValueAt(Boolean.TRUE, index, 0);
    }
    }

    class TextFieldPanel extends JPanel {
    JTextField[] tf = new JTextField[8];
    JLabel label = new JLabel();

    // TextFieldPanel constructor. The 5 JTextField and the JLabel
    TextFieldPanel() {
    super(new GridBagLayout());
    add(new JLabel("\n")); // a little gap at the top
    GridBagConstraints t = new GridBagConstraints();

    //ADD LABELS TO SEARCH FIELDS
    String[] labels = new String[]{"SVC LAB", "CUSTOMER", "MODEL", "SERIAL", "ECN", "NOMENCLATURE", "SUB CUSTODIAN", "SCHED LAB"};
    for(int i = 0; i < labels.length; ++i) {
    JLabel x = new JLabel(labels[i].toString());
    //System.out.println(x);
    t.gridx = i; t.gridy = 0; add(x, t);
    }

    // the 8 JTextFields in a row
    String[] tips = new String[]{"Filter by Servicing Lab", "Filter by Customer ID",
    "Filter by Model Number", "Filter by Serial Number",
    "Filter by Equipment Control Number",
    "Filter by Nomenclature", "Filter by Sub Custodian",
    "Filter by Scheduled Lab"};
    for(int i = 0; i < tf.length; ++i) {
    tf[i] = new JTextField(12);
    Color bg = new Color(224, 242, 252);
    tf[i].setBackground(bg);
    tf[i].setToolTipText(tips[i]);
    t.gridx = i; t.gridy = 1; add(tf[i], t);
    }

    // the status label
    label.setOpaque(true);
    label.setBackground(new Color(210, 226, 232));
    label.setHorizontalAlignment(SwingConstants.CENTER );

    t.gridx = 3; t.gridy = 2; add(label, t);
    t.gridx = 8; t.gridy = 1; add(refresh,t);
    setOpaque(false);
    }

    // return the String in the 8 JTextFields
    String[] getHash() {
    String[] token = new String[tf.length];
    for(int i = 0; i < token.length; ++i)
    token[i] = tf[i].getText().trim();
    return token;
    }
    }

    class RadioListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

    reportType = e.getActionCommand();
    jlbPicture.setIcon(new ImageIcon("D:\\PCQ\\"+e.getActionCommand() + ".jpg"));

    }
    }

    } //end SearchTest



    class TransparentButton extends JButton {
    public TransparentButton(String text) {
    super(text);
    final Color alphaZero = new Color(0, true);
    setBackground(alphaZero);
    setForeground(Color.black);
    setOpaque(false);
    //setBorder(null);
    //setBorderPainted(false);
    setContentAreaFilled(true);
    }

    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g.create();
    //g2.setComposite(AlphaComposite.getInstance(AlphaCo mposite.SRC_OVER, 0.5f));
    super.paint(g2);
    setForeground(Color.black);
    g2.dispose();
    }
    }

    class TransparentButtonW extends JButton {
    public TransparentButtonW(String text, Color color) {
    super(text);
    final Color alphaZero = new Color(0, true);
    setBackground(alphaZero);
    setForeground(color);
    setOpaque(false);
    //setBorder(null);
    //setBorderPainted(false);
    setContentAreaFilled(true);
    }

    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g.create();
    //g2.setComposite(AlphaComposite.getInstance(AlphaCo mposite.SRC_OVER, 0.5f));
    super.paint(g2);
    setForeground(Color.black);
    g2.dispose();
    }
    }

    class CustomRenderer implements TableCellRenderer{
    JLabel label;
    int targetRow, targetCol;
    final Color alphaZero = new Color(0, true);

    public CustomRenderer()
    {
    label = new JLabel();
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setOpaque(true);
    targetRow = -1;
    targetCol = -1;
    }


    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column)
    {
    if(isSelected)
    {
    label.setBackground(alphaZero);
    label.setForeground(alphaZero);
    }
    else
    {
    label.setBackground(alphaZero);
    label.setForeground(alphaZero);
    }
    if(row == targetRow && column == targetCol)
    {
    label.setBorder(BorderFactory.createLineBorder(Col or.red));
    label.setFont(table.getFont().deriveFont(Font.BOLD ));
    }
    else
    {
    label.setBorder(null);
    label.setFont(table.getFont());
    }
    label.setText((String)value);
    return label;
    }

    public void setTargetRow(int row){
    targetRow = row;
    }

    public void setTargetCell(int row, int col)
    {
    targetRow = row;
    targetCol = col;
    }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,145
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Might be a thread leak problem reading a file into an Array list.

    ava.lang.ArrayIndexOutOfBoundsException: 11
    at PCQ.SearchTest.returnReportData(SearchTest.java:86 7)
    At line 867 the index to an array is past the end of the array. The index's value was 11.
    Look at line 867 and see what array is being indexed, and see why the index to that array is past the end of the array. You may have to add some println statements to print out the size of the array and the values of the index to see why the index is going past the end of the array.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Apr 2012
    Posts
    160
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: Might be a thread leak problem reading a file into an Array list.

    It looks like you are splitting the line into only 11 parts of data, rather than the 26 that you were expecting.

  4. #4
    Junior Member rushtonjj's Avatar
    Join Date
    Jun 2012
    Posts
    2
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Might be a thread leak problem reading a file into an Array list.

    Correct, it does think I am splitting it into 11 parts. If I have nextLine()in there it thinks I'm splitting the columns into 22 parts. I tried next because its not a new line its looking for the next pipe. I've reviewed the file and the file has 26 -1. I'll give finding the size of the array and the value of the index a shot.

    I do have a question though, why would this code work on my partner's machine and not mine when we are using the exact same files and code. I've just taken his code so I can integrate my part, which currently I have not? Does the code look correct to you?
    V/r,

    Rushtonjj

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,145
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Might be a thread leak problem reading a file into an Array list.

    Does the code look correct to you?
    No, because the code does NOT test if the array from the split() method has 20+ elements before trying to access all those elements. You should always test that your assumptions are correct before using them.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Reading file into array. PLEASE HELP! :)
    By otissmith in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: April 27th, 2012, 12:52 AM
  2. Replies: 3
    Last Post: December 2nd, 2011, 11:53 AM
  3. Reading file of floats into array list and sorting into subsets
    By Skave in forum Collections and Generics
    Replies: 2
    Last Post: November 9th, 2011, 07:03 PM
  4. Reading from a sequential file to an array
    By Xrrak in forum File I/O & Other I/O Streams
    Replies: 15
    Last Post: August 20th, 2011, 01:33 PM
  5. Reading a file, then putting it in an array
    By Gondee in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 16th, 2010, 11:11 AM