| |||||||||||
| |||||||||||
Generalised Graphing Applet
Archived examples from previous versions of courses example from a Well House Consultants training course
More on Archived examples from previous versions of courses [link]
![]() Source code: waxwing.java Module: J610
// --- ARCHIVED EXAMPLE (may not be current) ---
// --- See notes at http://www.wellho.net/mouth/2654.html --- // // Well House Consultants, 2002. /** General Graphing Applet */ /* Also to run standalone! */ /* With Command Line Arguments */ import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.*; import java.net.*; import java.io.*; public class waxwing extends java.applet.Applet { // Data related - fixed across applets static int value_count; static int highest; static int [] income; static String title="Java Training!"; static int start_year=1998; static int happenings = 0; static Hashtable happen_text; // To share across instances to allow consistency static Font large_font, medium_font, small_font; static Font label_font; static FontMetrics label_metrics; // Applet instance specific static int window_width = 0; static int window_height = 0; // Position for labelling box; static int value_upper_x; static int value_lower_y; static int value_upper_y; static int value_lower_x; // static long timer = 200; static boolean showval = false; static boolean needbuttons = true; static boolean fastrepaint = false; static boolean havebuttons = false; static Button [] buttons; // static boolean isapplet = true; static String [] command_line_parameters ; // ConfirmDialog yesno; // Vector remote_params; // public int year_of_interest = -1; // static PopupMenu popmenu; static int graphmode = 0; static int spotsize; String imagename = "waxwing.gif"; boolean haveimage = false; Image image; int image_height = 0, image_width = 0; ////////////////////////////////////////////////////////////////////////// // main method for standalone operation ////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { isapplet = false; command_line_parameters = args; Frame area = new Frame("waxwing stand alone application"); Applet direct = new waxwing(); area.add(direct,"Center"); direct.init(); area.setSize(800,600); area.show(); } ////////////////////////////////////////////////////////////////////////// // Extended / Replaced methods ////////////////////////////////////////////////////////////////////////// public void init() { // Values to Graph Vector income_build = new Vector(); String remote_data,passed_in; remote_params = new Vector(); // if a URL is given, graph the data from *there* instead! if (isapplet) { remote_data = this.getParameter("url"); } else { remote_data = getCLine("url"); } if (remote_data != null) { URL data_source; URLConnection data_connect; InputStream param_stream; InputStreamReader params; BufferedReader liner; try { data_source = new URL(remote_data); data_connect = data_source.openConnection(); param_stream = data_connect.getInputStream(); params = new InputStreamReader(param_stream); liner = new BufferedReader(params); String collect; while ((collect=liner.readLine()) != null) remote_params.addElement(collect); } catch (Exception e) { System.err.println(e); } } // Data is [now] from command line or applet parameters if (isapplet && remote_data == null) { passed_in = this.getParameter("values"); } else { passed_in = getCLine("values"); } if (passed_in == null) passed_in = "1,2,4,8,16"; StringTokenizer values_in = new StringTokenizer(passed_in,","); while (values_in.hasMoreTokens()) { Integer next_value = Integer.valueOf(values_in.nextToken().trim()); income_build.addElement(next_value); } income = new int [income_build.size()]; for (int k=0;k<income_build.size();k++) { income[k] = ((Integer)income_build.elementAt(k)).intValue(); } // What parameters *are* available?? // getParameterInfo // Title if (isapplet && remote_data == null) { title = this.getParameter("title"); } else { title = getCLine("title"); } if (title == null) title = "Title not supplied"; // Base Scale if (isapplet && remote_data == null) { start_year = (Integer.valueOf(this.getParameter("base"))).intValue(); } else { String starter = getCLine("base"); if (starter == null) starter = "1998"; start_year = (Integer.valueOf(starter)).intValue(); } // Happenings String happen=null, year=null; happen_text = new Hashtable(); for (int k=start_year;k<start_year+income.length+1;k++) { if (isapplet && remote_data == null) { happen = this.getParameter(year=String.valueOf(k)); } else { happen = getCLine(year=String.valueOf(k)); } if (happen != null) { happenings++; happen_text.put(year,happen); } } // Other initialisations large_font = new Font("TimesRoman",Font.BOLD,36); medium_font = new Font("TimesRoman",Font.ITALIC,18); small_font = new Font("TimesRoman",Font.PLAIN,9); } ////////////////////////////////////////////////////////////////////////// private String getCLine(String wanted) { int k; if (remote_params.size() == 0) { // Look for stand alone "-param" style for (k=0;k<(command_line_parameters.length)-1;k++) { if (command_line_parameters[k].equals("-"+wanted)) return command_line_parameters[k+1]; } // look for "param=" style for (k=0;k<command_line_parameters.length;k++) { if (command_line_parameters[k].startsWith(wanted+"=")) return command_line_parameters[k].substring(wanted.length()+1); } // Look in vector of remote parameters } else { for (k=0;k<remote_params.size();k++) { if (((String)remote_params.elementAt(k)).startsWith(wanted+" ")) return ((String)remote_params.elementAt(k)).substring(wanted.length()+1); } } return null; } ////////////////////////////////////////////////////////////////////////// public void start() { } ////////////////////////////////////////////////////////////////////////// public void paint(Graphics mycanvas) { mycanvas.setColor(Color.blue); int old_width = window_width; int old_height = window_height; // window_width = getSize().width-1; // Java 1.1 // window_height = getSize().height-1; window_width = size().width-1; // Java 1.0 window_height = size().height-21; if (old_width > 0 && old_width != window_width) needbuttons = true; if (old_height > 0 && old_height != window_height) needbuttons = true; spotsize = (window_width-100)/income.length-2; if (spotsize < 3) spotsize = 3; if (spotsize > 15) spotsize = 15; if (needbuttons) { this.setLayout(null); if (havebuttons) removeAll(); String [] button_text = {"Rerun","Toggle Speed","Toggle Reporting","Style"}; String [] full_text = {"Rerun","Toggle Speed","Toggle Reporting", "Style","Quit"}; if (! isapplet) button_text = full_text; buttons = new Button [button_text.length]; for (int k=0;k<button_text.length;k++) { buttons[k] = new Button(button_text[k]); } for (int k=0;k<buttons.length;k++) { buttons[k].setBounds(k*window_width/buttons.length, window_height, window_width/buttons.length, 20); add(buttons[k]); } needbuttons = false; havebuttons = true; // Popup popmenu = new PopupMenu("Look"); SetUpMenu(popmenu, new String [] {"Bar Chart","Line Graph","Spot Plot","Imagine"}, new String [] {"bar","line","spot","image"}); this.add(popmenu); } Font headline_font; if (window_width > 500 && window_height > 400) { headline_font = large_font; label_font = medium_font; } else { headline_font = medium_font; label_font = small_font; } FontMetrics headline_metrics = getFontMetrics(headline_font); label_metrics = getFontMetrics(label_font); mycanvas.fillRect(0,0,window_width,window_height); highest = income[0]; for (int k=1;k<income.length;k++) if (highest < income[k]) highest = income[k]; value_count = income.length; mycanvas.setColor(Color.red); int xstep = getAxisStep(income.length); int ystep = getAxisStep(highest); grid(mycanvas,xstep,ystep); mycanvas.setColor(Color.yellow); int textpos = toXPixel(income.length/2) - headline_metrics.stringWidth(title) / 2 ; int text_y; if (textpos < 60) { textpos = toXPixel(income.length/2) - label_metrics.stringWidth(title) / 2 ; mycanvas.setFont(label_font); text_y = label_metrics.getAscent()+5; } else { mycanvas.setFont(headline_font); text_y = headline_metrics.getAscent()+5; } mycanvas.drawString(title, textpos, text_y); value_upper_x = window_width -20; value_lower_y = text_y+20; mycanvas.setFont(label_font); for (int k=0; k<=income.length;k+=(2*xstep)) { String year = String.valueOf(k+start_year); int xfrom = toXPixel(k)-label_metrics.stringWidth(year)/2; int yfrom = toYPixel(0)+label_metrics.getAscent()+1; mycanvas.drawString(year,xfrom,yfrom); } for (int k=0; k<=highest;k+=(2*ystep)) { String level = String.valueOf(k); textpos = toXPixel(0)-5-label_metrics.stringWidth(level); int yfrom = toYPixel(k); mycanvas.drawString(level,textpos,yfrom); } int haps = 1, hapstep = (window_height/2 - text_y - 10) / (happenings+1) ; int oldxfrom=0,oldyfrom=0; for (int k=0;k<income.length;k++) { int xfrom = toXPixel(k); int xto = toXPixel(k+1); int yto = toYPixel(0); int yfrom = toYPixel(income[k]); // Was this an event year? String year; Color behind; String report = (String) happen_text.get((year=String.valueOf(k+start_year))); if (report == null) { mycanvas.setColor(Color.white); behind = Color.white; } else { int xbase, ybase; mycanvas.setColor(Color.yellow); behind = Color.green; mycanvas.drawString(year + " - " + report,xbase=5+haps*hapstep, ybase=haps*hapstep+text_y); mycanvas.setColor(Color.green); mycanvas.drawLine(xbase+hapstep/2,ybase+4,xbase+hapstep/2, window_height/2-10); mycanvas.drawLine(xbase+hapstep/2, window_height/2-10, (xfrom+xto)/2,yto); if (graphmode>0) mycanvas.drawLine((xfrom+xto)/2,yfrom, (xfrom+xto)/2,yto); haps++; } if (graphmode == 0) mycanvas.fillRect(xfrom,yfrom,xto-xfrom,yto-yfrom); if (graphmode == 2) mycanvas.fillOval((xfrom+xto-spotsize)/2, yfrom-spotsize/2,spotsize,spotsize); if (graphmode == 1) { mycanvas.setColor(Color.white); if (k>0) mycanvas.drawLine(oldxfrom,oldyfrom, (xfrom+xto)/2,yfrom); oldxfrom=(xfrom+xto)/2; oldyfrom=yfrom; } if (graphmode == 3) { if (!haveimage) { if (isapplet) { image = this.getImage(this.getDocumentBase(),imagename); } else { image = Toolkit.getDefaultToolkit().getImage(imagename); } } haveimage=true; image_height = image.getHeight(this); image_width = image.getWidth(this); /* mycanvas.drawImage(image,xfrom,yfrom,xto-xfrom,yto-yfrom, this); */ int sector_left = k*image_width/income.length; int sector_right = (k+1)*image_width/income.length; int sector_top = (highest-income[k]) *image_height/highest; int sector_base = image_height; mycanvas.drawImage(image,xfrom,yfrom,xto,yto, sector_left,sector_top,sector_right,sector_base, behind,this); } if (!fastrepaint){ if (showval) pound_box(mycanvas,k); try { Thread.sleep(timer); } catch (InterruptedException fred) {k=income.length;} } } if (showval && (! fastrepaint)) pound_box(mycanvas,-1); fastrepaint = true; } ////////////////////////////////////////////////////////////////////////// protected static void SetUpMenu(Menu popmenu,String [] text, String [] responses){ for (int k=0;k<text.length;k++) { MenuItem box = new MenuItem(text[k]); box.setActionCommand(responses[k]); popmenu.add(box); } } ////////////////////////////////////////////////////////////////////////// public boolean mouseDown(Event selection,int xlocn, int ylocn) { int requested = fromXPixel(xlocn); Graphics addon = getGraphics(); pound_box(addon,requested); year_of_interest = (requested<0)?0:requested+start_year; return true; } ////////////////////////////////////////////////////////////////////////// static void pound_box(Graphics addon, int requested) { if (requested < 0 || requested >= income.length) { addon.setColor(Color.blue); addon.fillRect(value_lower_x-2,value_lower_y-2, value_upper_x-value_lower_x+4, value_upper_y-value_lower_y+4); } else { String Line1 = "Value for "+(requested+start_year); String Line2 = "\u00a3"+income[requested]; addon.setColor(Color.red); value_lower_x = value_upper_x -label_metrics.stringWidth(Line1)-40; value_upper_y = value_lower_y +40+2*label_metrics.getHeight()+ label_metrics.getLeading(); addon.fillRoundRect(value_lower_x,value_lower_y, value_upper_x-value_lower_x, value_upper_y-value_lower_y,10,10); addon.setColor(Color.white); addon.fillRoundRect(value_lower_x+5,value_lower_y+5, value_upper_x-value_lower_x-10, value_upper_y-value_lower_y-10,10,10); addon.setColor(Color.black); addon.setFont(label_font); addon.drawString(Line1, value_lower_x+20 , value_upper_y -20 - label_metrics.getHeight()-label_metrics.getLeading()); int midpoint = (value_lower_x + value_upper_x ) / 2 - label_metrics.stringWidth(Line2) / 2; addon.drawString(Line2, midpoint , value_upper_y -20); } } ////////////////////////////////////////////////////////////////////////// public boolean action(Event what, Object pressed) { if (pressed.equals("Rerun")) { fastrepaint = false; repaint(); } if (pressed.equals("Toggle Speed")) timer = 1000 - timer; if (pressed.equals("Toggle Reporting")) showval = ! showval; if (pressed.equals("Style")) { popmenu.show(buttons[3],70,-50); } if (pressed.equals("Quit")) { Frame confirm = new Frame("Quit requested"); confirm.setSize(250,150); // confirm.show(); yesno = new ConfirmDialog(confirm, "Quit Requested", "I have finished","don't quit"); yesno.show(); } // Following (I think!) redundant if (pressed.equals("yes")) System.exit(0); if (pressed.equals("no")) yesno.hide(); // And following is NOT redundant. if (pressed.equals("Bar Chart")) graphmode=0; if (pressed.equals("Line Graph")) graphmode=1; if (pressed.equals("Spot Plot")) graphmode=2; if (pressed.equals("Imagine")) graphmode=3; return true; } ////////////////////////////////////////////////////////////////////////// // I feel an object coming on here! private static int getAxisStep(int range) { int stepsize, step = 0, power = 1; int [] nice_steps = {1,2,5} ; while (range/(stepsize=(nice_steps[step%nice_steps.length]*power)) > 15) if (++step%nice_steps.length == 0) power *=10; return stepsize; } ////////////////////////////////////////////////////////////////////////// private static void grid(Graphics graph_area,int xsep, int ysep) { int y1 = toYPixel(0); int y2 = toYPixel(highest); for (int k=0;k<value_count;k+=xsep) { int xval = toXPixel(k); graph_area.drawLine(xval,y1,xval,y2); } int x1 = toXPixel(0); int x2 = toXPixel(value_count); for (int k=0;k<highest;k+=ysep) { int yval = toYPixel(k); graph_area.drawLine(x1,yval,x2,yval); } graph_area.drawRect(x1,y2,x2-x1,y1-y2); } ////////////////////////////////////////////////////////////////////////// private static int toXPixel (int value) { // Allow 80 pixels to left for labelling return value*(window_width-100)/value_count+80; } ////////////////////////////////////////////////////////////////////////// private static int fromXPixel (int value) { // Allow 80 pixels to left for labelling // return value*(window_width-100)/value_count+80; if (value < 80) return (-1); return (value-80)*value_count/(window_width-100); } ////////////////////////////////////////////////////////////////////////// private static int toYPixel (int value) { // bottom half of window, allowing 40 pixels for title return window_height - value*(window_height-40)/highest/2 - 20; } ////////////////////////////////////////////////////////////////////////// public void stop() { } ////////////////////////////////////////////////////////////////////////// public void destroy () { } } Learn about this subject
This module and example are covered on our public Java Extra course. If you have a group of
three or more trainees who need to learn the subject, we can also arrange a
private or on site course for you.
Books covering this topic
Yes. We have over 700 books in our library. Books
covering Java and associated technologies are listed here and when you've selected a
relevant book we'll link you on to Amazon to order.
Other Examples
This example comes from our "Archived examples from previous versions of courses" training module. You'll find a description of the topic and some
other closely related examples on the "Archived examples from previous versions of courses" module index page.
Full description of the source code
You can learn more about this example on the training courses listed on this page,
on which you'll be given a full set of training notes.
Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License. Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre. • The Horse's mouth provides a daily tip or thought. • Further resources are available via the resources centre. • All of these resources can be searched through through our search engine • And there's a global index here. Purpose of this website
This is a sample program, class demonstration or answer from a
training course. It's main purpose
is to provide an after-course service to customers who have attended our
public private or
on site courses, but the examples are made
generally available under conditions described below.
Web site author
Conditions of use
Past attendees on our training courses are welcome to use individual
examples in the course of their programming, but must check
the examples they use to ensure that they are suitable for their
job. Remember that some of our examples show you how not to do
things - check in your notes. Well House Consultants take no responsibility
for the suitability of these example programs to customer's needs.
This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details. Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request. |
| ||||||||||
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho PAGE: http://www.wellho.net/resources/ex.php4 • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb |