如何从Jtable获取所有值并绘制图形?

时间:2017-04-28 05:09:03

标签: java swing jtable jfreechart

我有一个jtable设置,我已经填充了.csv文件中的值。我需要从jtable中检索所有值并绘制它们,但是我很难搞清楚它。我使用了JFreeChart并设置了图表,但绝对坚持如何使用JTable中的值填充折线图。

我尝试过的代码,但是当我按下图表按钮时,它还没有工作,只是暂停了应用程序:

    //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);
    }
    }

整个代码:

//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                   

关于什么对我有用的任何想法?我从来没有必要从表中获取数据并绘制图表,所以这对我来说都是新的。如果我搞砸了某个地方,请告诉我。

1 个答案:

答案 0 :(得分:2)

series.add(r, c);

那不会做任何事情。你只是得到循环的索引。

你想要这样的东西:

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

当然getValueAt(...)方法只返回一个Object,因此您需要将Object转换为系列Object所需的数据类型。

此外,如果您需要系列对象的两个参数,那么您显然需要两个getValueAt(...)语句。也许你只有两列,所以你只需要在行上有一个循环,然后从第0列和第1列获得值?只有您知道表格中的数据。