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;
Related
I`m currently trying to obtain a CountDownTimer based on the time in milliseconds of a Calendar object. The startTimer function works, so does the timerSort function. The thing is that when the timer gets initialized with the timeLeft value, it never start from a value lower than 60 seconds. This eventually causes delays bigger than 10 seconds. any suggestions?
Thank you.
Code:
private void startTimer(String x){
counter = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateCountdownText();
}
#Override
public void onFinish() {
timerRunning = false;
int comp = Integer.parseInt(x);
Toast.makeText(getApplicationContext(), "Alarm received!", Toast.LENGTH_LONG).show();
cal[comp].add(Calendar.MINUTE,rec[comp]);
//Update txt file
int month = cal[comp].get(Calendar.MONTH)+1;
int day = cal[comp].get(Calendar.DAY_OF_MONTH);
String data = cal[comp].get(Calendar.HOUR_OF_DAY) + ","
+cal[comp].get(Calendar.MINUTE) + ","
+day+ "," + month + ","
+cal[comp].get(Calendar.YEAR) + "," + rec[comp] + ",";
try {
FileOutputStream stream = new FileOutputStream(file[comp], false);
try {
stream.write(data.getBytes());
}catch (Exception e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//end update
timerSort();
BluetoothGattCharacteristic C = btper.getCharacteristic(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));
//If device is disconnected => it will crash
btper.writeCharacteristic(C , x.getBytes(StandardCharsets.UTF_8), WriteType.WITH_RESPONSE);
speak(String.valueOf(comp+1));
}
}.start();
}
private void updateCountdownText() {
if(counterView.getVisibility() != View.VISIBLE)
counterView.setVisibility(View.VISIBLE);
int minutes = (int)timeLeft / 1000 / 60;
int seconds = (int)timeLeft /1000 % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"Time left until next pill: %02d:%02d",minutes,seconds);
if(timeLeftFormatted.contains("00:00"))
counterView.setVisibility(View.INVISIBLE);
counterView.setText(timeLeftFormatted);
}
private void resetTimer(){}
private void timerSort(){
Context context = getApplicationContext();
int i,j;
j = 0;
int fileindex = 0;
int hour, day, month, minute, year;
calendar = Calendar.getInstance();
timeLeft = 0;
for (i = 0; i<20; i++){
fileindex = i+1;
file[i] = new File(context.getExternalFilesDir(null).getAbsolutePath(),"pills"+fileindex+".txt");
cal[i] = (Calendar) calendar.clone();
//Read text from pills file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file[i]));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String str = text.toString();
List<String> elephantList = Arrays.asList(str.split(","));
hour = Integer.parseInt(elephantList.get(0));
minute = Integer.parseInt(elephantList.get(1));
day = Integer.parseInt(elephantList.get(2));
month = Integer.parseInt(elephantList.get(3));
year = Integer.parseInt(elephantList.get(4));
rec[i] = Integer.parseInt(elephantList.get(5));
cal[i].set(Calendar.HOUR_OF_DAY, hour);
cal[i].set(Calendar.MINUTE, minute);
cal[i].set(Calendar.DAY_OF_MONTH, day);
cal[i].set(Calendar.MONTH-1, month);
cal[i].set(Calendar.YEAR,year);
}
// sorting:
int letsgo = 0;
Calendar tudor = Calendar.getInstance();
tudor.set(Calendar.YEAR,calendar.getMaximum(Calendar.YEAR));
for (i = 0; i<20; i++){
if(tudor.after(cal[i]) && cal[i].after(calendar)){
tudor = cal[i];
letsgo = i;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(letsgo), Toast.LENGTH_LONG).show();
TextView nextPillView = (TextView) findViewById(R.id.nextPillView);
if (!cal[letsgo].after(calendar)) {
nextPillView.setText("No Pills Scheduled");
} else {
// timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis() - Calendar.MILLISECOND;
int secleft = cal[letsgo].get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
int minleft = cal[letsgo].get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
timeLeft = secleft*1000 + minleft*60*1000 ;
//timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis();
String theTime = String.format(Locale.getDefault(), "%02d:%02d", cal[letsgo].get(Calendar.HOUR_OF_DAY), cal[letsgo].get(Calendar.MINUTE));
month = cal[letsgo].get(Calendar.MONTH)+1;
nextPillView.setText(cal[letsgo].get(Calendar.HOUR_OF_DAY)+":"+cal[letsgo].get(Calendar.MINUTE)+ " | | Day: " + cal[letsgo].get(Calendar.DAY_OF_MONTH) + " | | Month: " + String.valueOf(month) + " | | Year: " + cal[letsgo].get(Calendar.YEAR));
startTimer(String.valueOf(letsgo));
}
}
private void speak(String x){
float pitch = 1;
float speed = 1;
mTTS.setPitch(pitch);
mTTS.setSpeechRate(speed);
mTTS.speak("It is time to administer the compartment with the lit LED",
TextToSpeech.QUEUE_ADD,null);
}
I am fairly new to programming and I cant seem to find the problem in the area where I make the program search for the specific key term tho it's saved in the array.
here is the code where I add the details of the customer:
private void addCustomerToSeat(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Button[] seat = new Button[(SEATING_CAPACITY + 1)];
Button selectSeat = new Button(" Click to Book Seats ");
selectSeat.setLayoutX(320);
selectSeat.setLayoutY(512);
selectSeat.setOnAction(event -> {
window.setScene(scene2);
});
Label header = new Label("TRAIN BOOKING SYSTEM");
header.setLayoutX(250);
header.setLayoutY(30);
header.setStyle("-fx-font-size: 25px;");
Label clientName = new Label("Enter Customer Name: ");
clientName.setLayoutX(225);
clientName.setLayoutY(150);
clientName.setStyle("-fx-font-size: 16px;");
TextField cusName = new TextField();
cusName.setLayoutX(397);
cusName.setLayoutY(150);
Label destination = new Label("Choose destination: ");
destination.setLayoutX(225);
destination.setLayoutY(200);
destination.setStyle("-fx-font-size:16px;");
String [] destinations = {"Colombo to Badulla", "Badulla to Colombo"};
ComboBox Destination = new ComboBox(FXCollections.observableArrayList(destinations));
Destination.setLayoutX(397);
Destination.setLayoutY(200);
Label date = new Label("Select date:");
date.setLayoutY(275);
date.setLayoutX(225);
date.setStyle("-fx-font-size:16px;");
DatePicker datePicker = new DatePicker();
LocalDate now = LocalDate.now();
datePicker.setValue(now);
datePicker.setLayoutX(397);
datePicker.setLayoutY(275);
AnchorPane layout1 = new AnchorPane();
layout1.setStyle("-fx-background-color:#5a89a3; ");
layout1.getChildren().addAll(Destination,destination,selectSeat,clientName,cusName,header,date,datePicker);
scene1 = new Scene(layout1,800,600);
window.setTitle("Train Booking System");
window.setScene(scene1);
window.show();
Label header1 = new Label("TRAIN BOOKING SYSTEM");
header1.setLayoutX(250);
header1.setLayoutY(30);
header1.setStyle("-fx-font-size: 25px;");
Button submit = new Button("Submit");
submit.setLayoutX(640);
submit.setLayoutY(480);
Button exit = new Button("Exit");
exit.setLayoutX(710);
exit.setLayoutY(480);
exit.setOnAction(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
Label greenSeat = new Label("Unbooked Seat");
greenSeat.setLayoutY(160);
greenSeat.setLayoutX(590);
greenSeat.setStyle("-fx-font-size:14px;");
Button unbooked = new Button(" ");
unbooked.setLayoutY(160);
unbooked.setLayoutX(560);
unbooked.setStyle("-fx-background-color:green;");
Label redSeat = new Label("Booked Seat");
redSeat.setLayoutX(590);
redSeat.setLayoutY(200);
redSeat.setStyle("-fx-font-size:14px;");
Button booked = new Button(" ");
booked.setLayoutX(560);
booked.setLayoutY(200);
booked.setStyle("-fx-background-color:red;");
GridPane gridPane = new GridPane();
int columnIndex = 0;
int rowIndex = 0;
int rowIndexes = 0;
int[] reservedSeats = new int[1];
String seatNumber;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++) {
if (i <= 9) {
seatNumber = "0" + (i);
} else {
seatNumber = "" + (i);
}
seat[i] = new Button(seatNumber);
gridPane.add(seat[i], columnIndex, rowIndex);
columnIndex++;
rowIndexes++;
if (rowIndexes == 4) {
columnIndex = 0;
rowIndexes = 0;
rowIndex++;
}
}
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
if (seatBooking[f].equals("Empty")) {
seat[f].setStyle("-fx-background-color: green;");
}
if (seatBooking[f].equals("booked")) {
seat[f].setStyle("-fx-background-color: red");
}
}
List<Integer> bookedCurrent = new ArrayList<>();
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
int finalF = f;
seat[f].setOnAction(event -> {
seat[finalF].setStyle("-fx-background-color: red");
seatBooking[finalF] = "booked";
bookedCurrent.add(finalF);
});
submit.setOnAction(event -> {
String personName = cusName.getText();
personName = personName.toLowerCase();
window.close();
for ( int loopSeatArray = 1; loopSeatArray< (SEATING_CAPACITY + 1); loopSeatArray++) {
if (loopSeatArray == reservedSeats[0]) {
seatBooking[loopSeatArray] = "Booked";
customerName[loopSeatArray] = personName;
}
seatBookingAndCustomerName[loopSeatArray] = seatBooking[loopSeatArray];
}
for (int total = 43; total < (SEATING_CAPACITY + 1); total++){
seatBookingAndCustomerName[total]= customerName[total-42]; }
displayMenu(seatBooking, customerName, seatBookingAndCustomerName);
});
}
gridPane.setLayoutX(160);
gridPane.setLayoutY(80);
gridPane.setHgap(20);
gridPane.setVgap(5);
AnchorPane layout2 = new AnchorPane();
layout2.setStyle("-fx-background-color:#5a89a3; ");
layout2.getChildren().addAll(gridPane,submit,exit,header1,greenSeat,unbooked,redSeat,booked);
scene2 = new Scene(layout2,800,600);
window.setTitle("Train Booking System");
window.show();
window.setOnCloseRequest(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
}
and here is the part of the code where I prompt the user for the name and find the location of given name:
private void findCustomerSeats(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter customer name: ");
String name = input.nextLine();
boolean flag = false;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++){
if (name.toLowerCase().equals(customerName[i])){
System.out.println("Seats booked are: " + seatBooking);
flag = true;
}
}
if (flag !=true){
System.out.println(name + " has not reserved a seat");
}
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
}
when the above code is run, and when I input the name, it plain out does not work.
One potential issue, your for loop is starting at index 1, I would begin by using something like this:
for (int idx = 0; idx < customerName.length; idx++) {
//This way you will not check an index of your array that does not exist
//which could cause a NullPointerException
//Additionally, this is useful if you want to grow your customerName array
}
Another useful tip, that I use all the time. Try printing out more information and see if you can spot the issue. This might seem trivial but I have found it extremely helpful. For example:
System.out.println("Inputted Name: " + name);
for (int idx = 0; idx < customerName.length; idx++) {
System.out.println("Does " + name.toLowerCase() + " = " + customerName[idx] + " ?");
}
I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}
Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.
try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}
I want to set text by date and incrementing loop, and when the day changes looping start from the beginning.
Example
1. day 1 =
a. nameFile 110920190001
b. nameFile 110920190002, etc.
2. day 2 =
a. nameFile 120920190001
b. nameFile 120920190002, etc.
Code
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
for(int i = 1; i <= 1000; i++) {
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
Just put the Date Initialization in the for loop for it to always take the new Instance of the date.
public static void replace(String s) {
for (int i = 1; i <= 1000; i++) {
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
}
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.