Results 1 to 4 of 4
  1. #1
    Exceeder is offline Member
    Join Date
    Dec 2011
    Posts
    1
    Rep Power
    0

    Post Regarding jTable in Netbeans(FORMS).

    So I'm doing a school project and it requires for a jTable to be filled according to previous results (therefore not hard-coded). I have tried search the WEB but I can't find anything :S

    The table is jTable (drag and drop). Basically I need to extract results from previous methods and store them in the tables. I know how to fill it up hard-coded but not like this. The follow is the code, the bolded part is where the table is.

    Java Code:
    package tournament_;
    /**
     *
     * @author Vanessa
     */
    public class Statistics extends javax.swing.JFrame {
    
        /** Creates new form Statistics */
        public Statistics() {
            initComponents();
        }
        
       
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
           [B] jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {"Team 1", "2", null, null, null, null},
                    {"Team 2", "2", null, null, null, null},
                    {"Team 3", "2", null, null, null, null}
                },
                new String [] {
                    "Teams", "Played", "Wins", "Draw", "Lost", "Total"
                }
            ));
            jScrollPane1.setViewportView(jTable1);[/B]
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(33, 33, 33)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(45, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(61, 61, 61))
            );
    
            pack();
        }// </editor-fold>
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Statistics.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new Statistics().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration
        
    }
    Please help! :)

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: Regarding jTable in Netbeans(FORMS).

    Have you read the tutorial on JTables at the Oracle site?
    How to Use Tables (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
    It contains a lot of information on how to accomplish your requirements and then some. For instance, try created a custom table model or use a DefaultTableModel to edit the table data model.

  3. #3
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default Re: Regarding jTable in Netbeans(FORMS).

    I would suggest separating your JTable code from your GUI code to help you look at it closer.

    Create a new Java Class
    In NetBeans: Right-Click your package from your Projects list > New > Java Class...
    Name it something relevant like "StatsTable".

    You get the outline of the new class.

    Make an outline of all the fields and methods we need to add.
    To create a JTable, we need to fill out a String array of column names. We also need a 2D Object array of the JTable data and a method to fill the array with data. Finally, we'd need to be able to create a JTable from the data so we'd need a JTable field. Taking that in, your outline should look like this:
    Java Code:
    package your.package;
    public class StatsTable {
        private String[] columnNames;
        private Object[][] data;
        final private JTable table;
        //constructor - used to create a StatsTable
        public StatsTable(String[] columns, List<Team> teamsData) {
            columnNames = columns;
            data = fillData(teamsData);
            //create JTable
            table = new JTable(data, columnNames);
        }
        private Object[][] fillData(List<Team> teamsData) {
            //initialise 2D array with correct space
            data = new Object[teamsData.size()][columnNames.length];
            //loop to fill data
            ... 
            return data;
        }
        
    }
    Note: JTable will be underlined as red, click on it and press ALT+ENTER (in NetBeans) to auto-add the import (javax.swing.JTable).

    Viewing the JTable
    Now we'd want some sort of way so that when we call this new class and the JTable data is processed for us, we should be able to view it.
    Java Code:
    List<Team> teams = new ArrayList<Team>();
    //fill up team info
    ...
    String[] cols = new String[] {"Team Name", "No. of players", "Etc" };
    StatsTable table1 = new StatsTable(cols, teams);
    That alone will not allow you to see the JTable.
    If we make the class extend JPanel we can add the JTable to a JPanel (form) and then show the object.
    Java Code:
    public class StatsTable extends JPanel {
    ...
    private String title;
    //update constructor
    public StatsTable(..., String tableTitle) {
        ...
        title = tableTitle;
        ...
        JScrollPane tableContainer = new JScrollPane(table);
        add(tableContainer);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                show();
            }
        }
    }
    ...
    public void show() {
            JFrame frame = new JFrame(title);
            this.setOpaque(true);
            frame.setContentPane(this);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }
    Now when we create a new instance of StatsTable(...) a new JTable GUI should appear.
    Last edited by ozzyman; 12-17-2011 at 04:05 PM.

  4. #4
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: Regarding jTable in Netbeans(FORMS).

    Quote Originally Posted by ozzyman
    I would suggest separating your JTable code from your GUI code to help you look at it closer...
    For what its worth, I would much rather implement TableModel (or extends AbstractTableModel/DefaultTableModel) as explained in the link I posted above. It allows much more flexibility in updating the table, separating the model from the view, and using custom data models (thus removing the need to copy data into arrays). And always watch out for naming methods that can override methods which already exist - whether deprecated or not.
    Last edited by doWhile; 12-17-2011 at 06:42 PM.

Similar Threads

  1. Showing NetBeans-generated Swing forms
    By _SAS in forum AWT / Swing
    Replies: 0
    Last Post: 06-19-2010, 02:45 AM
  2. JTable netbeans help
    By karno in forum NetBeans
    Replies: 1
    Last Post: 03-31-2010, 03:45 AM
  3. Netbeans JTable
    By sysout in forum NetBeans
    Replies: 6
    Last Post: 08-26-2009, 02:27 AM
  4. Replies: 2
    Last Post: 04-28-2008, 10:56 AM
  5. Creating Sub forms in java netbeans 5.0
    By java_newbie in forum NetBeans
    Replies: 14
    Last Post: 08-06-2007, 07:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •