compress the horizontal line of real time graph - java

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.

Related

JFreeChart | Not able to position a graph properly in a specific location inside a JPanel

I have a project that uses JFreeChart.
The chart that I am using is displaying correctly and works fine with the current code.
My problem is that I can only position the graph to the east, south, west, center or north of my JPanel.
My desire is to move this chart to any position inside my JPanel.
This is the short code snippet where I add my graph to the panSimulator JPanel. The problematic code is at the bottom of the ConfigurationFrame class:
public class ConfigurationFrame extends JFrame {
private KettlerBikeConnector bike1 = null;
private static final long serialVersionUID = 1L;
CrosshairDemo chd = new CrosshairDemo();
private JPanel panSimulator;
private PanelBikeSimulator panBSim;
private Timer timerBike;
private TimerListener listener;
private final int UPDATE_MS = 1000; // updates every second
private JTabbedPane tabPane;
private JPanel panConfiguration;
private JPanel panGame;
private JComboBox<String> cbxPort;
private JTextPane lblStatus;
// to have access to the textfield
public static JTextField txtEnergy;
public static JTextField txtDistance;
public static JTextField txtHeartRate;
public static JTextField txtTime;
public File path = null;
public int key = -1;
boolean run = true;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConfigurationFrame frame = new ConfigurationFrame();
frame.setVisible(true);
// frame.pack(); // give a suitable size to window automatically
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
* #throws SAXException
* #throws ParserConfigurationException
*/
public ConfigurationFrame() throws ParserConfigurationException, SAXException, IOException {
setResizable(false);
setMinimumSize(new Dimension(1900, 1000));
setTitle("Bike Simulation ... I need a name ...");
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
try {
timerBike.stop();
bike1.close();
} catch (Exception e) {
log(e.getMessage());
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
getContentPane().setLayout(null);
// Panel
tabPane = new JTabbedPane(JTabbedPane.TOP);
tabPane.setFont(new Font("Tahoma", Font.PLAIN, 24));
tabPane.setBounds(0, 0, 1892, 994);
getContentPane().add(tabPane);
// Configuration-Panel
panConfiguration = new JPanel();
tabPane.addTab("Configuration", null, panConfiguration, null);
panConfiguration.setLayout(null);
// ComboBox for Kettler
cbxPort = new JComboBox<String>();
cbxPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
cbxPort.setBounds(734, 5, 247, 49);
panConfiguration.add(cbxPort);
// Button-Connection
JButton btnConnect = new JButton("Connect");
btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnConnect.setBounds(157, 7, 137, 49);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
bike1 = new KettlerBikeConnector();
bike1.connect(cbxPort.getSelectedItem().toString(), new KettlerBikeListener() {
#Override
public void bikeAck() {
switch (listener.state) {
case hello:
listener.state = State.connected;
break;
case reset:
listener.state = State.hello;
break;
case connected:
log("connection successful");
break;
case notConnected:
log("not connected");
break;
}
}
#Override
public void bikeData(DataRecord data) {
//Sending the Ergometer velcoity every 1000ms to the
panBSim.setErgometerVelocity(data.getSpeed() / 10);
panBSim.setErgometerRPM(data.getPedalRpm());
panBSim.setTrueDataHere(true);
double power = panBSim.getTraveledDistance();
chd.setPower(power);
//getPower und dann set hier die Ergometer widerstand
try {
bike1.sendSetPower(panBSim.getErgometerPower());
} catch (IOException ignored) {
System.out.println("ignored");
}
}
#Override
public void bikeDestPowerChanged(int power) {
log("dest power: " + power);
}
#Override
public void bikeError() {
log("error1");
}
});
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnConnect);
// Button-Start
JButton btnStart = new JButton("Start");
btnStart.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnStart.setBounds(304, 7, 137, 49);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
listener = new TimerListener(bike1);
timerBike = new Timer(UPDATE_MS, listener);
timerBike.start();
tabPane.setSelectedComponent(panSimulator); // switch to GamePanel
panBSim.startSimulate();
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnStart);
// Button-Scan
JButton btnScan = new JButton("Scan");
btnScan.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnScan.setBounds(10, 7, 137, 49);
btnScan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers(); // list of named
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
cbxPort.addItem(portId.getName());
if (portId.isCurrentlyOwned()) {
log("Port " + portId.getName() + " is already open");
}
}
}
}
});
panConfiguration.add(btnScan);
// Status displays information regarding connection
lblStatus = new JTextPane();
lblStatus.setText(
"Anweisung:\r\n\t1) W\u00E4hle ein Lebensmittel aus der Food-Item Combobox aus\r\n\t2) Dr\u00FCcke den Scan-Button und w\u00E4hle den Port aus der Port Combobox aus\r\n\t3) Dr\u00FCcke den Connect-Button, um die Ger\u00E4te zu verbinden\r\n\t4) Dr\u00FCcke den Start-Button, um die Anwendung zu starten\r\n\t5) Warte auf das akustische Signal des Ergometer\r\n\t6) Beginne zu treten");
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblStatus.setBounds(10, 125, 971, 229);
lblStatus.setDisabledTextColor(Color.BLACK);
lblStatus.setSelectionColor(new Color(51, 153, 255));
panConfiguration.add(lblStatus);
// FH Logo
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(10, 365, 971, 430);
try {
File in = new File("FHLogo.png");
Image logo = ImageIO.read(in);
Image scaledLogo = logo.getScaledInstance(lblLogo.getWidth(), lblLogo.getHeight(), Image.SCALE_SMOOTH);
ImageIcon iconLogo = new ImageIcon(scaledLogo);
lblLogo.setIcon(iconLogo);
} catch (IOException e2) {
e2.printStackTrace();
}
panConfiguration.add(lblLogo);
// Labels
JLabel lblPort = new JLabel("Port:");
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblPort.setBounds(600, 5, 124, 49);
panConfiguration.add(lblPort);
//-----------------------------------------------------------------------------XXX
//Tab Bike Simulator
BorderLayout bdl = new BorderLayout();
panSimulator = new JPanel();
tabPane.addTab("Bike Simulator", null, panSimulator, null);
panSimulator.setLayout(bdl);
//Panel Bike Simulator
//panBSim = new PanelBikeSimulator();
//panBSim.setBorder(BorderFactory.createLineBorder(Color.black));
panSimulator.add(chd.getContentPane(), bdl.NORTH);
}
/**
* To log information
*
* #param str String that is shown
*/
private void log(String str) {
lblStatus.setText(lblStatus.getText() + str + "\n");
}
}
And this class belongs to my chart that I want to move to any location in my JPanel.
public class CrosshairDemo extends JFrame {
private static double POWER = 0.0;
public void setPower(double power) {
POWER = power;
}
public CrosshairDemo() {
super();
this.setContentPane(new CrosshairDemo.MyDemoPanel());
}
public static class MyDemoPanel extends JPanel implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
Thread t = new Thread((Runnable) this);
private TimeSeries series;
private final ChartPanel chartPanel;
private final JFreeChart chart = this.createChart();
public MyDemoPanel() {
super(new BorderLayout());
this.chartPanel = new ChartPanel(this.chart);
this.chartPanel.setPreferredSize(new Dimension(200, 550));
this.chartPanel.setLocation(getWidth() + 50, getHeight() + 30);
this.chartPanel.setDomainZoomable(true);
this.chartPanel.setRangeZoomable(true);
this.add(this.chartPanel);
t.start();
}
private JFreeChart createChart() {
XYDataset dataset1 = this.createDataset("Random 1", 100.0D, new Minute(), 200);
JFreeChart chart1 = ChartFactory.createTimeSeriesChart("Crosshair Demo 1", "Time of Day", "Value", dataset1);
XYPlot plot = (XYPlot)chart1.getPlot();
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setDomainCrosshairVisible(true);
plot.setDomainCrosshairLockedOnData(false);
plot.setRangeCrosshairVisible(false);
return chart1;
}
private XYDataset createDataset(String name, double base, RegularTimePeriod start, int count) {
this.series = new TimeSeries(name);
RegularTimePeriod period = start;
double value = base;
for(int i = 0; i < count; ++i) {
this.series.add(period, value);
period = period.next();
value *= 1.0D + (Math.random() - 0.495D) / 10.0D;
}
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(this.series);
return dataset;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true) {
int value = (int) POWER; //this.slider.getValue();
XYPlot plot = (XYPlot)this.chart.getPlot();
ValueAxis domainAxis = plot.getDomainAxis();
Range range = domainAxis.getRange();
double c = domainAxis.getLowerBound() + (double)value / 100.0D * range.getLength();
plot.setDomainCrosshairValue(c);
}
}
}
Right now it's "attached" to the top (NORTH) of my JPanel:
Current chart position:
I would appreciate any help, because I have no more idea how to position this chart freely, therefore, I need your help guys.

JFreeChart - XYLineAndShapeRenderer getItemLineVisible() not working

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++;
}

JInternalFrame does not show up

from my MainFrame I create a internal Frame and add that to my desktop pane, but the internal Frame just won't show up. I tried to figure it out for 3 hours now and I kinda need some help with it. Before I implemented the observer pattern it just worked fine. So I thought it got something to do with that and changed some stuff and double checked the crucial code. No solution so far. I just realized how crappy my english is sometimes. Sorry for that!
The 2 code blocks are already shortened. Sorry that they are still pretty long. But I am just not sure where I made the mistake. If you need more code or anything else, just tell me. Thank you very much in advance.
This is the code of my main frame:
public class LangtonsAmeise extends JFrame implements ActionListener {
private JDesktopPane desk;
private JPanel panelButtons;
JMenuBar jmb;
JMenu file,modus;
JMenuItem load,save, exit, mSetzen,mMalen,mLaufen;
JSlider slider;
static int xInt, yInt,xFrame=450,yFrame=450;
static boolean bSetzen = false, bMalen = false, running = false;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText,status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
/* Those 4 lines work just fine. Internal Frame gets displayed.
JInternalFrame j = new JInternalFrame();
desk.add(j);
j.setSize(new Dimension(300,300));
j.setVisible(true);
*/
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
xField.setDocument(new IntegerDocument(2));
yField.setDocument(new IntegerDocument(2));
start = new JButton("Fenster erstellen");
stop = new JButton("Stopp");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(slider);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Aktueller Modus:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("Datei");
modus = new JMenu("Modus");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(save);
file.add(load);
file.addSeparator();
file.add(exit);
save.addActionListener(this);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(1000, 900));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
new popUpWindow(
"Sie müssen eine Zahl zwischen 2 und 99 angeben!!");
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, xInt, yInt);
s.addObserver(k);
addChild(k, this.getSize().width, this.getSize().height);
}
}
if (e.getActionCommand().equals("Stopp")) {
running=!running;
status.setText("Stopp");
}
}
public void addChild(JInternalFrame kind, int xPixel, int yPixel) {
// kind.setSize(370, 370);
kind.setLocation(randomGenerator.nextInt(xPixel - kind.getSize().height),
randomGenerator.nextInt(yPixel - kind.getSize().height - 100));
kind.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
desk.add(kind);
kind.setVisible(true);
kind.repaint();
kind.validate();
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
And this is my Internal Frame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
static int sleeptime;
state s;
ArrayList<JButton> jbArray = new ArrayList<>();
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
public static ArrayList<AmeiseThread> threadList = new ArrayList<>();
Color alteFarbe, neueFarbe;
JButton save, addAnt;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,int x, int y) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
setSize(new Dimension(xFrame, yFrame));
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(y, x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("Simulation speichern");
addAnt = new JButton("Ameise hinzufügen");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (threadList.size() >= 0) {
for (AmeiseThread t : threadList) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
sleeptime = 1000 / speed;
}
}
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
setVisible(true);
repaint();
validate();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Ameise hinzufügen")) {
threadList.add(new AmeiseThread(this));
threadList.get(threadList.size() - 1).start();
}
if (e.getActionCommand().equals("Simulation speichern")) {
OutputStream fos = null;
try {
fos = new FileOutputStream("test");
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(this );
} catch (IOException e1) {
System.err.println(e1);
} finally {
try {
fos.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
I think it is because you didn't set size for your JInternalFrame. In your code it is as a comment:
//kind.setSize(370, 370);
when I remove "//" it works for me.

drawing a graph using an updating JSlider

I'm making a grapher that draws a graph from a mathematical expression given by user .additionally the program has a slider and play button that user can choose a variable for the slider and its range so upon clicking the play button the slider will start from minimum range to maximum and the graph will be drawn.
for the timer I'm using the answer from a previous question.
for the grapher I'm using This code. (I'm working specifically on Plotter.java file)
The edited Plotter.java file with the playable slider(timer) code :
import java.util.*;
public class Plotter extends JFrame implements ActionListener
{
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private int value;
private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton ;
private Graph graph;
private JPanel userPanel , sliderPanel;
private JSlider slider_1 = new JSlider();
private JButton playButton = new JButton();
private JTextField textField = new JTextField();
private Timer timer ;
private ImageIcon playIcon = new ImageIcon(getClass().getResource("/images/play.png"));
private ImageIcon pauseIcon = new ImageIcon(getClass().getResource("/images/pause.png"));
public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
super("Plotter");
textField.setBounds(266, 11, 134, 28);
textField.setColumns(10);
createNewGraph(lowX, highX, frequency, file);
createLayout();
//createsliderpanel();
}
private void createLayout() throws GraphArgumentsException
{
Container c = getContentPane();
setSize(850,600);
getContentPane().setLayout(null);
c.add(graph);
c.add(userPanel);
JPanel down = new JPanel();
down.setBounds(0, 437, 650, 119);
getContentPane().add(down);
down.setLayout(null);
slider_1.setValue(0);
slider_1.setMajorTickSpacing(5);
slider_1.setMinorTickSpacing(1);
slider_1.setPaintLabels(true);
slider_1.setPaintTicks(true);
slider_1.setBounds(145, 51, 467, 42);
down.add(slider_1);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
playButton.setBounds(16, 51, 117, 29);
playButton.setIcon(playIcon);
down.add(playButton);
down.add(textField);
JPanel panel_1 = new JPanel();
panel_1.setBounds(649, 39, 201, 517);
getContentPane().add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
// c.add(sliderPanel , BorderLayout.SOUTH);
createMenuBar();
}
/**
* Creates a new Graph instance and adds equations from file into Graph
* #param eqFile file where equations are stored
* #throws IOException
*/
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
Equation[] eq = null;
graph = new Graph(minX, maxX, freq);
graph.setBounds(0, 39, 650, 396);
eq = readEquationsFromFile(eqFile);
if (eq != null)
addEquation(eq);
graph.setBackground(Color.WHITE);
userPanel = createUserPanel(eq);
}
private void createMenuBar()
{
menuBar.add(fileMenu);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
openMenuItem.addActionListener(this);
saveMenuItem.addActionListener(this);
exitMenuItem.addActionListener(this);
setJMenuBar(menuBar);
}
/**
* Create user panel at top of the GUI for adding and editing functions
* #param eq equation list to add into the combo box
* #return panel containing buttons and an editable combo box
*/
private JPanel createUserPanel(Equation[] eq)
{
JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
up.setBounds(0, 0, 844, 39);
eqCombo.setEditable(true);
if (eq != null)
{
//Add all equations into the combo box
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
addButton = new JButton("Add");
removeButton = new JButton("Remove");
clearButton = new JButton("Clear");
addButton.addActionListener(this);
removeButton.addActionListener(this);
clearButton.addActionListener(this);
up.add(eqCombo);
up.add(addButton);
up.add(removeButton);
up.add(clearButton);
return up;
}
// slider panel
/*private JPanel createsliderpanel()
{
JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));
playbutton = new JButton("Play");
slider = new JSlider();
field = new JTextField();
down.add(playbutton);
down.add(slider);
down.add(field);
return down;
}*/
/**
* Check action lister for button and menu events
*/
public void actionPerformed(ActionEvent e)
{
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int value = slider_1.getValue() + 1;
if (value >= slider_1.getMaximum()) {
stopTheClock();
} else {
slider_1.setValue(value);
}
}
});
slider_1.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textField.setText(Integer.toString(slider_1.getValue()));
}
});
slider_1.setValue(0);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
stopTheClock();
} else {
startTheClock();
}
}
});
if (e.getSource() == addButton)
addEquation((String)eqCombo.getSelectedItem());
else if (e.getSource() == removeButton)
removeEquation(eqCombo.getSelectedIndex());
else if (e.getSource() == saveMenuItem)
saveEquationList();
else if (e.getSource() == openMenuItem)
loadEquations();
else if (e.getSource() == clearButton)
clearEquations();
else if (e.getSource() == exitMenuItem)
System.exit(0);
}
/**
* Save equations to file
*
*/
private void saveEquationList()
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
for (int i = 0; i < eqCombo.getItemCount(); i++)
out.println(eqCombo.getItemAt(i));
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
private void clearEquations()
{
graph.removeAllEquations();
eqCombo.removeAllItems();
}
/**
* Load equations from file into graph
*
*/
private void loadEquations()
{
String file=null;
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
if (fc.getSelectedFile() != null)
{
file = fc.getSelectedFile().getPath();
try
{
Equation[] eq = readEquationsFromFile(file);
if (eq != null)
{
clearEquations();
addEquation(eq);
//Restock combo box with new equations
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Add an equation to the Graph
* #param eq equation
*/
private void addEquation(String eq)
{
try
{
if (eq != null && !eq.equals(""))
{
Equation equation = new Equation(eq);
eqCombo.addItem(eq);
graph.addEquation(equation);
}
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Add multiple equations to Graph
* #param eq equation array
*/
private void addEquation(Equation[] eq)
{
for (int i = 0; i < eq.length; i++)
{
graph.addEquation(eq[i]);
}
}
/**
* Remove equation from Graph
* #param index index to remove
*/
private void removeEquation(int index)
{
if (index >= 0)
{
graph.removeEquation(index);
eqCombo.removeItem(eqCombo.getSelectedItem());
}
}
// Timer methods
protected void startTheClock() {
slider_1.setValue(0);
timer.start();
playButton.setIcon(pauseIcon);;
}
protected void stopTheClock() {
timer.stop();
playButton.setIcon(playIcon);
}
/**
* Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
* #param file name of file containing equations
* #return array of equations
* #throws IOException
*/
public Equation[] readEquationsFromFile(String file) throws IOException
{
ArrayList<Equation> eqList = new ArrayList<Equation>(20);
if (file == null)
return null;
String line;
int lineCount = 1;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Equation eq = new Equation(line);
eqList.add(eq);
lineCount++;
}
br.close();
return ((Equation[])(eqList.toArray(new Equation[0])));
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
return null;
}
}
/**
* Set up Plotter object and draw the graph.
* #param args command line arguments for Plotter
*/
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String expr = JOptionPane.showInputDialog("Enter your expression");
String maxInput = JOptionPane.showInputDialog("Enter max value of x");
String minInput = JOptionPane.showInputDialog("Enter min value of x");
double frequency = 0.01;
double maxX = Double.parseDouble(maxInput);
double minX = Double.parseDouble(minInput);
String eqFile = null;
try
{
///double minX = Double.parseDouble(args[0]);
// double maxX = Double.parseDouble(args[1]);
// double frequency = Double.parseDouble(args[2]);
//double minX = -10;
//double maxX = 10;
//double frequency = 0.01;
if (args.length > 3)
eqFile = args[3];
Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
plotterGUI.setVisible(true);
plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (NumberFormatException e)
{
System.out.println("ERR: Invalid arguments");
}
catch (GraphArgumentsException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.print("ERR4: Unable to read or access file");
}
}
}
general look of program :
now I want to change the code so the slider will affect the grapher .it means when user chooses the range of x from -10 to 10 , by clicking the play button the grapher starts to draw the graph as slider changes the x from -10 to 10
Gapminder chart is an example about slider and grapher should work.
The question is how can I do this ?
here is a small code which might help you get the insight of JSlider.
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class demo extends JFrame
{
JFrame f=new JFrame("G");
JSlider slide=new JSlider();
JTextField field=new JTextField();
JTextField d=new JTextField();
final double value=0;
demo()
{
setSize(500,500);
f.setSize(600,600);
f.setVisible(true);
slide.setBounds(100,100,200,50);
field.setBounds(150,150,100,30);
d.setBounds(0,0,0,0);
add(slide);
add(field);
add(d);
}
public static void main(String args[])
{
demo m=new demo();
m.setVisible(true);
m.setLocationRelativeTo(null);
m.slidec();
}
public double slidec()
{
slide.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
double value=((JSlider)e.getSource()).getValue();
field.setText(Double.toString(value));
}
});
return value;
}
}

Exception in thread "Thread-1" java.lang.NullPointerException that happens when I try to update my graph

I edited a JFreeChart real time graph and now I get this error when I try to run it. When I run it, the GUI will pop up its just the graph doesn't have the random data stream in.
Any ideas would be a great help.
public class Therm extends ApplicationFrame implements ActionListener{
private static TimeSeries ts;
JTextArea text = new JTextArea("25");
JTextArea degreeC = new JTextArea("degrees C");
JTextArea degreeF = new JTextArea("degrees F");
public Therm(final String title){
super(title);
ts = new TimeSeries("Data", Millisecond.class);
TimeSeriesCollection data = new TimeSeriesCollection(ts);
JFreeChart chart = create(data);
JFrame frame = new JFrame("GraphTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChartPanel label = new ChartPanel(chart);
frame.getContentPane().add(label);
ChartPanel chartPanel = new ChartPanel(chart);
JButton buttonC = new JButton("Celsius");
JButton buttonF = new JButton("Farenheit");
JButton button1 = new JButton("Toggle Extension (60 and 300 seconds)");
JButton buttonOff = new JButton("Turn Box");
buttonC.setActionCommand("C");
buttonC.addActionListener(this);
buttonF.setActionCommand("F");
buttonF.addActionListener(this);
button1.setActionCommand("ADD");
button1.addActionListener(this);
buttonOff.setActionCommand("off");
buttonOff.addActionListener(this);
Font font = new Font ("Verdana", Font.BOLD, 26);
text.setFont(font);
degreeC.setFont(font);
degreeF.setFont(font);
JPanel graph = new JPanel(new BorderLayout());
graph.add(chartPanel);
chartPanel.setPreferredSize(new java.awt.Dimension(700,300));
setContentPane(graph);
JPanel content = new JPanel(new GridLayout(3,2));
content.setLayout(new GridLayout(3,2));
content.add(text);
content.add(degreeC);
content.add(buttonC);
content.add(buttonF);
content.add(button1);
content.add(buttonOff);
add(content,BorderLayout.SOUTH);
chartPanel.setPreferredSize(new java.awt.Dimension(700,300));
}
private JFreeChart create(final XYDataset data){
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Thermometer Reading",
"Time",
"Degrees",
data,
true,
true,
false
);
final XYPlot plot = chart.getXYPlot();
ValueAxis axisy = plot.getDomainAxis();
axisy.setFixedAutoRange(60000.0);
axisy = plot.getRangeAxis();
axisy.setRange(10.0,50.0);
return chart;
}
public void actionPerformed(final ActionEvent e) {
if (e.getActionCommand().equals("C")) {
degreeC.setText("degrees C");
}
if (e.getActionCommand().equals("F")){
degreeC.setText("degrees F");
}
if (e.getActionCommand().equals("off")){
}
}
public static void main(String[] args) throws IOException{
gen myGen = new gen();
new Thread(myGen).start();
final Therm prog = new Therm("Thermometer Graph");
prog.pack();
prog.setVisible(true);
}
static class gen implements Runnable{
public void run() {
while(true) {
int num = 25 + (int)(Math.random() * ((40 - 30) + 1));
System.out.println(num);
ts.addOrUpdate(new Millisecond(), num);
System.out.println("HI");
try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
}
EDIT: here is the new code that receives the error ""syntax error, insert "Classbody" to complete Class Declaration"" at 'gen'
static class gen{
while(true) {
// don't forget to make num final!
final int num = 25 + (int)(Math.random() * ((40 - 30) + 1));
System.out.println(num);
SwingUtilities.invokeLater(new Runnable(){
public void run() {
ts.addOrUpdate(new Millisecond(), num);
}
});
// ts.addOrUpdate(new Millisecond(), num);
System.out.println("HI");
try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
The TimeSeries is a Swing GUI model and probably should only be updated on the Swing event thread.
What happens if you add the update to the event queue like so:
while(true) {
// don't forget to make num final!
final int num = 25 + (int)(Math.random() * ((40 - 30) + 1));
System.out.println(num);
SwingUtilities.invokeLater(new Runnable(){
public void run() {
ts.addOrUpdate(new Millisecond(), num);
}
});
// ts.addOrUpdate(new Millisecond(), num);
System.out.println("HI");
try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
If this doesn't help, please print the entire stacktrace of your exception and indicate any lines in your class that the stacktrace refers to.

Categories