I'm writing a program which would display incoming data while day. It's getting data about every 600 milliseconds and adding it to the TimeSeries Chart. The problem is: after about 10 minutes of work, GUI starts freezing. But if display only few series of 33 it's become fine. So maybe I am doing something wrong?
How to solve that freezing? My SwingWorker may be weak, or chosen JFreeChart collection.
Any tips might be helpful, thank you!
My short code example:
import java.awt.event.ActionEvent;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.ChartFactory;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.data.xy.XYSeries;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYDataset;
import java.awt.Dimension;
import java.awt.Component;
import javax.swing.JCheckBox;
import org.jfree.chart.ChartPanel;
import java.awt.LayoutManager;
import java.awt.BorderLayout;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import java.awt.event.ActionListener;
import java.awt.Window;
import org.jfree.chart.ui.UIUtils;
import javax.swing.JPanel;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Paint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.SwingWorker;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.ui.ApplicationFrame;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class HideSeriesDemo1 extends ApplicationFrame {
public HideSeriesDemo1(final String title) {
super(title);
this.setContentPane(new MyDemoPanel());
}
public static JPanel createDemoPanel() {
return new MyDemoPanel();
}
public static void main(final String[] args) {
final HideSeriesDemo1 demo = new HideSeriesDemo1("JFreeChart: HideSeriesDemo1.java");
demo.pack();
UIUtils.centerFrameOnScreen(demo);
demo.setVisible(true);
}
static class MyDemoPanel extends JPanel implements ActionListener {
final JFreeChart chart;
private JPanel boxPanel;
TimeSeriesCollection seriesArray;
private XYItemRenderer renderer;
private void setLinesVisible() {
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
renderer.setSeriesVisible(i, true);
JCheckBox box = (JCheckBox) boxPanel.getComponent(i);
box.setSelected(true);
}
}
private void setLinesInvisible() {
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
renderer.setSeriesVisible(i, false);
JCheckBox box = (JCheckBox) boxPanel.getComponent(i);
box.setSelected(false);
}
}
private XYDataset createNumberedDataSet(int num) {
seriesArray = new TimeSeriesCollection();
for (int i = 0; i < num; i++) {
int num2 = i + 1;
TimeSeries s1 = new TimeSeries("Channel №" + num2);
seriesArray.addSeries(s1);
}
return seriesArray;
}
public MyDemoPanel() {
super(new BorderLayout());
final XYDataset dataset = this.createNumberedDataSet(33);
chart = this.createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
boxPanel = new JPanel();
boxPanel.setLayout(new GridLayout(0, 11));
boxPanel.validate();
for (int i = 0; i < 33; i++) {
int numchik = i + 1;
JCheckBox box1 = new JCheckBox("Channel №" + numchik);
String com = "S" + numchik;
box1.setSelected(true);
box1.setActionCommand(com);
box1.addActionListener(this);
boxPanel.add(box1);
}
boxPanel.validate();
final JButton btn = new JButton("All not sellected");
btn.setVisible(true);
btn.setActionCommand("btn");
btn.addActionListener(this);
boxPanel.add(btn);
final JButton btn2 = new JButton("All sellected");
btn2.setVisible(true);
btn2.setActionCommand("btn2");
btn2.addActionListener(this);
boxPanel.add(btn2);
final JButton btn3 = new JButton("SwingWorker?");
btn3.setVisible(true);
btn3.setActionCommand("btn3");
btn3.addActionListener(this);
boxPanel.add(btn3);
this.add(chartPanel);
this.add(boxPanel, "South");
JPopupMenu pop = chartPanel.getPopupMenu();
pop.add(new JSeparator());
JMenuItem remBtn = new JMenuItem("All not selected");
remBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
setLinesInvisible();
}
});
pop.add(remBtn);
JMenuItem addBtn = new JMenuItem("All visible");
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
setLinesVisible();
}
});
pop.add(addBtn);
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart("xDisplay", "Time", "Data", dataset, true, true, false);
final XYPlot plot = (XYPlot) chart.getPlot();
this.renderer = plot.getRenderer();
return chart;
}
#Override
public void actionPerformed(final ActionEvent e) {
int series = -1;
if (e.getActionCommand().equals("btn")) {
this.setLinesInvisible();
System.out.println("set invisible btn pressed");
boxPanel.validate();
// System.out.println("btn pressed");
return;
}
if (e.getActionCommand().equals("btn2")) {
setLinesVisible();
boxPanel.validate();
System.out.println("setBtnVisible pressed");
return;
}
if (e.getActionCommand().equals("btn3")) {
System.out.println("swingworker");
MySwingWorker swi = new MySwingWorker();
swi.execute();
}
for (int i = 0; i<33;i++){
String s="S"+i;
if (e.getActionCommand().equals(s)) {
series = i-1;
}
}
if (series >= 0) {
final boolean visible = this.renderer.getItemVisible(series, 0);
this.renderer.setSeriesVisible(series, !visible);
}
}
private class MySwingWorker extends SwingWorker<Boolean, double[]> {
LinkedList<Double> fifo = new LinkedList<Double>();
public MySwingWorker() {
fifo.add(0.0);
}
#Override
protected Boolean doInBackground() {
while (!isCancelled()) {
try {
Thread.sleep(600);
} catch (InterruptedException ex) {
Logger.getLogger(HideSeriesDemo1.class.getName()).log(Level.SEVERE, null, ex);
}
fifo.add(fifo.get(fifo.size() - 1) + Math.random() - .5);
if (fifo.size() > 1000) {
fifo.removeFirst();
}
double[] array = new double[fifo.size()];
for (int i = 0; i < fifo.size(); i++) {
array[i] = fifo.get(i);
}
System.out.println(array.length + " : " + Arrays.toString(array) + "Array: ");
publish(array);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// eat it. caught when interrupt is called
System.out.println("MySwingWorker shut down." + " name:" + Thread.currentThread().getName());
}
}
return true;
}
#Override
protected void process(List<double[]> chunks) {
double[] mostRecentDataSet = chunks.get(chunks.size() - 1);
for (int i = 0; i < seriesArray.getSeriesCount(); i++) {
TimeSeries series = seriesArray.getSeries(i);
series.addOrUpdate(new Millisecond(), mostRecentDataSet[0] + i);
}
fifo.removeFirst();
System.out.println(" repaint zone " + " name:" + Thread.currentThread().getName());
}
}
}
}
Related
I am trying to generate a chart dynamically that will show the value change over time. I am storing those value in an ArrayList< Integer, ArrayList<Integer>> and retrieving those values in this class. But it doesn't show the addition of the values in that ArrayList over time.
Here actually another two thread is updating that ArrayList and I need to show the values of that Arraylist in a chart that will be dynamic.
The below is the code based on this example:
package com.model.presentation;
import java.awt.BorderLayout;
import java.awt.Dimension;
//import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
//import java.util.Random;
import java.util.Map.Entry;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.Timer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import com.model.resources.Household;
/**
* #see https://stackoverflow.com/a/15715096/230513
* #see https://stackoverflow.com/a/11949899/230513
*/
public class DisplayChart {
//private static final int N = 128;
//private static final Random random = new Random();
private int n = 1;
static int count = 0;
public void display()
{
JFrame f = new JFrame("Community Rescilience Model");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
jtp.add(String.valueOf(n), createPane());
f.add(jtp, BorderLayout.CENTER);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Add") {
public void actionPerformed(ActionEvent e) {
jtp.add(String.valueOf(++n), createPane());
jtp.setSelectedIndex(n - 1);
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private ChartPanel createPane()
{
final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
final String name = "Community ";
/* for (int i = 0; i < random.nextInt(N) + N / 2; i++)
{
while (iterator.hasNext())
{
Map.Entry map = (Map.Entry) iterator.next();
String community_name = name + String.valueOf(map.getKey());
ArrayList<Integer> dataArrayList = (ArrayList<Integer>) map.getValue();
for (Iterator<Integer> it = dataArrayList.iterator(); it.hasNext();)
{
dataset.addValue(it.next(), community_name, String.valueOf(count));
count++;
}
}
}*/
// XYSeriesCollection dataset = new XYSeriesCollection(series);
new Timer(100, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Iterator<Entry<Integer, ArrayList<Integer>>> iterator = Household.goods.entrySet()
.iterator();
while (iterator.hasNext())
{
Map.Entry map = (Map.Entry) iterator.next();
String community_name = name + String.valueOf(map.getKey());
ArrayList<Integer> dataArrayList = (ArrayList<Integer>) map.getValue();
for (Iterator<Integer> it = dataArrayList.iterator(); it.hasNext();)
{
dataset.setValue(it.next(), community_name, String.valueOf(count));
count++;
}
}
}
}).start();
JFreeChart lineChart = ChartFactory.createLineChart("Resource Production/Consumption over time", "Time",
"Number of GOODS", dataset, PlotOrientation.VERTICAL,
true, true, false);
return new ChartPanel(lineChart) {
#Override
public Dimension getPreferredSize()
{
return new Dimension(1000, 500);
}
};
}
/*public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DisplayChart().display();
}
});
}
}*/
}
The main class is :
public class Main_class {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new DisplayChart().display();
}
});
}
This code works but at certain point, it gets stuck. It means it does not show the value of the changes in that Arraylist.
I have it running indefinitely although i am not sure it is still working as you intended.
I didn't have the Household class so I just faked it with.
class Household {
static public Map<Integer, ArrayList<Integer>> goods = new HashMap<>();
}
I also don't think I have your code for adding data to the plot. I did it like this:
Random rand = new Random();
while (true) {
try {
Thread.sleep(100);
for (int i = 0; i < 10; i++) {
final int fi = i;
EventQueue.invokeLater(new Runnable() {
public void run() {
ArrayList<Integer> l = Household.goods.get(fi);
if (l == null) {
l = new ArrayList<>();
}
l.add(rand.nextInt(100));
if (l.size() > 20) {
l.remove(0);
}
Household.goods.put(fi, l);
}
});
}
} catch (InterruptedException ex) {
}
}
Note that it is important to do it in the EventQueue thread or you will get a ConcurrentModificationException.
The real issue seems to be that your adding the same data in the list over and over again associated with different counts.
So I changed:
for (Iterator<Integer> it = dataArrayList.iterator(); it.hasNext();)
{
dataset.setValue(it.next(), community_name, String.valueOf(count));
count++;
}
To :
for (count = 0; count < dataArrayList.size(); count++) {
dataset.setValue(dataArrayList.get(count), community_name, String.valueOf(count));
}
only problem is that whenever i set initial value for the x and y to be greater than 10,it gives bad result.Please help.It works fine for the values less than 10 for x and y.
i have also debugged it and find out whenever the button is pressed after the 10th index it behaves like setting the variable i to 1.i am unable to fix this issue as i am new in java.so i really need help in this.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
class butMaddFrame extends JFrame implements ActionListener
{
int x=12;
int y=12;
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
Container c = getContentPane();
int[][] intArray = new int[x][y];
public butMaddFrame()
{
butGen();
score2();
//cPanel.add(scoreKeeper);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
// mPanel.add(cPanel, BorderLayout.LINE_END);
c.add(mPanel);
setTitle("ButtonMaddness");
setSize(1000,400);
setLocation(200,200);
setVisible(true);
}
private void butGen()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
bPanel.add(buttons[i][j]);
}
}
private void score()
{
// String string = "";
// for(int i=0;i<x;i++)
// {
// for(int j=0;j<y;j++)
// string += i+"x"+j+" => " +String.valueOf(intArray[i][j]) +"\t";
// string+= "\n";
// }
// scoreKeeper.setText(string);
}
private void score2()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
buttons[i][j].setText(String.valueOf(intArray[i][j]));
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
int i = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(1)));
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() +" " +i +" " +j);
}
// score2();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class buttonMaddness {
public static void main(String[] args)
{
butMaddFrame myFrame = new butMaddFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your problem is here:
replaceAll("_", "").charAt(0)
because some of your buttons have things like 11_9 for
example. So you get just the first 1 of the number 11.
Just change your actionPerformed method
to this and your bug will be fixed.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().contains("button")) {
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
/*
int i = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(1)));
*/
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() + " " + i + " " + j);
}
// score2();
}
I am new in JFreeChart and new to Java also.
I have this data from our claims table:
SEQ IP_CLAIMS_RECEIVED HB_CLAIMS_RECEIVED IP_AVERAGE_RESPONSE HB_AVERAGE_RESPONSE
30 Seconds 29 19 4 4
This data every 30 seconds will change giving the amount of claims processed and with the avarage seconds it took to process this.
So my graph I want it on the Y-Axis to display the round seconds like (0,,5,10,15,20,25,30,35,40) and then on the X-Axis to display the time - the 30 seconds intervals showing the refresh times. And then the spike-lines would show the average-response times... And if it will be possible have two combined graphs one for IP Claims and another for HB Claims. I have a perfect example of the graph but its confusing me a bit here is the code of it below:
package timeseriesdemo;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.DynamicTimeSeriesCollection;
import org.jfree.data.time.Second;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
/** #see https://stackoverflow.com/questions/5048852 */
public class TimeSeriesDemo extends ApplicationFrame {
private static final String TITLE = "Dynamic Series";
private static final String START = "Start";
private static final String STOP = "Stop";
private static final float MINMAX = 100;
private static final int COUNT = 2 * 60;
private static final int FAST = 100;
private static final int SLOW = FAST * 5;
private static final Random random = new Random();
private Timer timer;
public TimeSeriesDemo(final String title) {
super(title);
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection(1, COUNT, new Second());
dataset.setTimeBase(new Second(0, 0, 0, 1, 1, 2011));
dataset.addSeries(gaussianData(), 0, "Gaussian data");
JFreeChart chart = createChart(dataset);
final JButton run = new JButton(STOP);
run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (STOP.equals(cmd)) {
timer.stop();
run.setText(START);
} else {
timer.start();
run.setText(STOP);
}
}
});
final JComboBox combo = new JComboBox();
combo.addItem("Fast");
combo.addItem("Slow");
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Fast".equals(combo.getSelectedItem())) {
timer.setDelay(FAST);
} else {
timer.setDelay(SLOW);
}
}
});
this.add(new ChartPanel(chart), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(run);
btnPanel.add(combo);
this.add(btnPanel, BorderLayout.SOUTH);
timer = new Timer(FAST, new ActionListener() {
float[] newData = new float[1];
#Override
public void actionPerformed(ActionEvent e) {
newData[0] = randomValue();
System.out.println("dataset1 : " + dataset.advanceTime());
dataset.advanceTime();
dataset.appendData(newData);
}
});
}
private float randomValue() {
System.out.println("randomvalue : " + (float) (random.nextGaussian() * MINMAX / 3));
return (float) (random.nextGaussian() * MINMAX / 3);
}
private float[] gaussianData() {
float[] a = new float[COUNT];
for (int i = 0; i < a.length; i++) {
a[i] = randomValue();
}
return a;
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "hh:mm:ss", "Claims Received", dataset, true, true, false);
final XYPlot plot = result.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
ValueAxis range = plot.getRangeAxis();
range.setRange(-MINMAX, MINMAX);
return result;
}
public void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TimeSeriesDemo demo = new TimeSeriesDemo(TITLE);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
demo.start();
}
});
}
}
My requirement is to create a dynamic time series stacked area chart in a java desktop app. Something like this example, but i want Stacked Area chart. I have found lot of examples of stacked area chart but they all are based on static data.
Here is the modified version of this example for dynamic time series stacked area chart.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StackedXYAreaRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.time.TimeTableXYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class DTSCTest extends ApplicationFrame {
private static final String TITLE = "Dynamic Series";
private static final String START = "Start";
private static final String STOP = "Stop";
private static final float MINMAX = 100;
private static final int COUNT = 15;
private static final int FAST = 1000;
private static final int SLOW = FAST * 5;
private static final Random random = new Random();
private Timer timer;
private static final String SERIES1 = "Positive";
private static final String SERIES2 = "Negative";
public DTSCTest(final String title) {
super(title);
final TimeTableXYDataset dataset = new TimeTableXYDataset();
JFreeChart chart = createAreaChart(dataset);
final JButton run = new JButton(STOP);
run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (STOP.equals(cmd)) {
timer.stop();
run.setText(START);
} else {
timer.start();
run.setText(STOP);
}
}
});
final JComboBox combo = new JComboBox();
combo.addItem("Fast");
combo.addItem("Slow");
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Fast".equals(combo.getSelectedItem())) {
timer.setDelay(FAST);
} else {
timer.setDelay(SLOW);
}
}
});
this.add(new ChartPanel(chart), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(run);
btnPanel.add(combo);
this.add(btnPanel, BorderLayout.SOUTH);
timer = new Timer(FAST, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TimePeriod period = new Second();
dataset.add(period, randomValue(), SERIES1);
dataset.add(period, randomValue(), SERIES2);
if(dataset.getItemCount() > COUNT) {
TimePeriod firstItemTime = dataset.getTimePeriod(0);
dataset.remove(firstItemTime, SERIES1);
dataset.remove(firstItemTime, SERIES2);
}
}
});
}
private float randomValue() {
float randValue = (float) (random.nextGaussian() * MINMAX / 3);
return randValue < 0 ? -randValue : randValue;
}
private JFreeChart createAreaChart(final TimeTableXYDataset dataset) {
final JFreeChart chart = ChartFactory.createStackedXYAreaChart(
"Live Sentiment Chart", "Time", "Sentiments", dataset, PlotOrientation.VERTICAL, true, true, false);
final StackedXYAreaRenderer render = new StackedXYAreaRenderer();
render.setSeriesPaint(0, Color.RED);
render.setSeriesPaint(1, Color.GREEN);
DateAxis domainAxis = new DateAxis();
domainAxis.setAutoRange(true);
domainAxis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
domainAxis.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND, 1));
XYPlot plot = (XYPlot) chart.getPlot();
plot.setRenderer(render);
plot.setDomainAxis(domainAxis);
plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
plot.setForegroundAlpha(0.5f);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setNumberFormatOverride(new DecimalFormat("#,###.#"));
rangeAxis.setAutoRange(true);
return chart;
}
public void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DTSCTest demo = new DTSCTest(TITLE);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
demo.start();
}
});
}
}
My code so far:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TestFile2 {
public static void main(String args[]) {
String size[] = {"Small", "Medium", "Large", "Extra Large"};
String toppings[] = {"Cheese", "Pepperoni", "Sausage", "Spinach", "Pepperoncini"};
JFrame f = new JFrame("Pizza");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList list1 = new JList(size);
JList list2 = new JList(toppings);
Container c = f.getContentPane();
JScrollPane sp1 = new JScrollPane(list1);
sp1.setColumnHeaderView(new JLabel("Select Size"));
JScrollPane sp2 = new JScrollPane(list2);
sp2.setColumnHeaderView(new JLabel("Select Toppings. Hold Ctrl to select multiple toppings"));
Box box = Box.createHorizontalBox();
box.add(sp1);
box.add(sp2);
list1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
JList jListSource = (JList) e.getSource();
Object[] selection = jListSource.getSelectedValues();
if (!e.getValueIsAdjusting()) {
System.out.println("----");
for (int i = 0; i < selection.length; i++) {
double costSize;
if (selection[i].equals("Small")) {
costSize = 7.00;
} else if (selection[i].equals("Medium")) {
costSize = 9.00;
} else if (selection[i].equals("Large")) {
costSize = 11.00;
} else {
costSize = 14.00;
}
System.out.println("selection = " + selection[i]);
System.out.println("selection = " + costSize);
}
}
}
});
c.add(box, BorderLayout.CENTER);
f.setSize(
300, 200);
f.setVisible(
true);
}
}
I need to do something similar to what I did with list1.
I need to have the user select from a JList both the size of pizza and the toppings. At the end I need to be able to calculate the total cost. Each topping is $1. Any point in a certain direction would be greatly appreciated as I have been pulling my hair out for the past few hours trying different methods for this problem.
Thanks in advance.
I hope this will help :) ... there are other ways to do it.... this just one of them ...
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TestFile2 {
private static JList list1;
private static JList list2;
public static void main(String args[]) {
String size[] = {"Small", "Medium", "Large", "Extra Large"};
String toppings[] = {"Cheese", "Pepperoni", "Sausage", "Spinach", "Pepperoncini"};
JFrame f = new JFrame("Pizza");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list1 = new JList(size);
list2 = new JList(toppings);
Container c = f.getContentPane();
JScrollPane sp1 = new JScrollPane(list1);
sp1.setColumnHeaderView(new JLabel("Select Size"));
JScrollPane sp2 = new JScrollPane(list2);
sp2.setColumnHeaderView(new JLabel("Select Toppings. Hold Ctrl to select multiple toppings"));
Box box = Box.createHorizontalBox();
box.add(sp1);
box.add(sp2);
list1.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
handleEvent(e);
}
});
list2.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
handleEvent(e);
}
});
c.add(box, BorderLayout.CENTER);
f.setSize(
300, 200);
f.setVisible(
true);
}
protected static void handleEvent(ListSelectionEvent e)
{
double cost = 0.0;
Object[] selection = list1.getSelectedValues();
Object[] toppings = list2.getSelectedValues();
if(toppings.length == 0)
System.out.println("Please select a topping");
if(selection.length == 0)
System.out.println("Please select a size");
if (!e.getValueIsAdjusting())
{
System.out.println("----");
for (int i = 0; i < selection.length; i++)
{
double costSize;
if (selection[i].equals("Small")) {
cost = 7.00;
} else if (selection[i].equals("Medium")) {
cost = 9.00;
} else if (selection[i].equals("Large")) {
cost = 11.00;
} else {
cost = 14.00;
}
}
for (int i = 0; i < toppings.length; i++)
{
cost++;
}
System.out.println("Total = " + cost);
}
}
}