Trying to make a constantly running line graph - java

I have a program that is operating fine which repeats a series of formulas using different values for independent variables. I now want to make a plot of the calculations after every iteration of the loop. This is what I have so far:
public static void main(String[] args) {
JFrame window=new JFrame();
window.setTitle("Try");
window.setSize(600, 400);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
XYSeries series = new XYSeries("graph");
XYSeriesCollection dataset= new XYSeriesCollection(series);
...
My big questions are how do I take my data and generate a dataset, and then how do I make the graph update after every iteration of the loop? I have imported the JFreeChart class and some swing. Any and all insight would be greatly appreciated.

So I figured this out after some time. The trick is to set visible inside of the loop. But now, the JFrame redraws with every iteration. I don't know if there is a way to hold the frame constant. If anyone does know, I would appreciate the help.
package trylog{
import javax.swing.JFrame;
import java.awt.BorderLayout;
java.util.List;
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.ValueAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.data.general.DatasetGroup;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import sun.security.jca.GetInstance.Instance;
public class TryLog {
private static Object InstanceTools;
public static void main(String[] args) {
JFrame window=new JFrame();
window.setTitle("Try");
window.setSize(600, 400);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//window.setVisible(true);
XYSeries series = new XYSeries("graph");
XYSeriesCollection dataset= new XYSeriesCollection(series);
double[] newArray= new double[1000];
for (int j=0;j<1000;j++)
{
newArray[j]=1+10;
}
JFreeChart chart=ChartFactory.createXYLineChart("Graph Try", "hi", "bye", dataset);
window.add(new ChartPanel(chart),BorderLayout.CENTER);
int x=0;
int number=10;
JFrame window1=new JFrame();
window1.setTitle("Try");
window1.setSize(600, 400);
window1.setLayout(new BorderLayout());
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//window.setVisible(true);
XYSeries series1 = new XYSeries("graph");
XYSeriesCollection dataset1= new XYSeriesCollection(series1);
double[] newArray1= new double[1000];
for (int j=0;j<1000;j++)
{
newArray[j]=1+10;
}
JFreeChart chart1=ChartFactory.createXYLineChart("Graph Try", "hi", "bye", dataset1);
window1.add(new ChartPanel(chart1),BorderLayout.CENTER);
int y=0;
int number1=10;
for (int i=0;i<10000;i++)
{
series.add(x,number);
x++;
number++;
window.setVisible(true);
series1.add(y,number1);
y++;
number1++;
window1.setVisible(true);
}
}

Related

I used canvas to create a graphing utility. Is there any way I can also incorporate JButtons, JTextFields etc

I created a graphing utility using canvas. Currently, information is inputted through the console. However, I want to make the program more presentable by adding inputs via JTextField and JButtons. Is there any way I can do that?
something like this:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFrameWithCanvas extends JFrame {
private Canvas canvas = new Canvas();
public JFrameWithCanvas() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pnlToolbar = new JPanel();
pnlToolbar.add(new JTextField(10));
pnlToolbar.add(new JButton("foo"));
getContentPane().add(pnlToolbar, BorderLayout.PAGE_START);
canvas.setBackground(Color.MAGENTA);
getContentPane().add(canvas, BorderLayout.CENTER);
canvas.setPreferredSize(new Dimension(300, 300));
pack();
setLocationRelativeTo(null); // center it on the screen
}
public static void main(String[] args) {
new JFrameWithCanvas().setVisible(true);
}
}

I added a gif to my JLabel but it only plays once and doesn't continue, how do i fix it?

JLabel two = new JLabel();
ImageIcon jaina= new ImageIcon("images/jaina.gif");
two.setBounds(0,0,300,300);
two.setIcon(jaina);
then i added the Label to my panel, it plays only once
If your gif is not set to loop, the correct solution is to modify the gif to have it loop.
Out of curiosity I mocked up this example. What if I want to animate a gif independent of its animation settings.
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.EventQueue;
public class GifLabel{
public static void startGui( List<ImageIcon> imgs){
JFrame frame = new JFrame("animated gif");
JLabel label = new JLabel( );
frame.add(label);
label.setIcon(imgs.get(0));
Timer t = new Timer( 30, new ActionListener(){
int i = 0;
#Override
public void actionPerformed( ActionEvent evt ){
label.setIcon ( imgs.get(i) );
i = (i+1)%imgs.size();
}
});
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
t.start();
}
public static void main(String[] args) throws Exception{
ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
reader.setInput( new FileImageInputStream( new File("images/jaina.gif")));
int n = reader.getNumImages( true );
List<ImageIcon> imgs = new ArrayList<>();
for(int i = 0; i<n; i++){
imgs.add( new ImageIcon(reader.read(i)) );
}
EventQueue.invokeLater( ()->{
startGui(imgs);
});
}
}
This is way more fragile than just making sure the GIF is the correct format. Also way more code, considering the original new ImageIcon("..."); handles everything.

How to change the side range value colors in thermometer in JFreeChart

I found a thermometer demo and customized it for my dashboard project. http://www.java2s.com/Code/Java/Chart/JFreeChartThermometerDemo2.htm
In my dashboard I have six thermometer with different Mercury Color. However, I cannot seem to find a way to change the color of the range numbers that are displayed beside the thermometer.
How do I change the range number text color from Black to White?
My Demo Thermometer screenshot
package Thermometers;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.data.general.DefaultValueDataset;
import App.App_v2;
public class ThermometerDemo2 extends JPanel
{
private static final long serialVersionUID = 1L;
public ThermometerDemo2(Color color, double maxValue)
{
// create a dataset...
final DefaultValueDataset dataset = new DefaultValueDataset(110);
// create the chart...
final ThermometerPlot plot = new ThermometerPlot(dataset);
plot.setRange(0.0, maxValue);
plot.setSubrange(ThermometerPlot.CRITICAL, 250, 300);
plot.setValueFont(new Font("Georgia", Font.BOLD, 32));
plot.setThermometerStroke(new BasicStroke(2.0f));
plot.setBackgroundPaint(new Color(20,42,60));
plot.setMercuryPaint(color);
final JFreeChart chart = new JFreeChart(plot);
chart.setBorderVisible(false);
// add the chart to a panel...
ChartPanel chartPanel = new ChartPanel(chart);
this.add(chartPanel);
this.setBackground(new Color(20,42,60));
}
public static void main(final String[] args) {
JFrame frame = new JFrame("change the black range color into white");
frame.setVisible(true);
frame.setSize(500, 500);
ThermometerDemo2 demo = new ThermometerDemo2(Color.magenta, 300);
demo.setVisible(true);
frame.add(demo);
frame.pack();
}
}

Time series chart, X axis tick labels turning into

I am using JFreeChart to make a barchart vs time. For some reason on these charts, the tick labels on the x axis turn into "..." occasionally. There seems like there is plenty of room for the labels to expand, but instead it just cuts off the whole thing. How can I fix this.
I tried uploading a picture using the image button, but it does not seem to be working.
Here is code with a similar set up to my project. Strangely it acted different then what is happening to my build. On mine instead of saying "Hou...", it just says "...". Ignore comments and all other uneeded things please.
package dataDisplay;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
public class mockTest extends JPanel{
ChartPanel chartPanel;
JFreeChart chart;
CategoryAxis domainAxis;
NumberAxis rangeAxis;
public mockTest()
{
//Mock data
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
int[] times = new int[]{1,2,3,4,5,6,7,8,9,10,11,12};
for ( int i = 0; i < times.length; i++ ){
dataset.addValue(times[i], "Time", "Houreee" + String.valueOf(i+1));;
}
CategoryPlot plot = new CategoryPlot();
//create the plot
//add the first dataset, and render as bar values
CategoryItemRenderer renderer = new BarRenderer();
plot.setDataset(0,dataset);
plot.setRenderer(0,renderer);
//set axis
domainAxis = new CategoryAxis("Time");
rangeAxis = new NumberAxis("Value");
plot.setDomainAxis(0,domainAxis);
plot.setRangeAxis(rangeAxis);
chart = new JFreeChart(plot);
chartPanel = new ChartPanel( chart );
this.addComponentListener(new ComponentAdapter() {
#Override
/**
* Makes it so it does not stretch out text. Resizes the fonts to scale with the screen width..
*/
public void componentResized(ComponentEvent e) {
chartPanel.setMaximumDrawHeight(e.getComponent().getHeight());
chartPanel.setMaximumDrawWidth(e.getComponent().getWidth());
chartPanel.setMinimumDrawWidth(e.getComponent().getWidth());
chartPanel.setMinimumDrawHeight(e.getComponent().getHeight());
// Makes the font size scale according to the width of the chart panel.
rangeAxis.setLabelFont(new Font("SansSerif", Font.PLAIN,e.getComponent().getWidth()/60));
domainAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN,e.getComponent().getWidth()/80));
rangeAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN,e.getComponent().getWidth()/75));
}
});
this.add(chartPanel, "Center");
}
public static void main (String[] args)
{
// Get the default toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Get the current screen size
Dimension scrnsize = toolkit.getScreenSize();
int scrnWidth= (int)scrnsize.getWidth();
int scrnHeight = (int) scrnsize.getHeight();
JFrame J= new JFrame();
JPanel jP = new JPanel();
J.setContentPane(jP);
J.setSize(scrnWidth, scrnHeight);
jP.setBackground(Color.white);
jP.setBounds(0,0,scrnWidth,scrnHeight);
int xPercent= 50;
int yPercent = 50;
int widthPercent=50;
int heightPercent=43;
jP.setLayout(null);
jP.setSize(scrnWidth, scrnHeight);
mockTest b= new mockTest();
jP.add(b);
b.setBounds(new Rectangle((int)(scrnWidth*((double)xPercent/100)),(int)(scrnHeight*((double)yPercent/100)),(int)(scrnWidth*((double)widthPercent/100)),(int)(scrnHeight*((double)heightPercent/100))));
J.setUndecorated(true);
J.setVisible(true);
}
Don't use a null layout; let the layout manager do the work. The default layout of JPanel is FlowLayout, which ignores your subsequent changes. In the example below,
The chartPanel is given a GridLayout; when added to the enclosing frame's CENTER, the chart will be free to grow as the frame is resized.
Avoid unnecessarily nested panels.
Use setExtendedState() to maximize the frame.
If necessary, use one of the approaches suggested here to alter the chart's initial size.
If you choose to alter a Font, use deriveFont() to avoid abrupt disparities in the user's chosen settings.
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
/** #see https://stackoverflow.com/a/31014252/230513 */
public class Test {
public void display() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < 12; i++) {
dataset.addValue(i, "Time", "Hours" + String.valueOf(i + 1));
}
CategoryPlot plot = new CategoryPlot();
CategoryItemRenderer renderer = new BarRenderer();
plot.setDataset(0, dataset);
plot.setRenderer(0, renderer);
CategoryAxis domainAxis = new CategoryAxis("Time");
NumberAxis rangeAxis = new NumberAxis("Value");
plot.setDomainAxis(0, domainAxis);
plot.setRangeAxis(rangeAxis);
JFreeChart chart = new JFreeChart(plot);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setLayout(new GridLayout());
JFrame f = new JFrame();
f.add(chartPanel);
f.setExtendedState(f.getExtendedState() | JFrame.MAXIMIZED_BOTH);
f.setUndecorated(true);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}

java Swing Application Freezes when call to jpcapCaptor.openDevice method

I am developing some bandwidth utilization monitor tool using jpcap.
what am i doing:-
1. i created a radio buttons panel containing the list of all the network interfaces that is present on system, and user has to choose one of them.
2. a jfreechart panel (dynamic) that will show the real time graph of bandwidth utilization when user clicks GO! button.
problem:-
i have added following in ActionListener in GO! button
try{captor = JpcapCaptor.openDevice(devices[selecteddevice], 65535,true, 20);}catch(Exception e){}
timer.start();
captor.loopPacket(-1,new PacketPrinter());
so when i run the program GUI comes with radiobutton panel and jfreechart panel but when i select an option and press GO! application freezes and chart panel does not show any dynamic updation.
when i commented out the JpcapCaptor.openDevice(devices[selecteddevice], 65535,true, 20);
then when i press GO! button, everything works,for example timer starts and chart panel is being updated.(but as captor is null so it is not capturing any data)
Please Help me!!!
my system is ubuntu 10.04, jpcap 0.7
my code is as follows:-
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import org.jfree.chart.ChartFrame;
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 java.util.List;
import java.util.ArrayList;
import jpcap.*;
import jpcap.packet.*;
import java.util.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
public class Sniffer extends JPanel
{
private static jpcap.NetworkInterface[] devices;
private static int selecteddevice=-1;
JFrame frame;
public static JpcapCaptor captor;
private static final String TITLE="Bandwidth Utilization Meter";;
public static List<Packet> packets;
public static Timer timer;
public static ArrayList<JRadioButton> radioButtonArray = new ArrayList<JRadioButton>();
private ButtonGroup group= new ButtonGroup();
public static JButton go;
JFreeChart chart;
static DynamicTimeSeriesCollection dataset;
public Sniffer()
{
packets = new ArrayList<Packet>();
dataset =new DynamicTimeSeriesCollection(1,120, new Second());
dataset.setTimeBase(new Second(0, 0, 0, 2, 1, 2011));
dataset.addSeries(new float[0], 0, "PPP0 Bandwidth Utilization Meter");
chart = createChart(dataset);
getDevices();
timer = new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{ long tlen=0;
List<Packet> temp = new ArrayList<Packet>(packets);
packets.clear();
for(Packet i : temp)
{
tlen+=i.len;
}
float[] newData = new float[1];
newData[0]=(float)tlen/1024;
dataset.advanceTime();
dataset.appendData(newData);
}});
setGUI();
}
void setGUI()
{
setLayout(new BorderLayout());
frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(devices.length, 1));
for (JRadioButton combo : radioButtonArray)
{
panel.add(combo);
}
JScrollPane scrollPane = new JScrollPane(panel);
go= new JButton("GO!");
go.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ee)
{
//problem starts here.............
try{captor = JpcapCaptor.openDevice(devices[selecteddevice], 65535,true, 20);}catch(Exception e){}
timer.start();
captor.loopPacket(-1,new PacketPrinter());
//.....................................
}
}
);
go.setEnabled(false);
panel.add(go);
add(scrollPane, BorderLayout.CENTER);
scrollPane.setSize(300,300);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setLayout(new GridLayout(2, 0));
frame.add(scrollPane);
frame.add(new ChartPanel(chart));
frame.setSize(1024, 768);
frame.setTitle("BW");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void getDevices()
{
devices = JpcapCaptor.getDeviceList();
for(int i=0;i<devices.length;i++)
{
String device=null;
radioButtonArray.add(new JRadioButton());
group.add(radioButtonArray.get(i));
radioButtonArray.get(i).addActionListener(new RadioButtonListener());
device= devices[i].name+" "+"("+devices[i].description+")";
radioButtonArray.get(i).setText(device);
}
}
public static void startSniffing() throws Exception
{
captor = JpcapCaptor.openDevice(devices[selecteddevice], 65535,true, 20);
}
public static void setSelectedDevice(int device)
{
selecteddevice = device;
}
public NetworkInterface getSelectedDevice()
{
if (selecteddevice == -1)
{
return null;
}
else
{
return devices[selecteddevice];
}
}
public static void main(String args[])
{
Sniffer sniffer = new Sniffer();
//sniffer.start();
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart xyz = ChartFactory.createTimeSeriesChart(
TITLE, "Time(Seconds)", "Bandwidth KB/s", dataset, true, true, false);
final XYPlot plot = xyz.getXYPlot();
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
ValueAxis range = plot.getRangeAxis();
range.setRange(0,1000);
return xyz;
}
}
class RadioButtonListener extends JPanel implements ActionListener {
public void actionPerformed(ActionEvent e) {
Sniffer.go.setEnabled(true);
for (JRadioButton radio : Sniffer.radioButtonArray) {
if (radio.isSelected()) {
Sniffer.setSelectedDevice(Sniffer.radioButtonArray.indexOf(radio));
}
}
}
}
class PacketPrinter implements PacketReceiver {
static long tlen;
public void receivePacket(Packet packet) {
Sniffer.packets.add(packet);
}
}
Don't block the EDT. Put the time consuming task in a SwingWorker.

Categories

Resources