How to make a runnable thread for my charts? - java

My program is up and working like I wanted it but now I want to implement Runnable in my program so I could show each tab that my chart runs. How should I do this? I've tried using the methods that I did before but I could not correlate it into my program.
public class Induction {
final static String titles[] = {"A","B","C","S", "SH", "W"};
private final static TimeSeriesCollection all = new TimeSeriesCollection();
static Day day = new Day(9,7,2014);
private static TimeSeriesCollection createInduction() {
for (String s : titles) {
all.addSeries(new TimeSeries(s));
}
// while parsing the CSV file
String zone = "/home/a002384/ECLIPSE/IN070914.CSV";
TimeSeries ts = all.getSeries(zone);
TreeMap<String, TreeMap<Integer, Integer[]>> zoneMap = new TreeMap<String, TreeMap<Integer, Integer[]>>();
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(zone));
String line;
try {
// Read a line from the csv file until it reaches to the end of the file...
while ((line = bufferedReader.readLine()) != null)
{
// Parse a line of text in the CSV
String [] indData = line.split("\\,");
long millisecond = Long.parseLong(indData[0]);
String zones = indData[1];
// The millisecond value is the # of milliseconds since midnight
// From this, we can derive the hour and minute of the day
// as follows:
int secOfDay = (int) (millisecond / 1000);
int hrOfDay = secOfDay / 3600;
int minInHr = secOfDay % 3600 / 60;
// Obtain the induction rate TreeMap for the current zone
// If this is a "newly-encountered" zone, create a new TreeMap
TreeMap<Integer, Integer[]> hourCountsInZoneMap;
if (zoneMap.containsKey(zones))
hourCountsInZoneMap = zoneMap.get(zones);
else
hourCountsInZoneMap = new TreeMap<Integer, Integer[]>();
// Obtain the induction rate array for the current hour
// in the current zone.
// If this is a new hour in the current zone, create a
// new array, and initialize this array with all zeroes.
// The array is size 60, because there are 60 minutes in
// the hour. Each element in the array represents the
// induction rate for that minute
Integer [] indRatePerMinArray;
if (hourCountsInZoneMap.containsKey(hrOfDay))
indRatePerMinArray = hourCountsInZoneMap.get(hrOfDay);
else
{
indRatePerMinArray = new Integer[60];
Arrays.fill(indRatePerMinArray, 0);
}
// Increment the induction rate for the current minute
// by one. Each line in the csv file represents a
// single induction at a single point in time
indRatePerMinArray[minInHr]++;
// Add everything back into the TreeMaps if these are
// newly created.
if (!hourCountsInZoneMap.containsKey(hrOfDay))
hourCountsInZoneMap.put(hrOfDay, indRatePerMinArray);
if (!zoneMap.containsKey(zones))
zoneMap.put(zones, hourCountsInZoneMap);
}
}
finally
{
bufferedReader.close();
}
}
catch (Exception e){
e.printStackTrace();
}
// Iterate through all zones and print induction rates
// for every minute into every hour by zone ...
Iterator<String> zoneIT = zoneMap.keySet().iterator();
while (zoneIT.hasNext())
{
String zones2 = zoneIT.next();
TreeMap<Integer, Integer[]> hourCountsInZoneMap = zoneMap.get(zones2);
System.out.println("ZONE " + zones2 + ":");
Iterator<Integer> hrIT = hourCountsInZoneMap.keySet().iterator();
while (hrIT.hasNext())
{
int hour = hrIT.next();
Integer [] indRatePerMinArray = hourCountsInZoneMap.get(hour);
for (int i = 0; i < indRatePerMinArray.length; i++)
{
System.out.print(hour + ":");
System.out.print(i < 10 ? "0" + i : i);
System.out.println(" = " + indRatePerMinArray[i] + "induction(s)");
}
}
}
TimeSeries s1 = new TimeSeries("A");
TreeMap<Integer, Integer[]> dayAZone = zoneMap.get("A");
Iterator<Integer> hourIT = dayAZone.keySet().iterator();
while (hourIT.hasNext())
{
Integer indHour = hourIT.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = dayAZone.get(indHour);
for (int i = 0; i < 60; i++)
s1.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
TimeSeries s2 = new TimeSeries("B");
TreeMap<Integer, Integer[]> dayBZone = zoneMap.get("B");
Iterator<Integer> hourIT1 = dayBZone.keySet().iterator();
while (hourIT1.hasNext())
{
Integer indHour = hourIT1.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = dayBZone.get(indHour);
for (int i = 0; i < 60; i++)
s2.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
TimeSeries s3 = new TimeSeries("C");
TreeMap<Integer, Integer[]> dayCZone = zoneMap.get("C");
Iterator<Integer> hourIT2 = dayCZone.keySet().iterator();
while (hourIT2.hasNext())
{
Integer indHour = hourIT2.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = dayCZone.get(indHour);
for (int i = 0; i < 60; i++)
s3.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
TimeSeries s4 = new TimeSeries("S");
TreeMap<Integer, Integer[]> daySZone = zoneMap.get("S");
Iterator<Integer> hourIT3 = daySZone.keySet().iterator();
while (hourIT3.hasNext())
{
Integer indHour = hourIT3.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = daySZone.get(indHour);
for (int i = 0; i < 60; i++)
s4.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
TimeSeries s5 = new TimeSeries("SH");
TreeMap<Integer, Integer[]> daySHZone = zoneMap.get("SH");
Iterator<Integer> hourIT4 = daySHZone.keySet().iterator();
while (hourIT4.hasNext())
{
Integer indHour = hourIT4.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = daySHZone.get(indHour);
for (int i = 0; i < 60; i++)
s5.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
TimeSeries s6 = new TimeSeries("W");
TreeMap<Integer, Integer[]> dayWZone = zoneMap.get("W");
Iterator<Integer> hourIT5 = dayWZone.keySet().iterator();
while (hourIT5.hasNext())
{
Integer indHour = hourIT5.next();
Hour hour = new Hour(indHour, day);
Integer [] indMins = dayWZone.get(indHour);
for (int i = 0; i < 60; i++)
s6.addOrUpdate(new Minute(i, hour), indMins[i]);
System.out.println(zoneMap);
}
all.addSeries(s1);
all.addSeries(s2);
all.addSeries(s3);
all.addSeries(s4);
all.addSeries(s5);
all.addSeries(s6);
return all;
}
private static ChartPanel createPane(String title) {
TimeSeriesCollection dataset = new ``TimeSeriesCollection(all.getSeries(title));
int j = 0;
JFreeChart chart = ChartFactory.createXYBarChart(
"Induction Chart Zone ",
"Hour",
true,
"Inductions Per Minute",
dataset,
PlotOrientation.VERTICAL,
false,
true,
false
);
XYPlot plot = (XYPlot)chart.getPlot();
XYBarRenderer renderer = (XYBarRenderer)plot.getRenderer();
renderer.setBarPainter(new StandardXYBarPainter());
renderer.setDrawBarOutline(false);
// Set an induction of 30 per minute...
Marker target = new ValueMarker(30);
target.setPaint(java.awt.Color.blue);
target.setLabel("Rate");
plot.addRangeMarker(target);
return new ChartPanel(chart);
}
public static void main(String[] args) {
createInduction();
final JFrame frame = new JFrame("Induction Zone Chart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
final int j = 0;
jtp.add(titles[j], createPane("A"));
jtp.add(titles[j+1], createPane("B"));
jtp.add(titles[j+2], createPane("C"));
jtp.add(titles[j+3], createPane("S"));
jtp.add(titles[j+4], createPane("SH"));
jtp.add(titles[j+5], createPane("W"));
for (String s : titles) {
jtp.add(createPane(s));
}
jtp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
ChartPanel chart = null;
for (int i = 0; i < titles.length; i++)
{
chart = createPane(titles[i].substring(1, titles[i].length()));
}
final JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Update") {
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}));
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
int index = sourceTabbedPane.getSelectedIndex();
String tabTitle = sourceTabbedPane.getTitleAt(index);
createPane(tabTitle.substring(0, tabTitle.length()));
System.out.println("Source to " + tabTitle);
}
};
while (jtp.getTabCount() > 6)
jtp.remove(6);
jtp.addChangeListener(changeListener);
frame.add(jtp, BorderLayout.CENTER);
frame.add(p, BorderLayout.SOUTH);
frame.setPreferredSize(new Dimension(1000, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Update each chart's model, an instance of TimeSeries, in the background of a SwingWorker. A complete example is shown here. The listening view, an instance of ChartPanel, will update itself accordingly.

Related

Java - Treat data from a file

I have a file that looks like this:
year population
1952 120323
1953 136688
1954 161681
.... .....
I want to go in that find the year with the largest increase in population as compared to the previous year.
I tried th following code but I get a the NoSuchElementException and I'm not sure why:
String path = "filePath";
File file = new File(filePath);
Scanner sc = new Scanner(file);
int y = 0, y1, y2, p1, p2, diff = 0;
while(sc.hasNext()){
if(sc.next().equals("year") || sc.next().equals("population")){
break;
}else{
y1 = Integer.parseInt(sc.next());
p1 = Integer.parseInt(sc.next());
y2 = Integer.parseInt(sc.next()); // this line throws the exception
p2 = Integer.parseInt(sc.next());
if(p2 - p1 > diff){
diff = y2-y1;
y = y2;
}
}
}
System.out.println(y);
Not sure how your code produced NoSuchElementException error. Because you are exiting from the loop when you find "year" or "population". Hope the following code should meet your expected result.
String path = "filePath";
File file = new File (path);
Scanner scanner = new Scanner(file);
Long[][] yd = new Long[0][];
long prev = 0;
for(scanner.nextLine();scanner.hasNext();){
long year = scanner.nextLong();
long curnt = scanner.nextLong();
long diff = prev==0?prev:curnt-prev;
prev = curnt;
yd = Arrays.copyOf(yd, yd.length+1);
yd[yd.length-1] = new Long[2];
yd[yd.length-1][0] = year;
yd[yd.length-1][1] = diff;
}
Arrays.sort(yd, new Comparator<Long[]>() {
#Override
public int compare(Long[] o1, Long[] o2) {
Long diffOne = o1[1];
Long diffTwo = o2[1];
return diffTwo.compareTo(diffOne);
}
});
System.out.println("Year="+yd[0][0]+"; Difference="+yd[0][1]);
Try this...
String path = "filePath";
File file = new File (filePath);
Scanner sc = new Scanner(file);
long year = 0L, population = 0L, largestDiff = 0L;
while (sc.hasNext()) {
String line = sc.nextLine();
if (line.startsWith("year")) {
continue;
} else {
String[] parts = line.split(" +"); // Note the space before "+"
long currentYear = Long.parseLong(parts[0]);
long currentPopulation = Long.parseLong(parts[1]);
long diff = currentPopulation - population;
if (dif > largestDiff) {
largestDiff = diff;
year = currentYear;
}
population = currentPopulation;
}
}
System.out.println(year);
System.out.println(largestDiff);

ArrayList Index Error

I am trying to finish up a project that uses a graphical User Interface to search through a data Base of geysers in the US. I keep getting an error for one of my Array Lists. I would include my data for the program but is is 10,000 entries long. Any help much appreciated. This is being done in BlueJ
Error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
DataBase Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class GeyserDatabase
{
private ArrayList < Geyser > Geysers;
private ArrayList < Eruption > Eruptions;
public GeyserDatabase() {
Geysers = new ArrayList < Geyser >();
Eruptions = new ArrayList < Eruption >();
}
public void readGeyserData(String filename){
try{
File f = new File(filename);
Scanner sc = new Scanner(f);
String text;
// keep reading as long as there is more data
while(sc.hasNext()) {
text = sc.nextLine();
Eruption e = new Eruption(text);
Eruptions.add(e);
}
sc.close();
}
catch(IOException e) {
System.out.println("Failed to read the data file: " + filename);
}
createGeyserList();
}
public void addEruption (Eruption e){
Eruptions.add(e);
}
public ArrayList <Eruption> getEruptionList(){
return Eruptions;
}
public ArrayList <Geyser> getGeyserList(){
return Geysers;
}
public int getNumEruptions() {
return Eruptions.size();
}
public int getNumEruptions(int m,int d,int y) {
int count = 0;
for ( Eruption e : Eruptions) {
if (e.getMonth()==m && e.getDay()==d && e.getYear()==y) {
count++;
}
}
return count;
}
public Eruption getLateNightEruption() {
Eruption latestEruption = Eruptions.get(0);
int latestHour = latestEruption.getHour();
int latestMinute = latestEruption.getMinute();
for ( Eruption e: Eruptions ) {
if (e.getHour() > latestHour || (e.getHour()==latestHour && e.getMinute()>latestMinute)) {
latestEruption = e;
latestHour = e.getHour();
latestMinute = e.getMinute();
}
}
return latestEruption;
}
public ArrayList < Eruption > getEruptions(String geyser) {
ArrayList < Eruption > result = new ArrayList < Eruption > ();
for ( Eruption e: Eruptions ) {
if (e.getGeyserName().startsWith(geyser)) {
result.add(e);
}
}
return result;
}
private void createGeyserList(){
ArrayList<String>nameList = new ArrayList<String>();
// create temporary list of unique geyser names
for(Eruption e:Eruptions){
if(!nameList.contains(e.getGeyserName())){
nameList.add(e.getGeyserName());
}
}
// create a list of geysers
ArrayList<Geyser>geyserList = new ArrayList<Geyser>();
for(String s:nameList){
Geyser g = new Geyser(s);
// count number of eruptions for current geyser name
for(Eruption e:Eruptions){
if(e.getGeyserName().equals(g.getName()))
g.increment();
}
geyserList.add(g);
}
}
public int getMostGeysers(){
return Geysers.size();
}
public Geyser findMostActiveGeyser(){
Geyser MostEruptions = Geysers.get(0);
int mostActive = MostEruptions.getNumEruptions();
for( Geyser g : Geysers){
if(g.getNumEruptions() > mostActive){
MostEruptions =g;
mostActive = g.getNumEruptions();
}
}
return MostEruptions;
}
public Geyser findLeastActiveGeyser()
{
Geyser leastActiveGeyser = Geysers.get(0);
int leastActive = leastActiveGeyser.getNumEruptions();
for(Geyser g: Geysers)
{
if(g.getNumEruptions() < leastActive)
{
leastActiveGeyser = g;
leastActive = g.getNumEruptions();
}
}
return leastActiveGeyser;
}
public String findDayWithMostEruptions(int y){
int dayMost = 1;
int monthMost = 1;
int maxSoFar = getNumEruptions(1,1,y);
for(int m = 1; m<=12; m++){
for(int d = 1; d<=31;d++){
int eruptionsDay = getNumEruptions(m,d,y);
if(eruptionsDay>maxSoFar){
dayMost = d;
monthMost = m;
maxSoFar=eruptionsDay;
}
}
}
return monthMost + "/" + dayMost + "/" + y + "Eruptions: " + maxSoFar;
}
public static void main(String args[]){
GeyserDatabase gdb = new GeyserDatabase();
}
}
GUI Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.text.*;
/***********************************************************************
* GUI front end for a Yellowstone Geyser database
*
* #author Scott Grissom
* #version August 1, 2016
public class GeyserGUI extends JFrame implements ActionListener{
/** results box */
private JTextArea resultsArea;
private GeyserDatabase db;
/**JButtons */
private JButton findLateNightEruption;
private JButton findAmountOfEruptionsonDate;
private JButton findMaxEruptionsInYear;
private JButton findGeyserByName;
private JButton findMostActiveGeyser;
private JButton findLeastActiveGeyser;
private JButton getGeyserList;
private JTextField month;
private JTextField day;
private JTextField Year;
private JTextField geyser;
/** menu items */
private JMenuBar menus;
private JMenu fileMenu;
private JMenu reportsMenu;
private JMenuItem quitItem;
private JMenuItem openItem;
private JMenuItem countItem;
private JMenuItem geyserItem;
/*********************************************************************
Main Method
*********************************************************************/
public static void main(String arg[]){
GeyserGUI gui = new GeyserGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Yellowstone Geysers");
gui.pack();
gui.setVisible(true);
}
/*********************************************************************
Constructor - instantiates and displays all of the GUI commponents
*********************************************************************/
public GeyserGUI(){
db = new GeyserDatabase();
// FIX ME: the following line should be removed
db.readGeyserData("GeyserData.txt");
// create the Gridbag layout
setLayout(new GridBagLayout());
GridBagConstraints position = new GridBagConstraints();
// create the Results Text Area (5 x 10 cells)
resultsArea = new JTextArea(20,40);
JScrollPane scrollPane = new JScrollPane(resultsArea);
position.gridx = 0;
position.gridy = 0;
position.gridheight = 10;
position.gridwidth = 5;
position.insets = new Insets(20,20,0,0);
add(scrollPane, position);
/*******************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 0;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Month"), position);
position = new GridBagConstraints();
position.gridx = 0;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
month = new JTextField(2);
add(month, position);
/*************************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 1;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Day"), position);
position = new GridBagConstraints();
position.gridx = 1;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
day = new JTextField(2);
add(day, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 2;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Year"), position);
position = new GridBagConstraints();
position.gridx = 2;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
Year = new JTextField(4);
add(Year, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 3;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Geyser"), position);
position = new GridBagConstraints();
position.gridx = 3;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
geyser = new JTextField(12);
add(geyser, position);
/*********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 0;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Eruptions"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 1;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLateNightEruption = new JButton("Late Night Eruption");
findLateNightEruption.addActionListener(this);
add(findLateNightEruption, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 2;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findAmountOfEruptionsonDate = new JButton("# On Date");
findAmountOfEruptionsonDate.addActionListener(this);
add(findAmountOfEruptionsonDate, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 3;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMaxEruptionsInYear = new JButton("Max Eruptions in Year");
findMaxEruptionsInYear.addActionListener(this);
add(findMaxEruptionsInYear, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 4;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findGeyserByName = new JButton("By Name");
findGeyserByName.addActionListener(this);
add(findGeyserByName, position);
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 5;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Geysers"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 6;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMostActiveGeyser = new JButton("Most Active");
findMostActiveGeyser.addActionListener(this);
add(findMostActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 7;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLeastActiveGeyser = new JButton("Least Active");
findLeastActiveGeyser.addActionListener(this);
add(findLeastActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 8;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
getGeyserList = new JButton("Geyser List");
getGeyserList.addActionListener(this);
add(getGeyserList, position);
// set up File menus
setupMenus();
pack();
}
/*********************************************************************
List all entries given an ArrayList of eruptions. Include a final
line with the number of eruptions listed
#param m list of eruptions
*********************************************************************/
private void displayEruptions(ArrayList <Eruption> m){
resultsArea.setText("");
for(Eruption e: m){
resultsArea.append("\n" + e.toString());
}
resultsArea.append ("\nNumber of Geysers: " + m.size());
}
/*********************************************************************
Respond to menu selections and button clicks
#param e the button or menu item that was selected
*********************************************************************/
public void actionPerformed(ActionEvent e){
Eruption item = null;
// either open a file or warn the user
if (e.getSource() == openItem){
openFile();
}else if(db.getNumEruptions() == 0){
String errorMessage = "Did you forget to open a file?";
resultsArea.setText(errorMessage);
return;
}
// menu item - quit
else if (e.getSource() == quitItem){
System.exit(1);
}
// FIX ME: Count menu item - display number of eruptions and geysers
else if (e.getSource() == countItem){
resultsArea.setText("\nNumber of Eruptions: " + db.getNumEruptions());
}
// FIX ME: display late night eruption
else if (e.getSource() == findLateNightEruption){
resultsArea.setText("Latest Eruption\n" + db.getLateNightEruption());
}
//FIX ME: display all geyser names
else if (e.getSource() == getGeyserList){
displayEruptions(db.getEruptionList());
}
//FIX ME: max eruptions day in a year (check for year)
else if(e.getSource() == findMaxEruptionsInYear){
String aux = Year.getText();
if(aux.length() == 0){
JOptionPane.showMessageDialog(this, "Enter a Year to Search For Maax Eruptions");
}
else
{
int y = Integer.parseInt(Year.getText());
String result = db.findDayWithMostEruptions(y);
resultsArea.setText(result);
}
}
// FIX ME: list all eruptions for a geyser (check for name)
else if(e.getSource() == findGeyserByName){
String name = geyser.getText();
if(name.length() == 0){
JOptionPane.showMessageDialog(this, "Provide Name");
}
else
{
ArrayList<Eruption>result = db.getEruptions(name);
displayEruptions(result);
}
}
// FIX ME: display eruptions for a particular date
else if(e.getSource()==findAmountOfEruptionsonDate){
String aux1 = Year.getText();
String aux2 = month.getText();
String aux3 = day.getText();
if(aux1.length() == 0 || aux2.length() == 0 || aux3.length() == 0)
{
JOptionPane.showMessageDialog(this, "Provide year,month, and day");
}
else
{
int y = Integer.parseInt(Year.getText());
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int result = db.getNumEruptions(m, d, y);
resultsArea.setText("Number of Eruptions: " + result);
}
}
else if(e.getSource() == findMostActiveGeyser){
resultsArea.setText("Most active Geyser: " + db.findMostActiveGeyser());
}
else if(e.getSource() == findLeastActiveGeyser){
resultsArea.setText("Least active Geyser: " + db.findLeastActiveGeyser());
}
}
/*********************************************************************
In response to the menu selection - open a data file
*********************************************************************/
private void openFile(){
JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
int returnVal = fc.showOpenDialog(this);
// did the user select a file?
if (returnVal == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
// use the name of your lottery ticket variable
db.readGeyserData(filename);
}
}
/*********************************************************************
Create a custom gridbag constraint
*********************************************************************/
private GridBagConstraints makeConstraints(int x, int y, int h, int w, int align){
GridBagConstraints rtn = new GridBagConstraints();
rtn.gridx = x;
rtn.gridy = y;
rtn.gridheight = h;
rtn.gridwidth = w;
// set alignment: LINE_START, CENTER, LINE_END
rtn.anchor = align;
return rtn;
}
/*********************************************************************
Set up the menu items
*********************************************************************/
private void setupMenus(){
// create menu components
fileMenu = new JMenu("File");
quitItem = new JMenuItem("Quit");
openItem = new JMenuItem("Open...");
reportsMenu = new JMenu("Reports");
countItem = new JMenuItem("Counts");
// assign action listeners
quitItem.addActionListener(this);
openItem.addActionListener(this);
countItem.addActionListener(this);
// display menu components
fileMenu.add(openItem);
fileMenu.add(quitItem);
reportsMenu.add(countItem);
menus = new JMenuBar();
menus.add(fileMenu);
menus.add(reportsMenu);
setJMenuBar(menus);
}
}
Geyser Code:
import java.util.Scanner;
public class Geyser
{
String geyserName;
int count = 0;
public Geyser (String name){
geyserName = name;
}
public void increment (){
count++;
}
public String getName() {
return geyserName;
}
public int getNumEruptions() {
return count;
}
public static void main(String args[]) {
Geyser g = new Geyser("xyz");
if (g.getName().equals("xyz")) {
System.out.println("getName worked well.");
}
else {
System.out.println("getName did not work well.");
}
if (g.getNumEruptions() == 0) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
g.increment();
if (g.getNumEruptions() == 1) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
}
}
Eruption Code:
import java.util.Scanner;
public class Eruption
{
int month;
int day;
int year;
int hour;
int minute;
String geyserName;
public Eruption(String info){
Scanner scnr = new Scanner(info);
scnr.useDelimiter("/|,|:");
month = scnr.nextInt();
day = scnr.nextInt();
year = scnr.nextInt();
geyserName = scnr.next();
hour = scnr.nextInt();
minute = scnr.nextInt();
}
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public String getGeyserName(){
return geyserName;
}
public String toString( ){
String geyserString = geyserName + " " + "on" + month +"/"+ day +"/" + year + "at" + hour +":"+ minute;
return geyserString;
}
public static void main(String [] args){
Eruption e = new Eruption("1/2/2016,Old Faithful,10:46");
if (e.getMonth() == 1) {
System.out.println("getMonth worked well");
}
}
}

How to make the line graph start from zero and end at the last range JFreeChart

I have produced a line graph like this. Even though there are no zero data for the blue line and also the red line only have the value until 100. So how do i set the blue line to start at zero and red to finish until 200 like this:
My data in textfile (outputAvgGen.txt) are:
11752.58,HC
11819.65,HC
11941.75,HC
12398.45,HC
12401.06,HC
12531.09,HC
12634.33,HC
12748.83,HC
12787.36,HC
12799.44,HC
.
.
.
30137.15,P3
31919.46,P3
32323.8,P3
.
.
.
and so on until 200 data
This is my code:
public class Graph2 extends JFrame{
public Graph2(){
setTitle("P3 Performance Analysis");
JPanel chartPanel = createChartPanel();
add(chartPanel, BorderLayout.CENTER);
setSize(640, 480);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Graph2().setVisible(true);
}
});
}
private JPanel createChartPanel() {
// creates a line chart object
// returns the chart panel
String chartTitle = "Average Fitness against No. of Generations";
String xAxisLabel = "No. of Generations";
String yAxisLabel = "Average Fitness";
XYDataset dataset = createDataset();
JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
xAxisLabel, yAxisLabel, dataset);
XYPlot plot = chart.getXYPlot();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
yAxis.setAutoRangeIncludesZero(true);
return new ChartPanel(chart);
}
private XYDataset createDataset() {
ArrayList<PlotData2> dataList = readData();
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Hill Climber");
XYSeries series2 = new XYSeries("P3");
for (int i = 0; i < dataList.size(); i++){
if (dataList.get(i).getAlgo().equals("HC")){
series1.add(i, dataList.get(i).getAvg());
System.out.println("HC i=" + i);
}
else if (dataList.get(i).getAlgo().equals("P3")){
series2.add(i, dataList.get(i).getAvg());
System.out.println("P3 i=" + i);
}
}
/*
for (int i = 0; i < dataList.size(); i++){
if (dataList.get(i).getAlgo().equals("HC")){
System.out.println("i = " + i);
series1.add(i, dataList.get(i).getAvg());
}
}
for (int j = 0; j < dataList.size(); j++){
if (dataList.get(j).getAlgo().equals("P3")){
System.out.println("j = " + j);
series2.add(j, dataList.get(j).getAvg());
}
}*/
/*
series1.add(1.0, 2.0);
series1.add(2.0, 3.0);
series1.add(3.0, 2.5);
series1.add(3.5, 2.8);
series1.add(4.2, 6.0);
series2.add(2.0, 1.0);
series2.add(2.5, 2.4);
series2.add(3.2, 1.2);
series2.add(3.9, 2.8);
series2.add(4.6, 3.0); */
dataset.addSeries(series1);
dataset.addSeries(series2);
return dataset;
}
public static ArrayList<PlotData2> readData(){
ArrayList<PlotData2> dataList = new ArrayList<PlotData2>();
try {
BufferedReader in = new BufferedReader( new FileReader("outputAvgGen.txt") );
String str;
while ( (str = in.readLine() )!= null ) {
String[] data = str.split( "," );
double avg = Double.parseDouble(data[0]);
String algo = data[1];
// int gen = Integer.parseInt(data[2]);
dataList.add(new PlotData2(algo,avg));
}
in.close();
} catch ( IOException ex ) {
System.err.println( "Error: Can't open the file for reading." );
}
return dataList;
}
}
Actually my original data being computed are in pairs of HC and P3 in a textfile like this:
15426.35,HC
38903.93,P3
13777.49,HC
34480.21,P3
15199.38,HC
38559.36,P3
13399.15,HC
32931.49,P3
.
.
and so on..
but I sorted it to make the graph being plotted ascendingly but when sorted it doesn't plot according to the pairs.
Can someone please help with the code at least to make it start at zero and end at max range for both lines to make it look simultaneous. Thank you.
The major issue with your code is that you are incrementing the x values for both series simultaneously. You need to do that separately. Furthermore, you are using hardcoded strings in your createDataset method.
Try this approach instead:
public static HashMap<String, List<Double>> readData() {
HashMap<String, List<Double>> dataList = new HashMap<String, List<Double>>();
try {
BufferedReader in = new BufferedReader(new FileReader("outputAvgGen.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] data = str.split(",");
String algo = data[1];
if (dataList.get(algo) == null) {
dataList.put(algo, new ArrayList<Double>());
}
dataList.get(algo).add(Double.parseDouble(data[0]));
}
in.close();
}
catch (IOException ex) {
System.err.println("Error: Can't open the file for reading.");
}
return dataList
}
private XYDataset createDataset() {
HashMap<String, List<Double>> dataList = readData();
XYSeriesCollection dataset = new XYSeriesCollection();
Set<String> keys = dataList.keySet();
for (String key : keys) {
XYSeries series = new XYSeries(key);
List<Double> numbers = dataList.get(key);
for (int i = 0; i < numbers.size() - 1; i++) {
series.add(i, numbers.get(i), false);
}
series.add(numbers.size() - 1, numbers.get(numbers.size() - 1), true);
dataset.addSeries(series);
}
return dataset;
}

Convert the string "8:00" into the minutes (integer value)

I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?
String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
int open = Integer.parseInt(row[0]);
}
csvReader.close();
You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);
int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
Try something like this
String str = "8:10";
int minutes=0;
String[] arr= str.split(":");
if(arr.length==2){
minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
}
System.out.println(minutes);
Write something like this to convert into int
public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
int value = Integer.parseInt(tokens[i - 1]);
if (i == 1) {
minutes += 60 * value;
}
else {
minutes += value;
}
}
return minutes;
}
Try this
String str = "8:20";
int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
System.out.println("Answer = "+ans);

Iterating through current month to get all events

I have a calendar app. I want to add a listview which displays all the events for the current month.
This is the code which I am using to loop but it displays only the last event of the month, instead of ALL the events:
for(int i = 0; i < _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
if(isHoliday(i, month, year, date_value))
{
String date= i + " " + getMonthForInt(month);
CalendarEvents events = new CalendarEvents();
final ArrayList<Event> e = new ArrayList<Event>();
e.addAll(events.eventDetails(hijri_date[1], hijri_date[0]));
for (int j = 0; j < e.size(); j++)
{
Event event = e.get(j);
summary_data = new Summary[]
{
new Summary(date, event.eventdetails)
};
}
}
}
summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summary_data);
calendarSummary = (ListView) v.findViewById(R.id.calendarSummary);
calendarSummary.setAdapter(summaryAdapter);
UPDATED CODE:
CalendarEvents events = new CalendarEvents();
final ArrayList<Event> e = new ArrayList<Event>();
String date;
for(int i = 0; i < _calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
if(isHoliday(i, month, year, date_value))
{
date = i + "-" + month + "-" + year;
e.addAll(events.eventDetails(month, day));
summary_data = new Summary[e.size()];
for (int j = 0; j < e.size(); j++)
{
Event event = e.get(j);
summary_data[j] = new Summary(date, event.eventdetails);
}
}
}
You are creating array every time and assigning to same reference. That is why last one replacing everything else.
summary_data = new Summary[]
{
new Summary(date, event.eventdetails)
};
You know the size ahead, so create array with size first and then assign values to index
summary_data = new Summary[e.size()];
for(....)
{
......
summary_data[j] = new Summary(date, event.eventdetails);
}
/////
if(isHoliday(i, month, year, date_value))
{
String date = i + "-" + month + "-" + year;

Categories

Resources