Search code examples
javaswingjtablejfreechart

How to get ALL values from a Jtable and graph them?


I have a jtable set up that I've populated with values from a .csv file. I need to retrieve all of the values from the jtable and graph them, but am having trouble figuring it out. I'm using JFreeChart and have set up the graph but am absolutely stuck on how to populate the line graph with values from the JTable.

Code that I've tried, but isn't working and simply halts the application when I hit the graph button:

    //instantiate the data series and the chart
    int row = tableRadio.getRowCount();
    int column = tableRadio.getColumnCount();
    for (int r = 0; r  < row; r++) {
    for (int c = 0; c  < column; c++) {
    series.add(r, c);
    }
    }

Entire Code:

//data used by all methods
DefaultTableModel tableModel;

//Global variables
XYSeries series;            //series of data that will be added to the graph
XYSeriesCollection dataSet; //a collection object holds the series
JFreeChart chart;           //chart to be placed on the panel

public MainWindow() {
    initComponents();

    //instantiate the DefaultTableModel
    tableModel = (DefaultTableModel) tableRadio.getModel();

    //instantiate the data series and the chart
    series = new XYSeries("Random Numbers");
    dataSet = new XYSeriesCollection(series);
    chart = ChartFactory.createXYLineChart("Radio Astronomy Graphing", "Time", "Sensor Value", dataSet);

    //display the graphing chart on the panel
    panelGraph.add(new ChartPanel(chart), BorderLayout.CENTER);
    panelGraph.revalidate();

    //center the applications window upon start
    this.setLocationRelativeTo(null);



}

/**
 * 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() {

    buttonLoad = new javax.swing.JButton();
    buttonGraph = new javax.swing.JButton();
    buttonSave = new javax.swing.JButton();
    buttonAdd = new javax.swing.JButton();
    buttonEdit = new javax.swing.JButton();
    buttonRemove = new javax.swing.JButton();
    labelValue = new javax.swing.JLabel();
    tfMonth = new javax.swing.JTextField();
    tfValue = new javax.swing.JTextField();
    tfDay = new javax.swing.JTextField();
    labelHour = new javax.swing.JLabel();
    labelMin = new javax.swing.JLabel();
    labelYear = new javax.swing.JLabel();
    labelDay = new javax.swing.JLabel();
    labelMonth = new javax.swing.JLabel();
    tfYear = new javax.swing.JTextField();
    tfHour = new javax.swing.JTextField();
    tfMin = new javax.swing.JTextField();
    panelGraph = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    tableRadio = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    buttonLoad.setText("Load File");
    buttonLoad.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonLoadActionPerformed(evt);
        }
    });

    buttonGraph.setText("Graph Data");
    buttonGraph.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonGraphActionPerformed(evt);
        }
    });

    buttonSave.setText("Save");
    buttonSave.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonSaveActionPerformed(evt);
        }
    });

    buttonAdd.setText("Add");
    buttonAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonAddActionPerformed(evt);
        }
    });

    buttonEdit.setText("Edit");
    buttonEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonEditActionPerformed(evt);
        }
    });

    buttonRemove.setText("Remove");
    buttonRemove.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonRemoveActionPerformed(evt);
        }
    });

    labelValue.setText("Sensor Value:");

    tfValue.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tfValueActionPerformed(evt);
        }
    });

    labelHour.setText("Hour");

    labelMin.setText("Minute");

    labelYear.setText("Year");

    labelDay.setText("Day");

    labelMonth.setText("Month");

    panelGraph.setLayout(new java.awt.BorderLayout());

    tableRadio.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "Date and Time", "Sensor Value"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(tableRadio);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(buttonLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(buttonSave, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(buttonGraph, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(buttonAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(84, 84, 84)
                            .addComponent(labelMonth)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(labelDay)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(buttonEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(buttonRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(87, 87, 87)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(labelValue)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(labelHour)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(15, 15, 15)
                                    .addComponent(labelMin)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(labelYear)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(0, 17, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(42, 42, 42)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(buttonLoad)
                .addComponent(buttonAdd)
                .addComponent(labelMonth)
                .addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(labelDay)
                .addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(labelYear)
                .addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(buttonGraph)
                .addComponent(buttonEdit)
                .addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(labelHour)
                .addComponent(labelMin)
                .addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(buttonSave)
                .addComponent(buttonRemove)
                .addComponent(labelValue)
                .addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(35, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void buttonLoadActionPerformed(java.awt.event.ActionEvent evt) {                                           
//Load file into table

//create JFileChooser
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);

//create myFile and define the path
File myFile = fileChooser.getSelectedFile();

try{
    //instantiate Scanner
    Scanner inputStream = new Scanner(myFile);

    for(int i=0; i < 12; i++){
    inputStream.nextLine();
    }

    //split values into 2 arrays and insert into table
    while (inputStream.hasNext()) {
        String data = inputStream.next();
        String[] values = data.split(",");
        tableModel.insertRow(tableModel.getRowCount(), values);

    }//end of while block
}//end of try block
catch(FileNotFoundException e) {
        JOptionPane.showMessageDialog(this, "File Not Found");
}//end of catch block
}                                          

private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {                                          
    //add info from text fields and combo boxes to table

    try {
       //create variables to hold the contents of what user has typed in
    int Month = Integer.parseInt(tfMonth.getText());
    int Day = Integer.parseInt(tfDay.getText());
    int Year = Integer.parseInt(tfYear.getText());
    int Hour = Integer.parseInt(tfHour.getText());
    int Min = Integer.parseInt(tfMin.getText());
    double Value = Double.parseDouble(tfValue.getText());



        //add the info to the table
        tableModel.insertRow(tableModel.getRowCount(), new Object[]{Month + "/" + Day + "/" + Year + " " + Hour + ":" + Min, Value });

        //clear the controls on the interface
        tfMonth.setText("");
        tfDay.setText("");
        tfYear.setText("");
        tfHour.setText("");
        tfMin.setText("");
        tfValue.setText("");

    }//end of try block

    catch(NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Please fill out all fields and enter only numbers");
    }//end of catch block
}                                         

private void buttonEditActionPerformed(java.awt.event.ActionEvent evt) {                                           
    //edit info based on row selected

    //make sure a row is selected
    if(tableRadio.getSelectedRow() >= 0){

        //set the values in the table for all text fields
        tableModel.setValueAt(tfMonth.getText() + "/" + tfDay.getText() + "/" + tfYear.getText() + " " + tfHour.getText() + ":" + tfMin.getText(), tableRadio.getSelectedRow(), 0);
        tableModel.setValueAt(tfValue.getText(), tableRadio.getSelectedRow(), 1);

        //clear the user interface controls after adding them to the table
        tfMonth.setText("");
        tfDay.setText("");
        tfYear.setText("");
        tfHour.setText("");
        tfMin.setText("");
        tfValue.setText("");
    }//end of if block checking for selected row
    else{
        JOptionPane.showMessageDialog(this, "Please select a row.");
    }//end of else block
}                                          

private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    //Delete the selected row

    //Make sure a row is selected
    if(tableRadio.getSelectedRow() >= 0){
        //remove the row
        tableModel.removeRow(tableRadio.getSelectedRow());

        //clear the user interface controls after deleting a row
        tfMonth.setText("");
        tfDay.setText("");
        tfYear.setText("");
        tfHour.setText("");
        tfMin.setText("");
        tfValue.setText("");
    }//end of if block
    else{
        JOptionPane.showMessageDialog(this, "Please select a row.");
    }//end of else block
}                                            

private void buttonGraphActionPerformed(java.awt.event.ActionEvent evt) {                                            

    //instantiate the data series and the chart
    int row = tableRadio.getRowCount();
    int column = tableRadio.getColumnCount();
    for (int r = 0; r  < row; r++) {
    for (int c = 0; c  < column; c++) {
    series.add(r, c);
    }
    }
}                                           

private void tfValueActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {                                           
 try {
    // capture the whole screen
    BufferedImage radioGraph = new Robot().createScreenCapture( 
    new Rectangle( panelGraph.getX(), panelGraph.getY(), panelGraph.getWidth(), panelGraph.getHeight() ) );

    //Save as PNG
    File file = new File("radioGraph.png");
    ImageIO.write(radioGraph, "png", file);

    JOptionPane.showMessageDialog(this, "radioGraph.png added to project folder");
}
catch(AWTException e) {
    JOptionPane.showMessageDialog(this, "Error");
}
catch(IOException e){
    JOptionPane.showMessageDialog(this, "Error"); 
}
}                                          

/**
 * @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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainWindow().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton buttonAdd;
private javax.swing.JButton buttonEdit;
private javax.swing.JButton buttonGraph;
private javax.swing.JButton buttonLoad;
private javax.swing.JButton buttonRemove;
private javax.swing.JButton buttonSave;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelDay;
private javax.swing.JLabel labelHour;
private javax.swing.JLabel labelMin;
private javax.swing.JLabel labelMonth;
private javax.swing.JLabel labelValue;
private javax.swing.JLabel labelYear;
private javax.swing.JPanel panelGraph;
private javax.swing.JTable tableRadio;
private javax.swing.JTextField tfDay;
private javax.swing.JTextField tfHour;
private javax.swing.JTextField tfMin;
private javax.swing.JTextField tfMonth;
private javax.swing.JTextField tfValue;
private javax.swing.JTextField tfYear;
// End of variables declaration                   

Any Ideas on what might work for me? I've never had to get data from a table and graph it so this is all new to me. Please let me know if I've messed up somewhere.


Solution

  • series.add(r, c);
    

    That won't do anything. You are just getting the indexes of your loop.

    You want something like:

    series.add( tableRadio.getValueAt(r, c) );
    

    Of course the getValueAt(...) method just returns an Object so you will need to convert the Object to the data type needed for the series Object.

    Also if you need two parameter for the series Object, then you will obviously need two getValueAt(...) statements. Maybe you only have two columns, so you only need a single loop on the rows and then you get the value from column 0 and column 1? Only you know the data you have in your table.