Using values from a for loop in a function outside

2019-08-15 07:57发布

I need to take values that I find from inside a for loop to use in a function that isn't inside the loop, and I can't figure out how to do this. What I am hoping to accomplish is to extract values from a key in a hashmap to then plot in a JTable only if that row is selected (using a ListSelectionListener). This way, I can avoid graphing a hundred tables which would save a lot of time. Also I am using DefaultTableModel.

This is my for loop:

tableMaker(model);
for(Map.Entry<String,NumberHolder> entry : entries)
{   
  //add rows for each entry of the hashmap to the table             

  double[] v = new double[entry.getValue().singleValues.size()];
  int i = 0;
  for(Long j : entry.getValue().singleValues)
  {
    v[i++] = j.doubleValue();
  }                  
  //right here I need to take "v" 
  //and use it in my tableMaker function for that specific row
}                  

In my tableMaker function, I create my JTable and add a ListSelectionListener, where I hope to create a histogram when a row is selected and add it to my lowerPanel. This is some of the code. I need v so that I can create the dataSet.

public static void tableMaker(DefaultTableModel m)
{
   JPanel lowerPanel = new JPanel();

   //create table here

   frame.getContentPane().add(lowerPanel, BorderLayout.SOUTH);
   table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    table.getSelectionModel().addListSelectionListener(
            new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    JFreeChart chart = ChartFactory.createHistogram(
                        plotTitle, xaxis, yaxis, dataset, orientation,
                        show, toolTips, urls);                      
                //  lowerPanel.add(chart);
                //  lowerPanel.revalidate();
                }
            }
        });
}

1条回答
叼着烟拽天下
2楼-- · 2019-08-15 08:40

I sense that you are trying to implement the approach outlined here. Instead of trying to create a new chart each time, create a single chart in a ChartPanel and retain a reference to its XYPlot. In your ListSelectionListener, you can then use plot.setDataset() to update the chart. In this example, a ChangeListener fetches the desired dataset from an existing List<XYDataset>. In this example, a button's ActionListener generates the dataset each time it is called.

查看更多
登录 后发表回答