JFreeChart - XYLineAndShapeRenderer getItemLineVisible() not working - java

I'm simulating dummy real-time data using DynamicTimeSeriesCollection, like this. During random intervals, the data being passed to the plot should 'dropout' to simulate a network connection loss. At this point, this plot should stop drawing and only start plotting the data after the dropout has subsided.
I subclassed XYLineAndShapeRenderer and overrode the getItemLineVisible() method:
#Override
public boolean getItemLineVisible(int series, int item){
if(offline){
return false;
}else{
return true;
}
}
However when offline is true, all points are still being drawn on the graph.
public class Test extends ApplicationFrame {
private static final String TITLE = "Dynamic Series";
private static final String START = "Start";
private static final String STOP = "Stop";
private static final int COUNT = 1000*60;
private static final int FAST = 1; //1000/FAST = occurrences per second real time
private static final int REALTIME = FAST * 1000;
private static final Random random = new Random();
private static final double threshold = 35;
private double gateStart = ThreadLocalRandom.current().nextInt(0, 101);
private boolean returning = false;
private boolean offline = false;
private Timer timer;
private Calendar startDate;
private static final int simulationSpeed = 1000/FAST;
private final TimeSeries seriesA = new TimeSeries("A");
public Test(final String title) throws ParseException {
super(title);
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy HH:mm", Locale.ENGLISH);
PriceParser parser = new PriceParser();
List<List<String>> priceData = parser.parse();
Date date = formatter.parse(priceData.get(0).get(0));
startDate = Calendar.getInstance();
startDate.setTime(date);
Calendar timeBaseStartDate = Calendar.getInstance();
timeBaseStartDate.setTime(startDate.getTime());
timeBaseStartDate.add(Calendar.SECOND, -COUNT);
final TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(this.seriesA);
JFreeChart chart = createChart(dataset);
final JComboBox combo = new JComboBox();
combo.addItem("Fast");
combo.addItem("Real-time");
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Fast".equals(combo.getSelectedItem())) {
timer.setDelay(FAST);
} else {
timer.setDelay(REALTIME);
}
}
});
JFrame frame = new JFrame("Test");
JLabel label = new JLabel("Network connectivity lost.");
this.add(new ChartPanel(chart), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(combo);
JPanel test = new JPanel();
test.add(label);
this.add(btnPanel, BorderLayout.SOUTH);
// frame.add(btnPanel);
//frame.add(test);
timer = new Timer(FAST, new ActionListener() {
Date timeToCheck = formatter.parse(priceData.get(0).get(0));
Calendar pauseResume = Calendar.getInstance();
Calendar offlineTime = Calendar.getInstance();
boolean paused = false;
boolean waiting = false;
//boolean offline = false;
double currentPrice;
float[] newData = new float[1];
PopupFactory pf = PopupFactory.getSharedInstance();
Popup popup;
#Override
public void actionPerformed(ActionEvent e) {
Date datasetTime = new Date();
if(offline){
System.out.println("Offline: "+offlineTime.getTime());
System.out.println("Current: "+datasetTime);
if(offlineTime.getTime().compareTo(datasetTime) == 0){
offline = false;
System.out.println("Im no longer offline");
popup.hide();
}
}
if(ThreadLocalRandom.current().nextInt(0, 1001) > 999 && !offline){
offline = true;
offlineTime.setTime(datasetTime);
offlineTime.add(Calendar.SECOND, ThreadLocalRandom.current().nextInt(1, 5)*10);
// dataset.addValue(0, 0, null);
popup = pf.getPopup(btnPanel, label, 900, 300);
popup.show();
}
if(timeToCheck.compareTo(datasetTime) == 0){
currentPrice = Double.valueOf(priceData.get(0).get(1));
paused = currentPrice >= threshold;
priceData.remove(0);
try {
timeToCheck = formatter.parse(priceData.get(0).get(0));
} catch (ParseException ex) {
ex.printStackTrace();
}
}
if(!paused) {
if (Math.round(gateStart) * 10 / 10.0 == 100d) {
returning = true;
} else if (Math.round(gateStart) * 10 / 10.0 == 0) {
returning = false;
}
if (returning) {
gateStart -= 0.1d;
} else {
gateStart += 0.1d;
}
}else{
if(datasetTime.compareTo(pauseResume.getTime()) == 0 && currentPrice < threshold){
paused = false;
waiting = false;
}else{
if(Math.round(gateStart)*10/10.0 == 0 || Math.round(gateStart)*10/10.0 == 100){
if(!waiting){
pauseResume.setTime(datasetTime);
pauseResume.add(Calendar.SECOND, 120);
}
waiting = true;
}else{
if(Math.round(gateStart)*10/10.0 >= 50){
gateStart += 0.1d;
}else if(Math.round(gateStart)*10/10.0 < 50){
gateStart -= 0.1d;
}
}
}
}
newData[0] = (float)gateStart;
seriesA.addOrUpdate(new Second(), gateStart);
}
});
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "Time", "Shearer Position", dataset, true, true, false);
final XYPlot plot = result.getXYPlot();
plot.setDomainZeroBaselineVisible(false);
XYLineAndShapeRendererTest renderer = new XYLineAndShapeRendererTest(true, false);
plot.setRenderer(renderer);
DateAxis domain = (DateAxis)plot.getDomainAxis();
Calendar endDate = Calendar.getInstance();
endDate.setTime(new Date());
endDate.add(Calendar.HOUR_OF_DAY, 12);
System.out.println(new Date());
System.out.println(endDate.getTime());
domain.setRange(new Date(), endDate.getTime());
domain.setTickUnit(new DateTickUnit(DateTickUnitType.HOUR, 1));
domain.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
ValueAxis range = plot.getRangeAxis();
range.setRange(0, 100);
return result;
}
private class XYLineAndShapeRendererTest extends XYLineAndShapeRenderer {
private boolean drawSeriesLineAsPath;
public XYLineAndShapeRendererTest(boolean line, boolean shapes){
super(line, shapes);
}
#Override
public Paint getItemPaint(int row, int col) {
if(!offline){
return super.getItemPaint(row, col);
}else{
return new Color(0, 0, 0);
}
}
}
private void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Test demo = null; //pass date in from csv
try {
demo = new Test(TITLE);
} catch (ParseException e) {
e.printStackTrace();
}
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
demo.start();
}
});
}
}
What am I doing wrong?

One approach would be to append an appropriate baseline value when off line. Starting from this example, the range is centered on a value of zero millivolts. The modification below adds zeroes between 60 and 90 milliseconds:
private float[] gaussianData() {
float[] a = new float[COUNT];
for (int i = 0; i < a.length; i++) {
if (i > 60 && i < 90) a[i] = 0;
else a[i] = randomValue();
}
return a;
}
In my instance, a period of offline should effectively stop graphing.
Use the approach suggested here, which uses setMaximumItemAge() to limit the number of displayed records. Add null values, as suggested here, to interrupt the display. Starting from this example, I got this display with these changes:
seriesA.setMaximumItemCount(120);
seriesB.setMaximumItemCount(120);
…
int i;
…
public void addNull() {
this.seriesA.add(new Millisecond(), null);
this.seriesB.add(new Millisecond(), null);
}
#Override
public void actionPerformed(ActionEvent e) {
if (i > 60 && i < 90) {
demo.addNull();
} else {
…
}
i++;
}

Related

JFreeChart - Can't see plot unless I zoom in

I have a Jfreechart which is plotting some mock real-time data. When I have my domain axis set to auto, the data can be seen updating every second. However, I wish to plot the data over a wider range (say the whole day). When I change the range, I am then unable to see the plot unless I zoom in.
Once zoomed in, the line does not cover the whole graph, but only a portion. This line then moves across the graph instead of growing/drawing along it
/** #see http://stackoverflow.com/questions/5048852 */
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 = 10;
private static final int FAST = 1000;
private static final int SLOW = FAST * 5;
private static final Random random = new Random();
private double gateStart = ThreadLocalRandom.current().nextInt(0, 101);
private boolean returning = false;
private Timer timer;
public DTSCTest(final String title) {
super(title);
final DynamicTimeSeriesCollection dataset =
new DynamicTimeSeriesCollection(1, COUNT, new Second());
Date date = new Date();
dataset.setTimeBase(new Second(date));
float[] gateStartLoad = new float[1];
gateStartLoad[0] = (float)gateStart;
dataset.addSeries(gateStartLoad, 0, "Longwall Data");
JFreeChart chart = createChart(dataset);
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(combo);
this.add(btnPanel, BorderLayout.SOUTH);
timer = new Timer(FAST, new ActionListener() {
float[] newData = new float[1];
#Override
public void actionPerformed(ActionEvent e) {
if(gateStart == 100){
returning = true;
}else if(gateStart == 0){
returning = false;
}
if(returning){
gateStart--;
}else{
gateStart++;
}
newData[0] = (float)gateStart;
dataset.advanceTime();
System.out.println(dataset.getNewestTime());
dataset.appendData(newData);
}
});
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
TITLE, "hh:mm:ss", "Shearer Position", dataset, true, true, false);
final XYPlot plot = result.getXYPlot();
DateAxis domain = (DateAxis)plot.getDomainAxis();
Calendar calendar = Calendar.getInstance();
calendar.set(2021, 0, 6);
System.out.println(new Date());
System.out.println(calendar.getTime());
domain.setRange(new Date(), calendar.getTime());
domain.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
ValueAxis range = plot.getRangeAxis();
range.setRange(0, 100);
return result;
}
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();
}
});
}
}
How do I make it so that the line is continuous (shows every observed point of data in the series), and how do I make it visible when I manually set the range
I removed domain.setRange(new Date(), calendar.getTime()); and changed nMoments in my DynamicTimeSeriesCollection(1, COUNT, new Second());, making COUNT a multiple of 60 and increasing its value. My x-axis now properly shows time however the plot is not continuous, it disappears after a time

How to create Stacked bar chart Date time Category

I expect to create Status chart like this
However I cant XAXis Category was rendered incorrectly.
Here is my code I studied from JFreeChart - horizontal stacked bar chart with date axis
private static final String STANDBY_SERIES = "STANDBY";
private static final String HEATING_SERIES = "HEATING";
private static final String HOLDING_SERIES = "HOLDING";
private static final String COOLING_SERIES = "COOLING";
private static final String LOWERING_SERIES = "LOWERING";
private static final int STANDBY_SERIES_INDEX = 0;
private static final int HEATING_SERIES_INDEX = 1;
private static final int HOLDING_SERIES_INDEX = 2;
private static final int COOLING_SERIES_INDEX = 3;
private static final int LOWERING_SERIES_INDEX = 4;
private static final Color STANDBY_COLOR = Color.DARK_GRAY;
private static final Color HEATING_COLOR = Color.ORANGE;
private static final Color HOLDING_COLOR = Color.YELLOW;
private static final Color COOLING_COLOR = Color.CYAN;
private static final Color LOWERING_COLOR = Color.GREEN;
ArrayList<EventStatus> testData = null;
CategoryPlot plot;
private Long Datetolong(String date)
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date inputDate = null;
try {
inputDate = simpleDateFormat.parse(date);
System.out.println(inputDate.getTime());
} catch (ParseException e) {
e.printStackTrace();}
return inputDate.getTime();
}
public StackedTimeBarChart(String title) {
super(title);
// set up some test data
initData();
// set the start and end date of the chart
plot = new CategoryPlot();
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
plot.setOrientation(PlotOrientation.HORIZONTAL);
// create dataset
CategoryDataset dataset = createDataset();
// create the axis
CategoryAxis catAxis = new CategoryAxis();
DateAxis dateAxis = new DateAxis();
dateAxis.setVerticalTickLabels(true);
//dateAxis.setTickUnit(new DateTickUnit(DateTickUnitType.HOUR, 1));
dateAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yyyy HH:mm"));
// set up the renderer
StackedBarRenderer rend = new StackedBarRenderer();
//rend.setBase(chartRange.getLowerBound());
rend.setSeriesPaint(STANDBY_SERIES_INDEX, STANDBY_COLOR);
rend.setSeriesPaint(HEATING_SERIES_INDEX, HEATING_COLOR);
rend.setSeriesPaint(HOLDING_SERIES_INDEX, HOLDING_COLOR);
rend.setSeriesPaint(COOLING_SERIES_INDEX, COOLING_COLOR);
rend.setSeriesPaint(LOWERING_SERIES_INDEX, LOWERING_COLOR);
// set up the plot
plot.setDataset(dataset);
plot.setDomainAxis(catAxis);
plot.setRangeAxis(dateAxis);
plot.setRenderer(rend);
// create the chart and add it
JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(600, 450));
setContentPane(chartPanel);
}
private CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
Date chartStartDate = new Date(testData.get(0).getTime());
Date chartEndDate = new Date(testData.get(testData.size() - 1).getTime());
Range chartRange = new Range(chartStartDate.getTime(), chartEndDate.getTime());
if (testData != null) {
for (int i = 0; i < testData.size(); i++) {
// is there data?
if (testData.size() > 0) {
for (int j = 0; j < testData.size(); j++) {
EventStatus es = testData.get(j);
long eventTime = es.getTime();
int status = es.getStatus();
String name = es.getName();
// if data event time is in the range of the chart then show it
// THIS DOES NOT WORK PROPERLY!!!!
if (eventTime >= chartStartDate.getTime() && eventTime < chartEndDate.getTime()) {
// create series and categories
if (es.getStatus() == STANDBY_SERIES_INDEX) {
dataset.addValue(new Double(es.getTime()), STANDBY_SERIES, es.getName());
} else if (es.getStatus() == HEATING_SERIES_INDEX) {
dataset.addValue(new Double(es.getTime()), HEATING_SERIES, es.getName());
} else if (es.getStatus() == HOLDING_SERIES_INDEX) {
dataset.addValue(new Double(es.getTime()), HOLDING_SERIES, es.getName());
} else if (es.getStatus() == COOLING_SERIES_INDEX) {
dataset.addValue(new Double(es.getTime()), COOLING_SERIES, es.getName());
} else if (es.getStatus() == LOWERING_SERIES_INDEX) {
dataset.addValue(new Double(es.getTime()), LOWERING_SERIES, es.getName());
} else {
dataset.addValue(chartRange.getUpperBound() - chartRange.getLowerBound(), STANDBY_SERIES, es.getName());
}
} else {
continue;
}
}
}
}
} else {
plot.setNoDataMessage("NO DATA AVAILABLE");
}
return dataset;
}
public static void main(String[] args) {
StackedTimeBarChart demo = new StackedTimeBarChart("demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
private void initData() {
testData = new ArrayList<EventStatus>();
testData.add(new EventStatus("Mach-1", Datetolong("03/04/2020 08:00"), 1));
testData.add(new EventStatus("Mach-1",Datetolong("03/04/2020 09:00"), 2));
testData.add(new EventStatus("Mach-1", Datetolong("03/04/2020 09:20"), 4));
testData.add(new EventStatus("Mach-1", Datetolong("03/04/2020 10:00"), 3));
}
// Chart object class that hold category, event time and status
private class EventStatus {
private String name;
private long time;
private int status;
public EventStatus(String name, long time, int status) {
this.name = name;
this.time = time;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}

Update JFreeChart from thread

I have to build a GPS parser. I need to parse the NMEA string in another thread, which will be parsing a single NMEA string and update chart at 1 Hz. For now I build part of my code, but I parse data in main thread in while loop; my teacher said that is wrong. I was programming some on Java but not in multi-threading aspects. How I could move parsing process and refreshing chart to background thread?
public class MainFrame extends JFrame {
private JButton btnWybPlik;
private JLabel jlDroga;
private JLabel jlPredkosc;
private JLabel jlCzas;
private JPanel mainjpanel;
private JPanel jpMenu;
private JPanel jpTablica;
//private String sciezkaPliku;
private SekwencjaGGA sekGGA = null;
private SekwencjaGGA popSekGGA = null;
private SekwencjaGSA sekGSA;
private SekwencjaGLL sekGLL;
private SekwencjaRMC sekRMC;
private double droga;
private double predkosc;
private XYSeries series1;
private XYSeriesCollection dataset;
public MainFrame() {
droga = 0;
btnWybPlik.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(mainjpanel);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
//System.out.println("Selected file: " + selectedFile.getAbsolutePath());
String sciezkaPliku = selectedFile.getAbsolutePath();
wczytaniePliku(sciezkaPliku);
}
}
});
jpTablica = new JPanel();
mainjpanel.add(jpTablica);
this.series1 = new XYSeries("Trasa", false);
final XYSeriesCollection dataset = new XYSeriesCollection(this.series1);
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
jpTablica.add(chartPanel);
}
private void wczytaniePliku(String sciezkaDoPliku) {
try (BufferedReader br = new BufferedReader(new FileReader(sciezkaDoPliku))) {
String line;
//series1.add(53.448, 14.4907);
while ((line = br.readLine()) != null) {
parseLine(line);
}
//series1.add(53.4485, 14.4910);
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseLine(String line) {
String bezSumKont = line.substring(0, line.length() - 3);
List<String> podzSekw = Arrays.asList(bezSumKont.split(","));
if (podzSekw.get(0).equalsIgnoreCase("$GPGGA")) {
if (check(line)) {
if (sekGGA != null)
popSekGGA = sekGGA;
sekGGA = new SekwencjaGGA(podzSekw);
if (popSekGGA != null) {
droga += obliczOdleglosc(popSekGGA, sekGGA);
jlDroga.setText(String.valueOf(droga));
}
series1.add(sekGGA.getWspolzedne().getLongitude(), sekGGA.getWspolzedne().getLatitude());
System.out.println(sekGGA.getWspolzedne().getLatitude() + " " + sekGGA.getWspolzedne().getLongitude());
//System.out.println(series1.getMaxY() + " " + series1.getMinY());
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGSA")) {
if (check(line)) {
sekGSA = new SekwencjaGSA(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGLL")) {
if (check(line)) {
sekGLL = new SekwencjaGLL(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPRMC")) {
//TODO: Sekwencja RMC (Recommended minimum of data)
if (check(line)) {
sekRMC = new SekwencjaRMC(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
}
private double obliczOdleglosc(SekwencjaGGA pkt1, SekwencjaGGA pkt2) {
double odleglosc = 0;
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(pkt2.getWspolzedne().getLatitude() - pkt1.getWspolzedne().getLatitude());
double dLng = Math.toRadians(pkt2.getWspolzedne().getLongitude() - pkt1.getWspolzedne().getLongitude());
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) * Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
odleglosc = earthRadius * c;
return odleglosc;
}
/**
* Funkcja sprawdzająca sume kontrolną
*
* #param tekst cała linia NMEA
* #return true jeśli się suma kontrolna zgadza
*/
private boolean check(String tekst) {
String suma = tekst.substring(tekst.length() - 2, tekst.length());
tekst = tekst.substring(1, tekst.length() - 3);
int checksum = 0;
for (int i = 0; i < tekst.length(); i++) {
checksum = checksum ^ tekst.charAt(i);
}
if (Integer.parseInt(suma, 16) == checksum) {
return true;
}
return false;
}
private JFreeChart createChart(final XYDataset dataset) { ... }
private void customizeChart(JFreeChart chart) { ... }
public static void main(String[] args) {
JFrame frame = new JFrame("MainFrame");
frame.setContentPane(new MainFrame().mainjpanel);
frame.setPreferredSize(new Dimension(640, 480));
frame.pack();
frame.setVisible(true);
}
To avoid blocking the event dispatch thread, construct an instance of SwingWorker. Collect data in your implementation of doInBackground(), publish() intermediate results, and update the XYSeries in your implementation of process(). The listening chart will update itself in response. A related example that uses jfreechart is seen below and examined here.

List of DisplayModes contains each mode 3 times

I'm trying to get a list of available display modes for my laptop. I'm running the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice display = ge.getDefaultScreenDevice();
DisplayMode[] availableModes = display.getDisplayModes();
This returns 112 possible display modes. When I print the list however I can see a lot of doubles. All most all display modes are printed 3 times. Would anyone know the cause of this?
800x600 8 bit 60 Hz
800x600 8 bit 60 Hz
800x600 8 bit 60 Hz
800x600 16 bit 60 Hz
800x600 16 bit 60 Hz
800x600 16 bit 60 Hz
800x600 32 bit 60 Hz
800x600 32 bit 60 Hz
800x600 32 bit 60 Hz
Kind regards
please to try that with this code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class DisplayModeModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
private DisplayMode[] modes;
public DisplayModeModel(DisplayMode[] modes) {
this.modes = modes;
}
public DisplayMode getDisplayMode(int r) {
return modes[r];
}
#Override
public String getColumnName(int c) {
return DisplayModeTest.COLUMN_NAMES[c];
}
#Override
public int getColumnCount() {
return DisplayModeTest.COLUMN_WIDTHS.length;
}
#Override
public boolean isCellEditable(int r, int c) {
return false;
}
#Override
public int getRowCount() {
if (modes == null) {
return 0;
}
return modes.length;
}
#Override
public Object getValueAt(int rowIndex, int colIndex) {
DisplayMode dm = modes[rowIndex];
switch (colIndex) {
case DisplayModeTest.INDEX_WIDTH:
return Integer.toString(dm.getWidth());
case DisplayModeTest.INDEX_HEIGHT:
return Integer.toString(dm.getHeight());
case DisplayModeTest.INDEX_BITDEPTH: {
int bitDepth = dm.getBitDepth();
String ret;
if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
ret = "Multi";
} else {
ret = Integer.toString(bitDepth);
}
return ret;
}
case DisplayModeTest.INDEX_REFRESHRATE: {
int refreshRate = dm.getRefreshRate();
String ret;
if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
ret = "Unknown";
} else {
ret = Integer.toString(refreshRate);
}
return ret;
}
}
throw new ArrayIndexOutOfBoundsException("Invalid column value");
}
}
class DisplayModeTest extends JFrame implements ActionListener, ListSelectionListener {
private static final long serialVersionUID = 1L;
private boolean waiting = false;
private GraphicsDevice device;
private DisplayMode originalDM;
private JButton exit = new JButton("Exit");
private JButton changeDM = new JButton("Set Display");
private JLabel currentDM = new JLabel();
private JTable dmList = new JTable();
private JScrollPane dmPane = new JScrollPane(dmList);
private boolean isFullScreen = false;
public static final int INDEX_WIDTH = 0;
public static final int INDEX_HEIGHT = 1;
public static final int INDEX_BITDEPTH = 2;
public static final int INDEX_REFRESHRATE = 3;
public static final int[] COLUMN_WIDTHS = new int[]{
100, 100, 100, 100
};
public static final String[] COLUMN_NAMES = new String[]{
"Width", "Height", "Bit Depth", "Refresh Rate"
};
public DisplayModeTest(GraphicsDevice device) {
super(device.getDefaultConfiguration());
this.device = device;
setTitle("Display Mode Test");
originalDM = device.getDisplayMode();
setDMLabel(originalDM);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Make sure a DM is always selected in the list
exit.addActionListener(this);
changeDM.addActionListener(this);
changeDM.setEnabled(device.isDisplayChangeSupported());
}
#Override
public void actionPerformed(ActionEvent ev) {
Object source = ev.getSource();
if (source == exit) {
device.setDisplayMode(originalDM);
System.exit(0);
} else { // if (source == changeDM)
int index = dmList.getSelectionModel().getAnchorSelectionIndex();
if (index >= 0) {
DisplayModeModel model = (DisplayModeModel) dmList.getModel();
DisplayMode dm = model.getDisplayMode(index);
device.setDisplayMode(dm);
setDMLabel(dm);
setSize(new Dimension(dm.getWidth(), dm.getHeight()));
validate();
}
}
}
#Override
public void valueChanged(ListSelectionEvent ev) {
changeDM.setEnabled(device.isDisplayChangeSupported());
}
private void initComponents(Container c) {
setContentPane(c);
c.setLayout(new BorderLayout());
JPanel currentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Current DM
c.add(currentPanel, BorderLayout.NORTH);
JLabel current = new JLabel("Current Display Mode : ");
currentPanel.add(current);
currentPanel.add(currentDM);
JPanel modesPanel = new JPanel(new GridLayout(1, 2));// Display Modes
c.add(modesPanel, BorderLayout.CENTER);
for (int i = 0; i < COLUMN_WIDTHS.length; i++) { // List of display modes
TableColumn col = new TableColumn(i, COLUMN_WIDTHS[i]);
col.setIdentifier(COLUMN_NAMES[i]);
col.setHeaderValue(COLUMN_NAMES[i]);
dmList.addColumn(col);
}
dmList.getSelectionModel().setSelectionMode( ListSelectionModel.SINGLE_SELECTION);
dmList.getSelectionModel().addListSelectionListener(this);
modesPanel.add(dmPane);
JPanel controlsPanelA = new JPanel(new BorderLayout());// Controls
modesPanel.add(controlsPanelA);
JPanel controlsPanelB = new JPanel(new GridLayout(2, 1));
controlsPanelA.add(controlsPanelB, BorderLayout.NORTH);
JPanel exitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Exit
controlsPanelB.add(exitPanel);
exitPanel.add(exit);
JPanel changeDMPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// Change DM
controlsPanelB.add(changeDMPanel);
changeDMPanel.add(changeDM);
controlsPanelA.add(new JPanel(), BorderLayout.CENTER);
}
#Override
public void setVisible(boolean isVis) {
super.setVisible(isVis);
if (isVis) {
dmList.setModel(new DisplayModeModel(device.getDisplayModes()));
}
}
private void setDMLabel(DisplayMode newMode) {
int bitDepth = newMode.getBitDepth();
int refreshRate = newMode.getRefreshRate();
String bd, rr;
if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
bd = "Multi";
} else {
bd = Integer.toString(bitDepth);
}
if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
rr = "Unknown";
} else {
rr = Integer.toString(refreshRate);
}
currentDM.setText(
COLUMN_NAMES[INDEX_WIDTH] + ": " + newMode.getWidth() + " "
+ COLUMN_NAMES[INDEX_HEIGHT] + ": " + newMode.getHeight() + " "
+ COLUMN_NAMES[INDEX_BITDEPTH] + ": " + bd + " "
+ COLUMN_NAMES[INDEX_REFRESHRATE] + ": " + rr);
}
public void begin() {
isFullScreen = device.isFullScreenSupported();
setUndecorated(isFullScreen);
setResizable(!isFullScreen);
if (isFullScreen) {
device.setFullScreenWindow(this); // Full-screen mode
validate();
} else {
pack();// Windowed mode
setVisible(true);
}
}
public static void main(String[] args) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = env.getScreenDevices();
// REMIND : Multi-monitor full-screen mode not yet supported
for (int i = 0; i < 1 /* devices.length */; i++) {
DisplayModeTest test = new DisplayModeTest(devices[i]);
test.initComponents(test.getContentPane());
test.begin();
}
}
}

compress the horizontal line of real time graph

I want to compress and store data of real time line graph I tried but not succeeded
public class DTest extends ApplicationFrame {
javax.swing.Timer _timer;
int nPoints = 200;
float[] history;
/** The most recent value added. */
private float lastValue = (float) 100.0;
DynamicTimeSeriesCollection dataset;
JPanel content;
private final ChartPanel chartPanel;
public DTest(final String title) {
super(title);
history = new float[nPoints];
dataset = new DynamicTimeSeriesCollection(
1, nPoints, new Second()//here speed will set
);
dataset.setTimeBase(new Second(0,0,0,1,1,2000));
dataset.addSeries(new float[]{0.0f}, 0, "S1");
System.out.println("Series count = " + dataset.getSeriesCount());
final JFreeChart chart = createChart(dataset);
chartPanel = new ChartPanel(chart);
content = new JPanel(new FlowLayout());
final JButton btn = new JButton("Stop");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_timer.stop();
}
});
final JButton btn1 = new JButton("Run");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create new dataset and chart, set the new chart in the chartpanel
//createChart(dataset);
_timer.start();
}
});
JComboBox comb = new JComboBox();
comb.addItem("Select");
comb.addItem("Joy Stick");
content.add(chartPanel);//panel for chart
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(btn);
btnPanel.add(btn1);
btnPanel.add(comb);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(content, BorderLayout.NORTH);
pane.add(btnPanel, BorderLayout.CENTER);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
//setContentPane(content);
comb.addActionListener(new ActionListener() {
private float[] float_array;
private int itemCount;
public void actionPerformed(ActionEvent e) {
JComboBox jComb = (JComboBox) e.getSource();
if (jComb.getSelectedItem().equals("Joy Stick")) {
System.out.println("Joy Stick is Pressed");
try {
float_array = new float[1];
float_array[0] = 0;
itemCount = 0;
dataset.appendData(float_array);
dataset.addSeries(new float[]{0.0f}, 0, "S1");
_timer = new javax.swing.Timer(1, new ActionListener() { // 500ms
private int resizes;
private int inserted;
public void actionPerformed(ActionEvent e) {
double factor = 0.90 + 0.2 * Math.random();
lastValue = lastValue * (float) factor;
float_array[0] = lastValue;
System.out.println("lastValue is " + lastValue);
inserted++;
if ( inserted % (resizes+1)==0 )
dataset.appendData(float_array, itemCount++, 1);
history[itemCount] = lastValue;
if (itemCount >= nPoints - 1) {
resizes++;
DynamicTimeSeriesCollection newSet = new DynamicTimeSeriesCollection(1, nPoints, new Second());
newSet.setTimeBase(new Second(0,0,0,2,2,2000));
newSet.addSeries(new float[]{0.0f}, 0, "S1");
itemCount /= 2;
for (int i = 1; i < nPoints; i++) {
history[i / 2] = history[i];
float_array[0]=history[i / 2];
newSet.appendData(float_array, i/2, 1);
history[i] = 0;
}
chartPanel.setChart(createChart(newSet));
dataset = newSet;
chartPanel.repaint();
}
}
});
_timer.setRepeats(true);
_timer.start();
} catch (NullPointerException ne) {
System.out.println("NullPointer Exception" + ne.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
} else { ;
}
}
});
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
"Dynamic Graph", "Time", "Value", dataset, true, true,
false);
final XYPlot plot = result.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
//plot.setRangeAxis(WIDTH, axi)
axis.setAutoRange(true);
//axis.setFixedAutoRange(60.0); // 60 seconds
axis = plot.getRangeAxis();
axis.setRange(-100.0, 200.0);
return result;
}
public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
final DTest demo = new DTest("Dynamic Graph");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
demo.setVisible(true);
} catch (Exception e) {
}
}
});
}
}
…as the line moves forward, the previous line value should not disappear, but it should begin to compress itself.
The Memory Usage tab of the demo does exactly what you describe.

Categories