Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By Fubarable

Thread: Swing Bar Graph will not display in JPanel

  1. #1
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Swing Bar Graph will not display in JPanel

    Hi all,

    There's a bit of code involved here, so I'll attempt to post only what's relevant to getting some help.

    I'm using a sample Swing Bar Chart class:

    Java Code:
    package PCQ;
    
    
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class SimpleBarChart extends JPanel {
    	  private double[] value;
    	  private String[] names;
    	  private String title;
    
    public SimpleBarChart(double[] val, String[] lang, String t) {
    	  value = val;
    	  names = lang;
    	  title = t;
    }
    public void paintComponent(Graphics graphics) {
    	  super.paintComponent(graphics);
    	  if (value == null || value.length == 0)
    		  return;
    	  double minValue = 0;
    	  double maxValue = 0;
    	  for (int i = 0; i < value.length; i++) {
    		  if (minValue > value[i])
    			  minValue = value[i];
    		  if (maxValue < value[i])
    			  maxValue = value[i];
    	  }
    	  
    Dimension dim = getSize();
    
    int clientWidth = dim.width;
    int clientHeight = dim.height;
    int barWidth = clientWidth / value.length;
    
    Font titleFont = new Font("Book Antiqua", Font.BOLD, 15);
    FontMetrics titleFontMetrics = graphics.getFontMetrics(titleFont);
    Font labelFont = new Font("Book Antiqua", Font.PLAIN, 10);
    FontMetrics labelFontMetrics = graphics.getFontMetrics(labelFont);
    
    int titleWidth = titleFontMetrics.stringWidth(title);
    int q = titleFontMetrics.getAscent();
    int p = (clientWidth - titleWidth) / 2;
    
    graphics.setFont(titleFont);
    graphics.drawString(title, p, q);
    
    int top = titleFontMetrics.getHeight();
    int bottom = labelFontMetrics.getHeight();
    	if (maxValue == minValue)
    		return;
    double scale = (clientHeight - top - bottom) / (maxValue - minValue);
    q = clientHeight - labelFontMetrics.getDescent();
    graphics.setFont(labelFont);
    
    	for (int j = 0; j < value.length; j++) {
    		int valueP = j * barWidth + 1;
    		int valueQ = top;
    		int height = (int) (value[j] * scale);
    			if (value[j] >= 0)
    				valueQ += (int) ((maxValue - value[j]) * scale);
    			else {
    				valueQ += (int) (maxValue * scale);
    				height = -height;
    			}
    			
    graphics.setColor(Color.blue);
    graphics.fillRect(valueP, valueQ, barWidth - 2, height);
    graphics.setColor(Color.black);
    graphics.drawRect(valueP, valueQ, barWidth - 2, height);
    int labelWidth = labelFontMetrics.stringWidth(names[j]);
    p = j * barWidth + (barWidth - labelWidth) / 2;
    graphics.drawString(names[j], p, q);
    	}
    }
    
    public static void main(String[] args) {
    	  JFrame frame = new JFrame();
    	  frame.setSize(350, 300);
    	  double[] value= new double[5];
    	  String[] languages = new String[5];
    	  value[0] = 1;
    	  languages[0] = "Visual Basic";
    
    	  value[1] = 2;
    	  languages[1] = "PHP";
    	
    	  value[2] = 3;
    	  languages[2] = "C++";
    	
    	  value[3] = 4;
    	  languages[3] = "C";
    	
    	  value[4] = 5;
    	  languages[4] = "Java";
    	  frame.getContentPane().add(new SimpleBarChart(value, languages,
    	    "Programming Languages"));
    
    	  WindowListener winListener = new WindowAdapter() {
    		  public void windowClosing(WindowEvent event) {
    			  System.exit(0);
    		  }
    	  	};
    frame.addWindowListener(winListener);
    frame.setVisible(true);
    
    }
    
    }
    I've got a second class to retrieve the values to go into the graph:

    Java Code:
    package PCQ;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Scanner;
    
    import javax.swing.JComboBox;
    
    public class chartData {
    	
    	JComboBox custDrop;	
    	Object[][] rdataA;
    	public Object[] custs;
    	public String[] columns = {"ACTIVE_CURRENT", "ACTIVE_INPROC", "ACTIVE_OD", "NCR", "INACTIVE"," TOTAL", "READINESS %", "OD %"}; 
    	public double[] values;
    
    	
    	public JComboBox getChartData() throws FileNotFoundException{
    		  Scanner scan = new Scanner(new File("C:\\PCQ\\READINESS.csv"));
    		  List<Object[]> rData = new ArrayList<Object[]>(); 
    			  
    		  	while (scan.hasNextLine()  ) {         
    				Object[] line = scan.nextLine().split(","); 	
    			
    					rData.add(new Object[] { 
    							(line[0]),  	//CUSTOMER_ID
    							(line[1]), 	    //UIC  
    							(line[2]),  	//ACC_CD
    							(line[3]),  	//CAT_CD
    							(line[4]),   	//ACTIVE_CUR
    							(line[5]),   	//ACTIVE_INPROC
    							(line[6]),    	//ACTIVE_OD
    							(line[7]),    	//NCR
    							(line[8]),    	//INACTIVE
    							(line[9]),    	//TOTAL
    							(line[10]),   	//READINESS
    							(line[11])  	//OD
    								}
    							); 					
    						}
    			int rows = rData.size();
    			int cols = columns.length;
    	    	rdataA = new Object[rows][12];  
    	    	
    			for (int i = 1; i < rows; i++) {        
    				rdataA[i] = rData.get(i);     
    			}
    				//System.out.println(rows);
    						
    			int ROWS = rdataA.length;
    			int COLS = rdataA[0].length;
    			for (int L = 0; L < ROWS; L++) {
    				for (int M = 0; M < COLS; M++) {
    					//System.out.print(" " + rdataA[L][M]);
    				}
    				//System.out.println("");
    				 }			
    			int rlength = rdataA.length;
    			custs = new Object[rlength];
    			
    			for (int i = 0; i < rlength; i++){
    				custs[i] = rdataA[i][0];
    				//System.out.println(custs[i]);
    			}
    			
    		  custDrop = new JComboBox(custs);
    		  custDrop.insertItemAt("Select A Customer", 0);
    		  custDrop.setSelectedIndex(0);
    		  custDrop.addActionListener(new ActionListener()
    		  	{
    			  public void actionPerformed(ActionEvent e) 
    			  {
    			        JComboBox custDrop = (JComboBox)e.getSource();
    			        String customer = (String)custDrop.getSelectedItem();
    			        values = getRow(customer); //pass in String custs and return row data from rdataA				        
    			  }		    
    			});
    			  
    			  return custDrop;		  
    	  	}
    	  
    	  public double[] getRow(String custs){
    		  
    		  int idx = 0;
    		  int rlen = rdataA.length;
    		  int rcol = rdataA[0].length ;
    		  Object[] row = new Object[rcol];
    		  for(int x = 1; x < rlen; x++){
    			  if(rdataA[x][0] == custs){
    				  for (int j = 0 ; j < rcol ; j++){   
    					  row[j] = rdataA[x][j];  
    		         }
    			  }
    		  }
    		 
    	  	double[] values = new double[8];
    	  	int index = 0;
    	  	for(int i = 4; i < 12; i++){
    	  		Object object = row[i];
    	  		String string = object.toString(); double dub = Double.valueOf(string).doubleValue();
    	  		values[index] = dub;
    	  		++index;
    	  	} 	
    	  	/*
    	  	 System.out.println(rcol); 			  	 
    		 System.out.println(Arrays.toString(row));
    		 System.out.println(Arrays.toString(values));
    		*/
    		return values;
    	  }
    
    }
    In my gui class I'm trying to implement the SampleBarChart class, passing values in using the chartData class, and displaying the chart.

    Java Code:
    	JPanel metR = new JPanel(new GridBagLayout());
    	chartData cd = new chartData();
    	JComboBox drop = cd.getChartData(); //need: a JComboBox filled with Customers from an Object[][]
    	value = cd.values;
    	String[] names = {"ACTIVE_CURRENT", "ACTIVE_INPROC", "ACTIVE_OD", "NCR", "INACTIVE"," TOTAL", "READINESS %", "OD %"}; 
    	String title = "test";
    	SimpleBarChart bc = new SimpleBarChart(value, names, title);
        GridBagConstraints e = new GridBagConstraints();
        e.gridx = 0; e.gridy = 0; metR.add(drop, e);
        e.gridx = 1; e.gridy = 0; metR.add(bc, e);
        //bc.setPreferredSize(new Dimension(990, 380));
    
    	tb.add(metR, "Fleet Analysis");
    When I add the SampleBarChart sb object to the JPanel in the gui class, it doesn't show up at all. Is the main method within the SampleBarChart class getting in the way? I know this is a bit of code to look at, but I'm absolutely struggling and would really appreciate a push in the right direction. Where am I going wrong??

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Swing Bar Graph will not display in JPanel

    The SimpleBarChart's main method won't "get in the way" if you don't explicitly call it. Something else is wrong, and you will need to do some debugging first before you or we have a chance of solving this. So put on your debugging hat, start peppering your code with println statements that check to see the size of components and the value of variables, and do some digging.
    DarrylBurke likes this.

  3. #3
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: Swing Bar Graph will not display in JPanel

    I've created the below more succinct version, added lots of println statements to check my work, and the graph still wont show up. Any chance of getting some more detailed assistance?

    Java Code:
    package graph;
    
    import java.awt.Container;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Scanner;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class gtest extends JPanel {
    	private double[] value;
    	
    	public static void main(String[] args) throws FileNotFoundException {
    		gtest app = new gtest();
    		app.build();
    
    	}
    	Object[][] rdataA;
    	private void build() throws FileNotFoundException {
    		
    		  JFrame frame = new JFrame("PCQ 0.1 Beta"); 		
    		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 		
    		  final JPanel panel = new JPanel();
    		  
    		  String[] languages;
    		  Object[] custs;
    		  final String title = "test";
    		  final String[] columns = {"ACTIVE_CURRENT", "ACTIVE_INPROC", "ACTIVE_OD", "NCR", "INACTIVE"," TOTAL", "READINESS %", "OD %"};
    		  
    		  Scanner scan = new Scanner(new File("C:\\PCQ\\READINESS.csv"));
    		  List<Object[]> rData = new ArrayList<Object[]>(); 
    		  while (scan.hasNextLine()  ) {         
    				Object[] line = scan.nextLine().split(","); 	
    			
    					rData.add(new Object[] { 
    							(line[0]),  	//CUSTOMER_ID
    							(line[1]), 	    //UIC  
    							(line[2]),  	//ACC_CD
    							(line[3]),  	//CAT_CD
    							(line[4]),   	//ACTIVE_CUR
    							(line[5]),   	//ACTIVE_INPROC
    							(line[6]),    	//ACTIVE_OD
    							(line[7]),    	//NCR
    							(line[8]),    	//INACTIVE
    							(line[9]),    	//TOTAL
    							(line[10]),   	//READINESS
    							(line[11])  	//OD
    								}
    							); 					
    						}
    			int rows = rData.size();
    			int cols = columns.length;
    	    	rdataA = new Object[rows][12];  
    	    	
    			for (int i = 1; i < rows; i++) {        
    				rdataA[i] = rData.get(i);     
    			}
    			int ROWS = rdataA.length;
    			int COLS = rdataA[0].length;
    			for (int L = 0; L < ROWS; L++) {
    				for (int M = 0; M < COLS; M++) {
    					System.out.print(" " + rdataA[L][M]);
    				}
    				System.out.println("");
    				 }			
    			int rlength = rdataA.length;
    			custs = new Object[rlength];
    			
    			for (int i = 0; i < rlength; i++){
    				custs[i] = rdataA[i][0];
    				System.out.println(custs[i]);
    			}
    			
    			
    		
    		  final JComboBox custdrop = new JComboBox(custs);
    		  custdrop.setSelectedIndex(1);
    		  
    			custdrop.addItemListener(new ItemListener(){
    				@Override
    				public void itemStateChanged(ItemEvent e) {
    					Object customer = (String)custdrop.getSelectedItem();
    					 value = getRow(customer);
    					System.out.println(customer);
    				repaint();
    				}
    				  });	  
    				
    		SimpleBarChart sb = new SimpleBarChart(value, columns, title);
    
    		panel.add(sb);
    		panel.add(custdrop);
    		frame.add(panel);
    		frame.setSize(1100, 610); 
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
    	
    	}
    	
    	  public double[] getRow(Object customer){
    		  
    		  int idx = 0;	
    		  int rlen = rdataA.length;
    		  int rcol = rdataA[0].length ;
    		  Object[] row = new Object[rcol];
    		  for(int x = 1; x < rlen; x++){
    			  if(rdataA[x][0] == customer){
    				  for (int j = 0 ; j < rcol ; j++){   
    					  row[j] = rdataA[x][j];  
    		         }
    			  }
    		  }
    		 
    	  	double[] values = new double[8];
    	  	int index = 0;
    	  	for(int i = 4; i < 12; i++){
    	  		Object object = row[i];
    	  		String string = object.toString(); double dub = Double.valueOf(string).doubleValue();
    	  		values[index] = dub;
    	  		++index;
    	  	} 	
    	  	
    	  	 //System.out.println(rcol); 			  	 
    		 System.out.println(Arrays.toString(row));
    		 System.out.println(Arrays.toString(values));
    		
    		return values;
    	  }
    	  
    	  
    
    }
    Java Code:
    
    package graph;
    
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
      public class SimpleBarChart extends JPanel {
    	  private double[] value;
    	  private String[] languages;
    	  private String title;
    
      public SimpleBarChart(double[] val, String[] lang, String t) {
    	  value = val;
    	  languages = lang;
    	  title = t;
      }
      public void paintComponent(Graphics graphics) {
    	  super.paintComponent(graphics);
    	  if (value == null || value.length == 0)
    		  return;
    	  double minValue = 0;
    	  double maxValue = 0;
    	  for (int i = 0; i < value.length; i++) {
    		  if (minValue > value[i])
    			  minValue = value[i];
    		  if (maxValue < value[i])
    			  maxValue = value[i];
    	  }
    	  
      Dimension dim = getSize();
      
      int clientWidth = dim.width;
      int clientHeight = dim.height;
      int barWidth = clientWidth / value.length;
      
      Font titleFont = new Font("Book Antiqua", Font.BOLD, 15);
      FontMetrics titleFontMetrics = graphics.getFontMetrics(titleFont);
      Font labelFont = new Font("Book Antiqua", Font.PLAIN, 10);
      FontMetrics labelFontMetrics = graphics.getFontMetrics(labelFont);
      
      int titleWidth = titleFontMetrics.stringWidth(title);
      int q = titleFontMetrics.getAscent();
      int p = (clientWidth - titleWidth) / 2;
      
      graphics.setFont(titleFont);
      graphics.drawString(title, p, q);
      
      int top = titleFontMetrics.getHeight();
      int bottom = labelFontMetrics.getHeight();
      	if (maxValue == minValue)
      		return;
      double scale = (clientHeight - top - bottom) / (maxValue - minValue);
      q = clientHeight - labelFontMetrics.getDescent();
      graphics.setFont(labelFont);
      
      	for (int j = 0; j < value.length; j++) {
      		int valueP = j * barWidth + 1;
      		int valueQ = top;
      		int height = (int) (value[j] * scale);
      			if (value[j] >= 0)
      				valueQ += (int) ((maxValue - value[j]) * scale);
      			else {
      				valueQ += (int) (maxValue * scale);
      				height = -height;
      			}
      			
      graphics.setColor(Color.blue);
      graphics.fillRect(valueP, valueQ, barWidth - 2, height);
      graphics.setColor(Color.black);
      graphics.drawRect(valueP, valueQ, barWidth - 2, height);
      int labelWidth = labelFontMetrics.stringWidth(languages[j]);
      p = j * barWidth + (barWidth - labelWidth) / 2;
      graphics.drawString(languages[j], p, q);
      	}
      }
     
      public static void main(String[] args) {
    	  JFrame frame = new JFrame();
    	  frame.setSize(350, 300);
    	  double[] value= new double[5];
    	  String[] languages = new String[5];
    	  value[0] = 1;
    	  languages[0] = "Visual Basic";
    
    	  value[1] = 2;
    	  languages[1] = "PHP";
    	
    	  value[2] = 3;
    	  languages[2] = "C++";
    	
    	  value[3] = 4;
    	  languages[3] = "C";
    	
    	  value[4] = 5;
    	  languages[4] = "Java";
    	  frame.getContentPane().add(new SimpleBarChart(value, languages,
    	    "Programming Languages"));
    
    	  WindowListener winListener = new WindowAdapter() {
    		  public void windowClosing(WindowEvent event) {
    			  System.exit(0);
    		  }
    	  	};
      frame.addWindowListener(winListener);
      frame.setVisible(true);
      frame.setLocationRelativeTo(null);
      
      }
    }
    Last edited by Redefine12; 04-30-2012 at 11:22 PM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Swing Bar Graph will not display in JPanel

    Quote Originally Posted by Redefine12 View Post
    I've created the below more succinct version, added lots of println statements to check my work, and the graph still wont show up. Any chance of getting some more detailed assistance?
    First you might want to tell us more:

    • You have two classes posted above, both with main methods. What are both/either one supposed to do?
    • What are they not doing that they should be doing?
    • What are they doing that they shouldn't be doing?
    • A true SSCCE should run for us unmodified and require no outside code, libraries or files. You first class doesn't fulfill this criteria, and so if we can't run it and test it, we can't help you. Consider editing your code so as not to require this outside file(s).


    Looking forward to your reply and clarifications.

  5. #5
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: Swing Bar Graph will not display in JPanel

    Thank you Furable. I'll attempt to address your points below.

    You have two classes posted above, both with main methods. What are both/either one supposed to do?
    The first class' objectives:
    - Read data from a .csv file. - Confirmed working
    - Store the data in an Object[][] rdataA; - Confirmed working
    - Create a JComboBox, the contents of which are the first column of the Object[][] rdataA to provide a selection set - Confirmed working
    - Handle a JComboBox selection by filling double[] value with a subset of the corresponding row data from rdataA - Confirmed working
    - Add the JComboBox to the JPanel - Confirmed working
    - Create an SimpleBarChart sb instance (more on this below), and add it to the JPanel - Not working. No errors, the sb object simply
    doesn't show up.

    The second class' objectives:
    - Create a 2d bar graph object that can:
    1. Accept input values (double[] value, String[] columns, String title) from the first class. JComboBox selection should update
    the double[] value. - Working Unknown
    2. Paint the graph on a JPanel. - Working Unknown


    What are they not doing that they should be doing?
    Not doing: Displaying the bar graph below the JComboBox in the JPanel.
    Should be doing: Display a JComboBox. Handle selections from the JComboBox by changing the Bar Graph displayed below it.


    A true SSCCE should run for us unmodified and require no outside code, libraries or files. You first class doesn't fulfill this criteria,
    and so if we can't run it and test it, we can't help you. Consider editing your code so as not to require this outside file(s).
    Not to appear contrary or ungrateful, but I don't see a way around this. Hard-coding the values would be poor programming from an OOP perspective
    as I have come to understand it. Also, within the context of the enterprise, the data set represents frequently-changing metrics on the status
    of Customer Inventories. The .csv is generated from an SQL extract on our database. I can, hopefully provide some clarity, however:

    A subset of Object[][] rdataA, which holds the contents of the .csv appears as follows via one of my many println()'s:

    31STNCR 55752 P OT 3 0 89 2 0 94 3.26 96.74
    374TSYKR FB520 P AF 0 1 8 0 0 9 0 88.89
    374TWYJR P AF 11 0 5 2 0 18 68.75 31.25
    3DFSSGKR P MC 0 0 2 0 0 2 0 100
    3RDDLFJR 29024 P MC 4 0 13 0 0 17 23.53 76.47
    730AMOGR P AF 10 0 8 0 1 19 55.56 44.44
    ACB1S 55104 R FS 373 2 627 9 0 1012 37.23 62.57
    ACB2LCS 55105 C NS 578 0 461 2 0 1041 55.63 44.37
    ACU1S 53257 R NS 649 12 331 251 83 1326 65.42 33.37
    ACU1WPDS 55622 R FS 247 14 91 2 0 365 70.17 25.85
    ACU2LCS 53210 C NS 815 1 200 248 1 1272 80.22 19.69
    ACU4LCS 47106 C NS 471 28 229 22 0 751 64.7 31.46
    ACU5E 46587 Q FS 324 6 161 136 75 704 65.99 32.79
    ACU5S 46587 R FS 206 0 188 6 2 407 52.28 47.72
    ACU5WPDE 55621 Q FS 137 6 59 28 2 235 67.82 29.21
    AD4555R 421 A DW 10 2 10 81 238 341 45.45 45.45
    AEGISTCE 3596A B ES 294 18 551 330 39 1234 34.07 63.85
    AEGISWIE 45534 B ES 11 0 93 65 0 169 10.58 89.42

    Here's double value[] returned by another println() after selecting customer '31STNCR' from the JComboBox.

    [3.0, 0.0, 89.0, 2.0, 0.0, 94.0, 3.26, 96.74]

    Summary: The dataset is being read correctly. The JComboBox is being populated correctly. A selection event on the combo box produces the correct output in a println(). However, the SimpleBarChart sb is not displaying below the JComboBox. It would seem that I am 'Close, but no cigar'..
    Last edited by Redefine12; 05-01-2012 at 12:20 AM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Swing Bar Graph will not display in JPanel

    I placed your data above in a file and tried to read it in with your program but it failed due to it trying to split the line on commas and there are no commas present. I could fiddle with it to get it to work perhaps, but I have work to catch up on here and will leave this up to you. Please post back if you can post a working program and data file, and I promise to look at it some more.

Similar Threads

  1. Putting a graph on another JPanel in another JFrame
    By thestarncy in forum AWT / Swing
    Replies: 10
    Last Post: 12-31-2009, 04:45 PM
  2. how can I display more then one Java Graph
    By santana in forum New To Java
    Replies: 2
    Last Post: 10-29-2009, 10:22 AM
  3. Drawing Graph and Add to JPanel
    By halo3 in forum NetBeans
    Replies: 17
    Last Post: 09-22-2009, 01:31 PM
  4. Display graph in tabbed panel
    By Laura Warren in forum New To Java
    Replies: 3
    Last Post: 01-12-2009, 11:34 PM
  5. how to draw x-y graph in Jpanel.--not in APPLET.
    By vincent2001@gmail.com in forum New To Java
    Replies: 2
    Last Post: 08-24-2008, 05:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •