Queue/Array into JTable

Hi, I am reading some data from a database and I have got it stored locally inside a queue. What i want to do is read in the queue (already got a mehtod for this) but then add each object in the queue, into a row in my JTable. also I want to be able to delete a row of a jtable when i am finished with it. any help very much apprecaited. all i have got so far is declaring the JTable and jscrollpane etc. i sint too crash hot on swing so you might have to make it obvious. thanks.

Right, I seem to have got myself into a mess with this. i dont think i'm too far off though. if i get this bit then i should have cracked it. I am getting a null pointer exception as i try to enter my first string into the TableModel. PS Its a bit of a hashed together attempt so any tips of how to improve the class generally, greatly appreciated.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class ProtocolGUI extends JPanel implements ActionListener
          private JPanel menuPanel;
          private JMenuBar menuBar;
        private JMenu fileMenu;
        private JMenu helpMenu;
          private JMenuItem startMon;
         private JMenuItem exitItem;
        private JMenuItem about;
        private JTabbedPane tabbedPane;
          private JPanel graphicsPanel;
          private JPanel textPanel;
        private JTable pclTable;
     public ProtocolGUI()
        super(new BorderLayout());
        menuBar = new JMenuBar();
        fileMenu = new JMenu("File");
        helpMenu = new JMenu("Help");
        startMon = new JMenuItem("Start");
         exitItem = new JMenuItem("Exit");
        about = new JMenu("About");
        menuPanel= new JPanel();
        menuPanel.setLayout(new BorderLayout());
        this.add(menuPanel, BorderLayout.NORTH);
        exitItem.addActionListener(this);
        fileMenu.add(startMon);
        fileMenu.add(exitItem);
        helpMenu.add(about);
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);
        menuPanel.add(menuBar, BorderLayout.NORTH);
          ///////////end of menu///////////////
        tabbedPane = new JTabbedPane();
          ImageIcon graphIcon = createImageIcon("images/graphtab.gif");
          ImageIcon textIcon = createImageIcon("images/texttab.gif");
        graphIcon = new ImageIcon("images/graphtab.gif");
        textIcon = new ImageIcon("images/texttab.gif");
        graphicsPanel = new JPanel();
        textPanel = new JPanel();
          tabbedPane.addTab("Graphical", graphIcon, graphicsPanel,
                          "Swaps to graphical output");
        tabbedPane.addTab("Text", textIcon, textPanel,
                          "Swaps to text output");
        /*TableModel dataModel = new AbstractTableModel()
          public int getColumnCount()
                 return 6;
          public int getRowCount()
                 return 20;
          public Object getValueAt(int row, int col)
                 return new Integer(row*col);
          //pclTable = new JTable(dataModel);
        MessageSet ms2 = new MessageSet();
          textPanel.add(new JScrollPane(createTable(ms2.getArray())));
        //Add the tabbed pane to the outer panel.
          add(tabbedPane, BorderLayout.CENTER);
        setPreferredSize(new Dimension(500, 500));
        //Uncomment the following line to use scrolling tabs.
        //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    // Creates a JTable and returns it
     private JTable createTable(Message[] theArray)
          // Define empty data for model creation
          String[][] cellData = new String[0][6];
          String[] colNames = { "ID", "Sent To", "Sent From", "Command", "Data Ref", "Monitored" };
          // Create the table model
          DefaultTableModel tableModel = new DefaultTableModel(cellData, colNames);
          // Create some records and add them to the model
          String[] record = new String[6];
          for (int row=0; row<=theArray.length; row++)
            record[0] = Integer.toString(theArray[row].getID());
            record[1] = theArray[row].getToSection_ID();
               record[2] = theArray[row].getFromSection_ID();
               record[3] = Integer.toString(theArray[row].getType_ID());
               record[4] = theArray[row].getDataRef();
               record[5] = Integer.toString(theArray[row].getMonitored());
               tableModel.addRow(record);
          // Create the table and return it
          return new JTable(tableModel);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path)
        java.net.URL imgURL = ProtocolGUI.class.getResource(path);
        if (imgURL != null)
            return new ImageIcon(imgURL);
          else
            System.err.println("Couldn't find file: " + path);
            return null;
    public void actionPerformed(ActionEvent e)
        Object source = e.getSource();
        if (source == exitItem)
            System.exit(0);
     private static void createAndShowGUI()
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("Protocol GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new ProtocolGUI();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.getContentPane().add(new ProtocolGUI(),
                                 BorderLayout.CENTER);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args)
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}

Similar Messages

  • Need to use vector to insert data into JTable?

    hi
    i'm trying to insert data from mssql 2000 into JTable. The number of columns are fixed, but the number of rows are not, since it will depend on how many data retrieved from the database.
    The documentation says that vector class implements a growable array of objects, and I've seen some examples using vector such as from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=238597 .
    I would like to know, in my case, do i need to set my column and row to use vector? or should i only set rows to use vector ? (since the row size will vary, while the column size will stick to 6).

    Because your JTable operation will be done on a table model, the selection of the initial data
    structure for the model is almost non-issue. In other words, whatever will do.
    See the javadoc for the DefaultTableModel class, which you will eventually use, especially the
    construcotr part.

  • Inserting a associative array into a table

    Hi,
    I am working on a process where I want to store the temporary results in an associative array. At the end of the process I plan to write the contents of the array into a table that has the same structure. (the array is defined as a %rowtype of the table)
    Is it possible to execute ONE sql statement that transfers the array into the table? I am on 10g (10.2.0.4.0)
    Here's what I have now:
    declare
      type t_emp is table of emp%rowtype index by pls_integer;
      v_emp t_emp;
    begin
      -- a process that fills v_emp with lots of data
      for i in v_emp.first .. v_emp.last
      loop
        insert into emp values v_emp(i);
      end loop;  
    end;But it would be better if the loop could be replaced by sql one statement that inserts all of v_emp into emp. Is that possible?
    Thanks!
    PS: I'm not sure whether it's a good idea to use this approach... building a table in memory and inserting it into the database at the end of the process. Maybe it's better to insert every record directly into the table... but in any case I'm curious to see if it is possible in theory :)
    Edited: Added version info

    True, SQL cannot access the PL/SQL type.
    So you can not do something like this:
    insert into emp
    select * from table(v_emp)That is not possible.
    But FORALL is possible:
    FORALL i in v_emp.first .. v_emp.last
        insert into emp values v_emp(i);FORALL makes just one "round trip" to SQL bulk binding the entire contents of the array.
    It is much more efficient than the normal FOR loop, though it is mostly a PL/SQL optimization - even the FORALL actually inserts the rows "one at the time", it just hands the entire array to the SQL engine in one go.
    If the logic has to be done procedurally, FORALL is efficient.
    If the logic can be changed so arrays can be avoided completely and everything done in a single "insert into ... select ..." statement, that is the most efficient.

  • How can i pass a value in array into .setText()?

    i want to display a value in an array into a JTextField. May i know how to do it?
    eg:
    JTextField UserName;
    UserName.setText(s);
    but it doesn't display the value into the JTextfield.

    ok... is s an array?
    String[] s = {"s1", "s2"};Either you expect 1 value...
    username.setText(s[0]);
    // or
    username.setText(s[1]);Or you expect both:
    StringBuffer sb = new StringBuffer("");
    for(int x = 0; x < s.length; x++) {
       if(x != 0) sb.append(", ");
       sb.append(s[x])
    username.setText(sb.toString());

  • Cant get data from text file to print into Jtable

    Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
    void dbTest() {
    DataInputStream dis = null;
    String dbRecord = null;
    String hold;
    try {
    File f = new File("customer.txt");
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    Vector dataVector = new Vector();
    Vector headVector = new Vector(2);
    Vector row = new Vector();
    // read the record of the text database
    while ( (dbRecord = dis.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(dbRecord, ",");
    while (st.hasMoreTokens()) {
    row.addElement(st.nextToken());
    System.out.println("Inside nested loop: " + row);
    System.out.println("inside loop: " + row);
    dataVector.addElement(row);
    System.out.println("outside loop: " + row);
    headVector.addElement("Title");
    headVector.addElement("Type");
    dataTable = new JTable(dataVector, headVector);
    dataTableScrollPane.setViewportView(dataTable);
    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error!" + e.getMessage());
    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    } // end if
    } // end finally
    } // end dbTest

    Here's a thread that loads a text file into a JTable:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172
    And my reply in this thread shows how you can use a text file as a simple database:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=342380

  • Add time stamp array into first column of text file

    I am writing daq output to a file by using array to spreadsheet string vi then write that to a file but I would like to add a time stamp array into the first column of the text file. How do I do this?

    When you use a DAQmx Read, you have the option of returning a waveform data type. This includes time data. If you were to use this and either Export Waveforms to Spreadsheet File or Write Measurement File, this would included. To stick with the regular Write to Spreadsheet File, you would have to create an array of timestamps yourself based on a start time and the sample rate of the DAQ. Then you would convert this and the data array to strings and use the string array type of Write to Spreadsheet instead of the DBL type.
    Message Edited by Dennis Knutson on 09-25-2007 01:12 PM
    Attachments:
    Write to Spreadsheet - Strings.PNG ‏1 KB

  • Write arrays into a text file in different columns at different times

    Hi,
              I have a problem write data into a text file. I want to write 4 1D arrays into a text file. The problem is that I need to write it at different time and in different column (in other word, not only append the arrays).
    Do you have an idea to solve my problem?
    Thank you

    A file is long a linear string of data (text). In order ro insert columns, you need to rewrite the entire file, because colums are interlaced over the entire lenght of the file.
    So:
    read file into 2D array
    insert columns using array operations
    write resulting 2D array to file again.
    (Only if your colums are guaranteed to be fixed width AND you know the final number of colums, you could write the missing columns as spaces and then overwrite later. Still, it will be painful and inefficient, because column data are not adjacent in the file.)
    LabVIEW Champion . Do more with less code and in less time .

  • Converting object wrapper type array into equivalent primary type array

    Hi All!
    My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
    Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
    //Method signature
    Object createArray( Class clazz, String value ) throws Exception;
    //and usage should be as follows:
    Object arr = createArray( Integer.class, "2%%3%%4" );
    //"arr" will be passed as a parameter of a method again via reflection
    public void compute( Object... args ) {
        a = (int[])args[0];
    //or
    Object arr = createArray( Double.class, "2%%3%%4" );
    public void compute( Object... args ) {
        b = (double[])args[0];
    //and the method implementation -
    Object createArray( Class clazz, String value ) throws Exception {
         String[] split = value.split( "%%" );
         //create array, e.g. Integer[] or Double[] etc.
         Object[] o = (Object[])Array.newInstance( clazz, split.length );
         //fill the array with parsed values, on parse error exception will be thrown
         for (int i = 0; i < split.length; i++) {
              Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
              o[i] = meth.invoke( null, new Object[]{ split[i] });
         //here convert Object[] to Object of type int[] or double[] etc...
         /* and return that object*/
         //NB!!! I want to avoid the following code:
         if( o instanceof Integer[] ) {
              int[] ar = new int[o.length];
              for (int i = 0; i < o.length; i++) {
                   ar[i] = (Integer)o;
              return ar;
         } else if( o instanceof Double[] ) {
         //...repeat "else if" for all primary types... :(
         return null;
    Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
    Did I make myself clear? :)
    Thanks in advance,
    Pavel Grigorenko

    I think I've found the answer myself ;-)
    Never thought I could use something like int.class or double.class,
    so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
    and the easy solution is the following -
    Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
    for (int j = 0; j < split.length; j++) {
         Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
         Object val = meth.invoke( null, new Object[]{ split[j] });
         Array.set( primeArray, j, val );
    }where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc.

  • How do I modify an Array into a collection

    Hi I'm havin a real hard time modifying an Array into a collection, heres the code I'm working with
    I have to modify all the Arrays of this code....
    public class Student {
         private String           name;
         private float []      grades;
         private int           finalGrade;
         public Student(String name) {
              this.name      = name;
              this.grades = new float[5];
              for (int i = 0; i < grades.length; i ++) {
                   grades[i] = 0.0f;
              finalGrade = 0;
         public String toString() {
              String studentInfo = " Grades for " + name + ": ";
         for (int i = 0; i < grades.length; i ++)
         studentInfo += " " + grades;
         studentInfo += "\n final grade: " + getFinalGrade();
         return studentInfo;
         private void setFinalGrade() {
              float temp = 0.0f;
              for(int i = 0; i < grades.length; i++)
                   temp += grades[i];
              finalGrade = Math.round(temp/grades.length);
         public int getFinalGrade() {
              this.setFinalGrade();
              return finalGrade;
         public void setGrade( int index, float grade) {
              this.grades[index] = grade;
         public float[] getGrades() {
              return grades;
         public String getName() {
              return name;

    I'm kind of new at this I just started to learn about
    that, is there an example u could give me to inspire
    me ?
    Object[] o = new String[]{"one", "two", "five"};
    Collection ascollection = Arrays.asList(o);
    //the returned Collection (List) is unmodifiable,
    //so if we want to remove or add items, we need
    //a copy:
    Collection copy = new ArrayList(ascollection);
    copy.remove("two");
    String[] backagain = (String[]) copy.toArray(new String[copy.size()]);

  • How do I combine two arrays into one?

    I am trying to combine two byte arrays into one. What function do I use that will put in the information in the same order just combined?

    battler. wrote:
    Julien,
    Used LV for years.  Never knew that (concatenate inputs).  Wouldn't believe the lengths ive used to get around it.  Thanks
    Same here! I actually learned about it taking a sample test for the CLAD.
    Richard

  • Passing array into resultset

    hi,
    is it possible to pass an array into a resultset? if yes please indicate how.
    thank you all in advance

    Hi,
    Sorry for the confusion, here's what I'm trying to accomplish.
    I'm trying to create a report in Crystal Report and use Java as data source. My Java application needs to generate some value and pass them to the report as parameters. After some research I've found that I can use a Java Bean class as data source for Crystal Report that returns a ResultSet. Therefore I'm trying to pass some values in my Java app into the Bean class as array and convert them to a ResultSet for Crystal Report.
    If you know of a different way please let me know, otherwise, this is what I meant by passing array into resultset.
    thanks for your reply,

  • Append 2 arrays into 1

    im trying to append 2 arrays into 1 but i cant get it right!
    this is what i tried to do but im getting an error "'class' or 'interface' expected on line 14"
    plz help!!!
    import java.util.*;
    public class appendarrays {
         public static void main(String[] args) {
         int[] a = {1, 4, 9, 16, 9};
         int[] b = {11, 11, 7, 9, 16, 4, 1};
         append(a,b);
         System.out.println(Arrays.toString(ab));
    public static int[] append(int[] a, int[] b) {
         int[] ab = new int[a.length + b.length];
    System.arraycopy(a, 0, ab, 0, a.length);
    System.arraycopy(b, 0, ab, a.length, b.length);
    public String toSAtring() {
         return ab;
    }

    yoo hoo!!! it works now! thanks those who helped me here! i got it!
    import java.util.*;
    public class mergearrays {
         public static void main(String[] args) {
         int[] a = {1, 4, 9, 16, 9};
         int[] b = {11, 11, 7, 9, 16, 4, 1};
         int[] myArray = merge(a, b);
         System.out.println(Arrays.toString(myArray));
    public static int[] merge(int[] a, int[] b) {
       int[] newArray = new int[a.length + b.length];
       int i = 0;
       int len = a.length;
       for (int j = 0; j < len; j++) {
         newArray[i++] = a[j];
       len = b.length;
       for(int j = 0; j < len; j++) {
         newArray[i++] = b[j];
       return newArray;
    }as for the rest...take courses in helping people.

  • How to add data into JTable

    How can I add data into JTable, for instance ("Mike", "Gooler", 21).

    How can I add data into JTable, for instance ("Mike",
    "Gooler", 21).You will have very good results if you segregate out the table model as a seperate user class and provide a method to add a row there. In fact, if you use the table to reflect a database table you can add the row inplace using the existing cursor. I believe it's TableExample2 in the jdk\demo\jfc\TableExamples that has a very good example of this.
    Walt

  • Possible to insert array into db without looping?

    Hi there,
    I'm working on a Flex project that uses cfc's and MySQL. I
    have an ArrayCollection that I want to store in my db. I was
    thinking that I could store it as a BLOB. I'm taking a stab at it
    now but I thought I'd put the feelers out to see if anyone has any
    ideas of how to do this.
    Maybe a simpler way to put it:
    Is it possible to save an entire array into a database
    without looping through and storing each item in the array
    separately?
    Thanks.
    Novian

    For 1 dimensional arrays, you can either convert the array to
    a list - ArrayToList() or for more complicated structures you can
    serialize your data using XML, WDDX (a type of XML) or JSON. WDDX
    support is native to CF, you can find components online that will
    give you JSON support or you can roll your own XML
    conversion.

  • Divide an array into components

    Hello:
    I am developing a LV application that has, in some way, "two parts": One of them is the user interface and its associated block diagram, that receives values from controls and files. Then, this values are used for feeding the inputs of a "Call Library Function" node.
    Well, some of the values I use are components of an array. I thought that I could use a "Split array" block, but I cant connect the "1 component array" with the numerical input of the library node.
    How could I "convert" a "1 component array" into a "numerical value". I actually use a very improper method, I connect the "1 component" array to a "array max & min" block, and I use "max value" output (I could use min too, obviously).
    Another question that is related to this is the follwing: Is there any method in order to split an array into its numerical components? Because I have, for example, a 4 elements array, I wished to divide it (in an easy way, instead of having a "serial association" of 4 "split array" blocks) into 4 numerical values that are used for feeding a function node.
    Well, if you need any aditional info, please dont hesitate in ask for it. Thank you very much for your attention and please sorry for my bad english.
    Yours sincerely.
    Juan Crespo

    Juan,
    Apologies if I misunderstood, but is the 'Index Array' function the answer to both your questions?
    =====================================================
    Fading out. " ... J. Arthur Rank on gong."
    Attachments:
    Index Array Elements.jpg ‏12 KB

Maybe you are looking for

  • G4 Titanium - TV as display?

    I have a G4 titanium with no screen that my son was using for movies paired with an apple cinema display. The G4 is working fine, but has no screen. I wiped the HD and then verified it. The cinema display was sold and I am trying to sell the G4. A po

  • Sorting XML nodes in Java

    I have a java code that reads various xml files, filters cetain elements and writes the results of these files to one large xml file. Problem is, when the files are read into the large xml, all the nodes are sorted alphabetically. I tried looking for

  • Final Cut Pro Causing Hearing Damage *Big Problem*

    I've been experiencing a unique problem where I'm editing / playing footage back and out of nowhere a very loud blatting noise erupts from Final Cut Pro. When I'm wearing headphones the noise is catastrophic and I immediately I have to take the headp

  • The BMC reported failure in converting the document

    Hello, I have a problem with PDF generator. I launch a workflow with an attachment which contains a Word or a .ppt document. That document is sometimes well converted. But sometimes it is not well converted and a .log file is generated in the out dir

  • Error on JSF

    Hi all, Can someone please tell me why am I getting this error? Ever since I've installed jsf on eclipse to work with JSP/JavaServlet the Server (tomcat) being very temperamental it's fine at time and most of the time keeps greeting me with this erro