Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default Help in plotting graph

    hi... i just want to ask help with my SIMULATION PROJECT... .
    i have some few problems on it...

    1. The ScrollPane cannot be seen eventhough i already add it on the class... so i just deleted it and no scrollpane...:(:(
    2. Please help me plot the "Acceleration" result in a graph. i am having trouble coding it...:( :( :(

    here is the code....

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.util.Random;
    import java.util.*;
    
     
    public class Simulation extends JFrame 
    {
    	private ButtonGroup rg;
    	private JLabel l1, l2, l3, l4, l5, vl, brl, cyl, frc, acc;
    	private JComboBox bb, motif, wcardna;
    	private JTextArea list, result;
    	private JButton p1, p2, p3, p4;
    	private JRadioButton abox, bbox;
    	private JPanel picpan, conpan, bpan;
    	
    	public Simulation()
    	{
    		simulate();	
    	}
    		public void simulate()
    		
    		{
    	
    		//setup container
    		Container contentPane = getContentPane();
    		contentPane.setLayout(null);
    		contentPane.setBackground(Color.pink);
    
    		
    		vl = new JLabel();
    		vl.setBounds(55,80, 100,30);
    		vl.setText("Velocity");
    		contentPane.add(vl);
    		
    		brl = new JLabel();
    		brl.setBounds(145,80, 100,30);
    		brl.setText("Barrel Length");
    		contentPane.add(brl);
    		
    		cyl = new JLabel();
    		cyl.setBounds(320,80, 100,30);
    		cyl.setText("Cylinder Length");
    		contentPane.add(cyl);
    		
    		frc = new JLabel();
    		frc.setBounds(494,80, 100,30);
    		frc.setText("Spring Force");
    		contentPane.add(frc);
    		
    		acc = new JLabel();
    		acc.setBounds(671,80, 100,30);
    		acc.setText("Acceleration");
    		contentPane.add(acc);
    		
    		//setup textarea of the simulation result
    		list = new JTextArea();
    		list.setBounds(56,110, 770,425);
    		list.setEditable(false );
    		list.setToolTipText("Simulation Result");
    		
    		contentPane.add(list);	
    					
    		//setup Simulate button
    		p1 = new JButton();
    		p1.setBounds(300, 580, 95, 50);
    		p1.setText("Simulate");
    		p1.setToolTipText("Press To Simulate");
    		p1.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					generate();
    					
    				}
    			}	
    		);
    		contentPane.add(p1);
    		
    		//setup Clear button
    		p2 = new JButton();
    		p2.setBounds(400, 580, 95, 50);
    		p2.setText("Clear");
    		p2.setToolTipText("Press to Clear output");
    		p2.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					list.setText("");
    					
    				}
    			}	
    		);
    		contentPane.add(p2);
    		
    		//setup Exit button
    		p3 = new JButton();
    		p3.setBounds(500, 580, 95, 50);
    		p3.setText("Exit");
    		p3.setToolTipText("Press To Quit");
    		p3.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					JOptionPane.showMessageDialog(null, "Thank you for using our simulation"
    								,"Exit",JOptionPane.INFORMATION_MESSAGE);
     							System.exit(0);		
    					
    				}
    			}	
    		);
    		contentPane.add(p3);
    	
    	
    		//setup panel for the muzzle result
    		picpan = new JPanel();
    		picpan.setBounds(30,55,825,500);
    		picpan.setBorder(new TitledBorder("  Airsoft Muzzle Result"));
    		picpan.setLayout(null);
    		picpan.setBackground(Color.pink);
    		contentPane.add(picpan);
    			
    		//setup panel for the buttons
    		bpan = new JPanel();
    		bpan.setBounds(287,560,320,80);
    		bpan.setBorder(new TitledBorder("  Simulation Buttons"));
    		bpan.setLayout(null);
    		bpan.setBackground(Color.pink);
    		contentPane.add(bpan);
    		
    		rg = new ButtonGroup();
    		rg.add(abox);
    		rg.add(bbox);
    				
    		//setup container size and name
    		setSize(900,700);
    		setTitle("Airsoft Muzzle Simulator");
    		show();
    		
    		}	
    		
    		//method checkbox generate
    	
    		public void generate()
    			{
    			
    			double Accel;
    			double fLa;
    			double fLb;
    			double Vo;
    			double B;
    			double Ptotal;
    			double Padded;
    			double Lt;
    			double fVo;
    			double Ab = 0.00011304;
    			double Patm = 101.325;
    			double Ff = 2.53;
    			
    				for(int counter = 0;counter <=25;counter++)
    				{
    
    				Random generator = new Random();
    	
    				//generate random barrel length at minimum 0.110m and maximum of 0.650m
    				double maxLb = Math.max(0.650, 0.110);
    				double minLb = Math.min(0.650, 0.110);
    				double Lb = generator.nextDouble() * (maxLb - minLb) + minLb;
    	
    				//generate random cylinder length at minimum of 0.3m and maximum of 1.0m
    				double maxLa = Math.max(0.9, 0.3);
    				double minLa = Math.min(0.9, 0.3);
    				double La = generator.nextDouble() * (maxLa - minLa) + minLa;
    
    				//generate random spring force from 100N to 200N
    				double maxF = Math.max(200.0, 100.0);
    				double minF = Math.min(200.0, 100.0);
    				double F = generator.nextDouble() * (maxF - minF) + minF;
    
    				//generate random cylinder area from 0.20m^2 to 0.9.m^2
    				double maxAa = Math.max(0.90, 0.20);
    				double minAa = Math.min(0.90, 0.20);
    				double Aa = generator.nextDouble()*(maxAa - minAa) + minAa;
    	
    				//generate random mass from 0.002kg to 0.005kg
    				double maxM = Math.max(0.005, 0.002);
    				double minM = Math.min(0.005, 0.002);
    				double M = generator.nextDouble() * (maxM - minM) + minM;
    			
    				//initialize for loop
    				Padded = F/Aa;
    				Ptotal = Patm + Padded;
    		
    				Lt = La + Lb;
    
    				B = Lt/La;
    
    				//calculate velocity in meter per second
    				Vo = Math.sqrt(   ( (2 *(Aa * Ptotal * (La * (Math.log(B)))) ) - (Patm * Ab * Lb) - (Ff * Lb)) / M  );
    			
    				Accel = (Vo * Vo) / (2 * Lb);
    		
    				//convert velocity to feet per second
    				fVo = 3.28 * Vo;
    			
    				//convert barrel length to millimeter
    				fLb = Lb * 1000;
    			
    				//convert cylinder length to millimeter
    				fLa = La * 1000;
    			
    				//Show ouput results in textarea 
    				list.append(""+Math.round(fVo)+"fps\t" +Math.round(fLb)+"mm\t\t"+Math.round(fLa)+"mm\t\t"+Math.round(F)+"N\t\t"+Math.round(Accel)+"m/s^2\n");
    			
    				}
    			
    			}
    			
    		public static void main(String[] args)
    		{
    		Simulation application = new Simulation();
    		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
    		}
    }


    for your comments and advices, please free to post... i will update my thread.. . thanks...


    i failed in my simulation project because i did not finished or furnished it well.. so i retake simulation again and i will proposed again this simulation project of mine and this time, i will add "Velocity" which will computed by this formula:

    Velocity = Distance / Time

    Hope my proposal will be accepted so if ever my project will be accepted, please help me plot the "Velocity" in a graph... :)

    thanks...

    Hoping i will learn from you guyz...
    Last edited by javafanatic; 11-28-2009 at 10:24 AM.

  2. #2
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    bump!!!! please help!!!!

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

    Default

    1) You should avoid using absolute positioning and instead use the layout managers. It will make debugging, upgrading, and managing your app's layout that much easier.

    2) We have no idea why your scrollpane didn't work as you don't show us the faulty code. My guess is that you set the bounds of your text area but not the scrollpane, but who knows. for instance, this works:
    Java Code:
          //setup textarea of the simulation result
          list = new JTextArea();
          //!! list.setBounds(56, 110, 770, 425); //!! remove
          list.setEditable(false);
          list.setToolTipText("Simulation Result");
    
          JScrollPane scrollPane = new JScrollPane(list); //!! add
          scrollPane.setBounds(56, 110, 770, 425); //!! add
          //!! contentPane.add(list); //!! remove
          contentPane.add(scrollPane); //!! add
    3) I would use a JTable instead of a JTextArea with headings.

    4) Before you bump this again, let's see your attempt to plot first and work from there. If this is that important to you, then you should show the effort of what you've tried.

    Good luck!
    Last edited by Fubarable; 11-29-2009 at 06:27 AM.

  4. #4
    dinosoep is offline Senior Member
    Join Date
    Nov 2009
    Posts
    150
    Rep Power
    5

    Default

    use an idea like netbeans to build your gui.
    you can select which lay out you want to use and just paint your components.
    never use nul layout!!!

  5. #5
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    thanks Fubarable.... . .i am adding the code for the graph right now but there is no graph shown... soon i will post my additional code... . .just give me some time..:) thanks!!!

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

    Default

    Quote Originally Posted by dinosoep View Post
    use an idea like netbeans to build your gui.
    I respectfully disagree -- not when you're learning Swing as the NetBeans GUI-builder shields you from having to directly deal with Swing components and will slow your learning.

    you can select which lay out you want to use and just paint your components.
    never use nul layout!!!
    I respectfully disagree again (kind of). There are times and places for null layout, for instance when you wish the user to drag a component onto a location on your panel. I'd say that > 95% of the time, you'll want to use layout managers though.

  7. #7
    dinosoep is offline Senior Member
    Join Date
    Nov 2009
    Posts
    150
    Rep Power
    5

    Default

    about that learning, maybe your correct.
    never experienced that but i learned programming without ide until i discovered the use of an ide.
    I've heard horror stories about persons writing whole programs with the null layout and when running somewhere else there whole layout is messed up. aren't they true?

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

    Default

    Yes, if you change screen resolutions and default font types, you can greatly uglify your GUI. But that's not a problem for me since I create small utilities for my own use on my own computers. I mainly use the layout managers since I'm by nature lazy, and I like giving the hard task of keeping components on the best location to something else. As a for-instance, here is a similar app to the OPs (though not the same):

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    public class Simulate2 {
       private static final String[] COLUMN_NAMES = {
          "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
       };
       private static final String[] BUTTON_NAMES = {
          "January", "February", "March"
       };
       private static final Dimension PREF_SIZE = new Dimension(900, 700);
       private static final int ROW_MAX = 100;
       
       private JPanel mainPanel = new JPanel();
       private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, ROW_MAX);
       private JTable table = new JTable(model);
       private Random random = new Random();
       
       public Simulate2() {
          JPanel tablePanel = new JPanel(new BorderLayout());
          int eb = 20;
          tablePanel.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Fubars Unite!"), 
                   BorderFactory.createEmptyBorder(eb, eb, eb, eb)));
          tablePanel.add(new JScrollPane(table), BorderLayout.CENTER);
          tablePanel.setOpaque(false);
          
          JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 10, 10));
          for (String btnString : BUTTON_NAMES) {
             JButton button = new JButton(btnString);
             button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   buttonActionPerformed(e);
                }
             });
             buttonPanel.add(button);
          }
          eb = 10;
          buttonPanel.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Snafus Unlimited"), 
                   BorderFactory.createEmptyBorder(eb, eb, eb, eb)));
          buttonPanel.setOpaque(false);
          
          eb = 30;
          mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
          mainPanel.setPreferredSize(PREF_SIZE);
          mainPanel.setLayout(new BorderLayout(10, 10));
          mainPanel.add(tablePanel, BorderLayout.CENTER);
          mainPanel.add(buttonPanel, BorderLayout.SOUTH);
          mainPanel.setBackground(new Color(255, 215, 215));
       }
    
       private void buttonActionPerformed(ActionEvent e) {
          String command = e.getActionCommand();
    
          if (command.equalsIgnoreCase("January")) {
             for (int row = 0; row < model.getRowCount(); row++) {
                model.setValueAt(row, row, 0);
                for (int col = 1; col < model.getColumnCount(); col++) {
                   model.setValueAt(random.nextInt(1000), row, col);
                }
             }
          }
          else if (command.equalsIgnoreCase("February")) {
             for (int row = 0; row < model.getRowCount(); row++) {
                for (int col = 0; col < model.getColumnCount(); col++) {
                   model.setValueAt(null, row, col);
                }
             }
          }
          else if (command.equalsIgnoreCase("March")) {
             Window win = SwingUtilities.getWindowAncestor(mainPanel);
             win.dispose();
          }
       }
    
       public JComponent getComponent() {
          return mainPanel;
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Simulate2");
          frame.getContentPane().add(new Simulate2().getComponent());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    It creates 3 buttons on the bottom: January, February, and March, and uses a Grid layout to space the buttons evenly along the bottom. Now what if I want to add a fourth button? If I were using absolute positioning or null layout, I'd have to not only add a new button, but I'd have to manually resize and relocate all other components affected by this addition. But since I'm not using null layout, all I have to do is change this:
    Java Code:
       private static final String[] BUTTON_NAMES = {
          "January", "February", "March"
       };
    to this:
    Java Code:
       private static final String[] BUTTON_NAMES = {
          "January", "February", "March", "April"
       };
    and the layout managers take care of repositioning and what-not. It doesn't get much easier than that.

  9. #9
    dinosoep is offline Senior Member
    Join Date
    Nov 2009
    Posts
    150
    Rep Power
    5

    Default

    thanks for explaining it a bit.
    but about dragging components on a place on your panel, is this possible with a layout manager?

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

    Default

    Quote Originally Posted by dinosoep View Post
    thanks for explaining it a bit.
    but about dragging components on a place on your panel, is this possible with a layout manager?
    Yes, I believe that you can. You can use whatever layout you desire, but then move the component to the glass pane when you click on it, then drop it. I've not done this yet though, so I'm not speaking from experience.

  11. #11
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    im having trouble for initial code of plotting my graph...:( :(

    Java Code:
    
    //import packages
    
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.util.Random;
    import java.util.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    
     
    public class Simulation extends JFrame
    {
    	private ButtonGroup rg;
    	private JLabel l1, l2, l3, l4, l5, vl, brl, cyl, frc, acc;
    	private JComboBox bb, motif, wcardna;
    	private JTextArea list, result;
    	private JButton p1, p2, p3, p4, g1;
    	private JRadioButton abox, bbox;
    	private JPanel picpan, conpan, bpan;
    	
    	
    	private int[] data = {
            21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
            61, 55, 48, 60, 49, 36, 38, 27, 20, 18
        };
        
        final int PAD = 20;
    	
    	
    	public Simulation()
    	{
    		simulate();	
    	}
    		public void simulate()
    		
    		{
    	
    		//setup container
    		Container contentPane = getContentPane();
    		contentPane.setLayout(null);
    		contentPane.setBackground(Color.pink);
    
    		
    		vl = new JLabel();
    		vl.setBounds(55,80, 100,30);
    		vl.setText("Velocity");
    		contentPane.add(vl);
    		
    		brl = new JLabel();
    		brl.setBounds(145,80, 100,30);
    		brl.setText("Barrel Length");
    		contentPane.add(brl);
    		
    		cyl = new JLabel();
    		cyl.setBounds(320,80, 100,30);
    		cyl.setText("Cylinder Length");
    		contentPane.add(cyl);
    		
    		frc = new JLabel();
    		frc.setBounds(494,80, 100,30);
    		frc.setText("Spring Force");
    		contentPane.add(frc);
    		
    		acc = new JLabel();
    		acc.setBounds(671,80, 100,30);
    		acc.setText("Acceleration");
    		contentPane.add(acc);
    		
    		//setup textarea of the simulation result
    		list = new JTextArea();
    		list.setBounds(56,110, 770,425);
    		list.setEditable(false );
    		list.setToolTipText("Simulation Result");
    	//	contentPane.add(list);	
    			
    		JScrollPane scrollPane = new JScrollPane(list); //!! add
          	scrollPane.setBounds(56, 110, 770, 425); //!! add
          //!! contentPane.add(list); //!! remove
          	contentPane.add(scrollPane); //!! add	
    			
    	
    		g1 = new JButton("Graph");
    		g1.setBounds(10, 580, 95, 50);
    		g1.addActionListener(
    			new ActionListener()
    			{
    				public void actionPerformed(ActionEvent event)
    				{
    					
    					graph1();
    				}
    			}
    			);
    		contentPane.add(g1);
    		
    		
    		
    		//setup Simulate button
    		p1 = new JButton();
    		p1.setBounds(300, 580, 95, 50);
    		p1.setText("Simulate");
    		p1.setToolTipText("Press To Simulate");
    		p1.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					generate();
    					
    				}
    			}	
    		);
    		contentPane.add(p1);
    		
    		//setup Clear button
    		p2 = new JButton();
    		p2.setBounds(400, 580, 95, 50);
    		p2.setText("Clear");
    		p2.setToolTipText("Press to Clear output");
    		p2.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					list.setText("");
    					
    				}
    			}	
    		);
    		contentPane.add(p2);
    		
    		//setup Exit button
    		p3 = new JButton();
    		p3.setBounds(500, 580, 95, 50);
    		p3.setText("Exit");
    		p3.setToolTipText("Press To Quit");
    		p3.addActionListener(
    			new ActionListener()
    			{
    			
    				public void actionPerformed(ActionEvent event)
    				{
    					JOptionPane.showMessageDialog(null, "Thank you for using our simulation"
    								,"Exit",JOptionPane.INFORMATION_MESSAGE);
     							System.exit(0);		
    					
    				}
    			}	
    		);
    		contentPane.add(p3);
    	
    	
    		//setup panel for the muzzle result
    		picpan = new JPanel();
    		picpan.setBounds(30,55,825,500);
    		picpan.setBorder(new TitledBorder("  Airsoft Muzzle Result"));
    		picpan.setLayout(null);
    		picpan.setBackground(Color.pink);
    		contentPane.add(picpan);
    			
    		//setup panel for the buttons
    		bpan = new JPanel();
    		bpan.setBounds(287,560,320,80);
    		bpan.setBorder(new TitledBorder("  Simulation Buttons"));
    		bpan.setLayout(null);
    		bpan.setBackground(Color.pink);
    		contentPane.add(bpan);
    		
    		rg = new ButtonGroup();
    		rg.add(abox);
    		rg.add(bbox);
    		
    		
    		
    				
    		//setup container size and name
    		setSize(900,700);
    		setTitle("Airsoft Muzzle Simulator");
    		show();
    		
    		}	
    		
    		//method checkbox generate
    	
    		public void generate()
    			{
    			
    			double Accel;
    			double fLa;
    			double fLb;
    			double Vo;
    			double B;
    			double Ptotal;
    			double Padded;
    			double Lt;
    			double fVo;
    			double Ab = 0.00011304;
    			double Patm = 101.325;
    			double Ff = 2.53;
    			
    				for(int counter = 0;counter <=25;counter++)
    				{
    
    				Random generator = new Random();
    	
    				//generate random barrel length at minimum 0.110m and maximum of 0.650m
    				double maxLb = Math.max(0.650, 0.110);
    				double minLb = Math.min(0.650, 0.110);
    				double Lb = generator.nextDouble() * (maxLb - minLb) + minLb;
    	
    				//generate random cylinder length at minimum of 0.3m and maximum of 1.0m
    				double maxLa = Math.max(0.9, 0.3);
    				double minLa = Math.min(0.9, 0.3);
    				double La = generator.nextDouble() * (maxLa - minLa) + minLa;
    
    				//generate random spring force from 100N to 200N
    				double maxF = Math.max(200.0, 100.0);
    				double minF = Math.min(200.0, 100.0);
    				double F = generator.nextDouble() * (maxF - minF) + minF;
    
    				//generate random cylinder area from 0.20m^2 to 0.9.m^2
    				double maxAa = Math.max(0.90, 0.20);
    				double minAa = Math.min(0.90, 0.20);
    				double Aa = generator.nextDouble()*(maxAa - minAa) + minAa;
    	
    				//generate random mass from 0.002kg to 0.005kg
    				double maxM = Math.max(0.005, 0.002);
    				double minM = Math.min(0.005, 0.002);
    				double M = generator.nextDouble() * (maxM - minM) + minM;
    			
    				//initialize for loop
    				Padded = F/Aa;
    				Ptotal = Patm + Padded;
    		
    				Lt = La + Lb;
    
    				B = Lt/La;
    
    				//calculate velocity in meter per second
    				Vo = Math.sqrt(   ( (2 *(Aa * Ptotal * (La * (Math.log(B)))) ) - (Patm * Ab * Lb) - (Ff * Lb)) / M  );
    			
    				Accel = (Vo * Vo) / (2 * Lb);
    		
    				//convert velocity to feet per second
    				fVo = 3.28 * Vo;
    			
    				//convert barrel length to millimeter
    				fLb = Lb * 1000;
    			
    				//convert cylinder length to millimeter
    				fLa = La * 1000;
    			
    				//Show ouput results in textarea 
    				list.append(""+Math.round(fVo)+"fps\t" +Math.round(fLb)+"mm\t\t"+Math.round(fLa)+"mm\t\t"+Math.round(F)+"N\t\t"+Math.round(Accel)+"m/s^2\n");
    			
    				}
    			
    			}
    			
    	//adding the graph
    
    		
    			public void graph1()
    			{
    				
    				
    		protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            // Draw ordinate.
            g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
            // Draw abcissa.
            g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
            // Draw labels.
            Font font = g2.getFont();
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics("0", frc);
            float sh = lm.getAscent() + lm.getDescent();
            // Ordinate label.
            String s = "data";
            float sy = PAD + ((h - 2*PAD) - s.length()*sh)/2 + lm.getAscent();
            for(int i = 0; i < s.length(); i++) {
                String letter = String.valueOf(s.charAt(i));
                float sw = (float)font.getStringBounds(letter, frc).getWidth();
                float sx = (PAD - sw)/2;
                g2.drawString(letter, sx, sy);
                sy += sh;
            }
            // Abcissa label.
            s = "x axis";
            sy = h - PAD + (PAD - sh)/2 + lm.getAscent();
            float sw = (float)font.getStringBounds(s, frc).getWidth();
            float sx = (w - sw)/2;
            g2.drawString(s, sx, sy);
            // Draw lines.
            double xInc = (double)(w - 2*PAD)/(data.length-1);
            double scale = (double)(h - 2*PAD)/getMax();
            g2.setPaint(Color.green.darker());
            for(int i = 0; i < data.length-1; i++) {
                double x1 = PAD + i*xInc;
                double y1 = h - PAD - scale*data[i];
                double x2 = PAD + (i+1)*xInc;
                double y2 = h - PAD - scale*data[i+1];
                g2.draw(new Line2D.Double(x1, y1, x2, y2));
            }
            // Mark data points.
            g2.setPaint(Color.red);
            for(int i = 0; i < data.length; i++) {
                double x = PAD + i*xInc;
                double y = h - PAD - scale*data[i];
                g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
            }
        }
    
        private int getMax() {
            int max = -Integer.MAX_VALUE;
            for(int i = 0; i < data.length; i++) {
                if(data[i] > max)
                    max = data[i];
            }
            return max;
        }
    				
    	}
    			
    		public static void main(String[] args)
    		{
    			
    		JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new GraphingData());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    		Simulation application = new Simulation();
    		application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
    		}
    }
    there is a conflict of my public void graph1() with the protected void paintComponent(Graphics g) but the graph1() is the actionlistener of my button... . im trying to plot the int[] data with another screen because i set another button to output the graph..:( any suggestion about my code??? :( :(
    Java Code:
    
    			public void graph1()
    			{
    				
    				
    		protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

    i jsut copy and paste the code some of the thread here in forums... i just want to try adding the actionlistener which the output will be the graph.. but there is an error...:( :(

  12. #12
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    bumping....:D


    can i use JGraph in my code????

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

    Default

    I'm not familiar with JGraph, but I'm sure you could use JFreeChart in this situation.

    You seem to have a lot of code in one class that do disparate things, and I think this is a good situation for dividing and conquering. If this were my app, I'd work on getting the graphing to work in a separate class(s) with simple data. Then once it's functioning use this class in my main program. YMMV.

    Much luck.
    Last edited by Fubarable; 12-01-2009 at 02:17 PM.

  14. #14
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    does JCreator has already have a class for JFreeChart or i will download the library on it??:D

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

    Default

    You would have to go to the site and download it. Google can find it for you in a jiffy.

  16. #16
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    I am having problem importing JFreeChart package...:(
    I attached SS and some links for more references...


    i cant post links at this time..only during after 20 reply posts..:(

    @Fubarable

    can i pM to you the links??:) thanks..

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

  18. #18
    javafanatic is offline Member
    Join Date
    Nov 2009
    Posts
    22
    Rep Power
    0

    Default

    Fubarable, i posted an Screen Shots together with that link... any suggestions regarding my concern??:)

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

    Default

    Here's your image.


    Have you told JCreator where to find these packages? I don't know how this is done in JCreator (though I've done it in Eclipse).

    I'll try to look at your code later, but for now, I'm on call and have to head in to work :(

    I'm sure that better minds are looking this over as I write this. Best of luck.

  20. #20
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    From reply 11:
    im having trouble for initial code of plotting my graph...
    Compiling your (renamed) Simulation class gives:
    Java Code:
    C:\jexp>javac simulationrx.java
    simulationrx.java:269: illegal start of expression
            protected void paintComponent(Graphics g) {
            ^
    simulationrx.java:332: class, interface, or enum expected
        public static void main(String[] args)
                      ^
    simulationrx.java:335: class, interface, or enum expected
            application.setDefaultCloseOperation(EXIT_ON_CLOSE);
            ^
    simulationrx.java:337: class, interface, or enum expected
        }
        ^
    4 errors
    The trouble is here:
    Java Code:
        public void graph1()
        {
            protected void paintComponent(Graphics g) {
    Placing a method inside another method like this is not allowed in java.
    The genaral technique is to use a separate JPanel as a graphic component to draw your graph/ics on and add this component into you gui with an appropriate size hint.
    Java Code:
    public class Simulation extends JFrame {
        YourGraphicComponent ygc = new YourGraphicComponent();
    
        public Simulation() {
            // build gui
            // add ygc to your gui
            // show gui
        }
    
        public static void main(String[] args) {
            new Simulaton();
        }
    }
    
    public class YourGraphicComponent extends JPanel {
    
        protected void paintComponent(Graphics g) {
            // draw your graph here
        }
    
        /** one way to provide a size hint */
        public Dimension getPreferredSize() {
            return new Dimension(desiredWidth, height);
        }
    }
    Then, a compiler warning:
    Java Code:
    C:\jexp>javac simulationrx.java
    Note: simulationrx.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    which you deal with like this
    Java Code:
    C:\jexp>javac -Xlint:deprecation Simulationrx.java
    Simulationrx.java:182: warning: [deprecation] show() in java.awt.Window has been deprecate
    d
            show();
            ^
    1 warning
    Look up the method in the javadocs to see that it has been replaced with setVisible.

    This will now compile and run okay (after minimal changes).
    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.util.Random;
    import java.util.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    
    
    public class SimulationRx extends JFrame
    {
        private ButtonGroup rg;
        private JLabel l1, l2, l3, l4, l5, vl, brl, cyl, frc, acc;
        private JComboBox bb, motif, wcardna;
        private JTextArea list, result;
        private JButton p1, p2, p3, p4, g1;
        private JRadioButton abox, bbox;
        private JPanel picpan, conpan, bpan;
    
    
        private int[] data = {
            21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
            61, 55, 48, 60, 49, 36, 38, 27, 20, 18
        };
    
        final int PAD = 20;
    
    
        public SimulationRx()
        {
            simulate();
        }
    
        public void simulate()
        {
            //setup container
            Container contentPane = getContentPane();
            contentPane.setLayout(null);
            contentPane.setBackground(Color.pink);
    
            vl = new JLabel();
            vl.setBounds(55,80, 100,30);
            vl.setText("Velocity");
            contentPane.add(vl);
    
            brl = new JLabel();
            brl.setBounds(145,80, 100,30);
            brl.setText("Barrel Length");
            contentPane.add(brl);
    
            cyl = new JLabel();
            cyl.setBounds(320,80, 100,30);
            cyl.setText("Cylinder Length");
            contentPane.add(cyl);
    
            frc = new JLabel();
            frc.setBounds(494,80, 100,30);
            frc.setText("Spring Force");
            contentPane.add(frc);
    
            acc = new JLabel();
            acc.setBounds(671,80, 100,30);
            acc.setText("Acceleration");
            contentPane.add(acc);
    
            //setup textarea of the simulation result
            list = new JTextArea();
            list.setBounds(56,110, 770,425);
            list.setEditable(false );
            list.setToolTipText("Simulation Result");
            //contentPane.add(list);
    
            JScrollPane scrollPane = new JScrollPane(list); //!! add
            scrollPane.setBounds(56, 110, 770, 425); //!! add
            //!! contentPane.add(list); //!! remove
            contentPane.add(scrollPane); //!! add
    
    
            g1 = new JButton("Graph");
            g1.setBounds(10, 580, 95, 50);
            g1.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
    //                graph1();
                    // You could add the graphic component to your gui
                    // and update or show it from here.
                    // We'll use a dialog here for minimal changes/demo.
                    JDialog dialog = new JDialog(new Frame(), "Graph Panel", false);
                    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    dialog.add(panel);
                    dialog.setSize(400,400);
                    dialog.setLocation(700,50);
                    dialog.setVisible(true);
                }
            });
            contentPane.add(g1);
    
    
    
            //setup Simulate button
            p1 = new JButton();
            p1.setBounds(300, 580, 95, 50);
            p1.setText("Simulate");
            p1.setToolTipText("Press To Simulate");
            p1.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    generate();
                }
            });
            contentPane.add(p1);
    
            //setup Clear button
            p2 = new JButton();
            p2.setBounds(400, 580, 95, 50);
            p2.setText("Clear");
            p2.setToolTipText("Press to Clear output");
            p2.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    list.setText("");
                }
            });
            contentPane.add(p2);
    
            //setup Exit button
            p3 = new JButton();
            p3.setBounds(500, 580, 95, 50);
            p3.setText("Exit");
            p3.setToolTipText("Press To Quit");
            p3.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    JOptionPane.showMessageDialog(null, "Thank you for using our 
    
    simulation"
                    ,"Exit",JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0);
                }
            });
            contentPane.add(p3);
    
    
            //setup panel for the muzzle result
            picpan = new JPanel();
            picpan.setBounds(30,55,825,500);
            picpan.setBorder(new TitledBorder("  Airsoft Muzzle Result"));
            picpan.setLayout(null);
            picpan.setBackground(Color.pink);
            contentPane.add(picpan);
    
            //setup panel for the buttons
            bpan = new JPanel();
            bpan.setBounds(287,560,320,80);
            bpan.setBorder(new TitledBorder("  Simulation Buttons"));
            bpan.setLayout(null);
            bpan.setBackground(Color.pink);
            contentPane.add(bpan);
    
            rg = new ButtonGroup();
            rg.add(abox);
            rg.add(bbox);
    
            //setup container size and name
            setSize(900,700);
            setTitle("Airsoft Muzzle Simulator");
    
    //        show();  deprecated method
            setVisible(true);
        }
    
        //method checkbox generate
    
        public void generate()
        {
            double Accel;
            double fLa;
            double fLb;
            double Vo;
            double B;
            double Ptotal;
            double Padded;
            double Lt;
            double fVo;
            double Ab = 0.00011304;
            double Patm = 101.325;
            double Ff = 2.53;
    
            for(int counter = 0;counter <=25;counter++)
            {
                Random generator = new Random();
    
                //generate random barrel length at minimum 0.110m and maximum of 
    
    0.650m
                double maxLb = Math.max(0.650, 0.110);
                double minLb = Math.min(0.650, 0.110);
                double Lb = generator.nextDouble() * (maxLb - minLb) + minLb;
    
                //generate random cylinder length at minimum of 0.3m and maximum of 
    
    1.0m
                double maxLa = Math.max(0.9, 0.3);
                double minLa = Math.min(0.9, 0.3);
                double La = generator.nextDouble() * (maxLa - minLa) + minLa;
    
                //generate random spring force from 100N to 200N
                double maxF = Math.max(200.0, 100.0);
                double minF = Math.min(200.0, 100.0);
                double F = generator.nextDouble() * (maxF - minF) + minF;
    
                //generate random cylinder area from 0.20m^2 to 0.9.m^2
                double maxAa = Math.max(0.90, 0.20);
                double minAa = Math.min(0.90, 0.20);
                double Aa = generator.nextDouble()*(maxAa - minAa) + minAa;
    
                //generate random mass from 0.002kg to 0.005kg
                double maxM = Math.max(0.005, 0.002);
                double minM = Math.min(0.005, 0.002);
                double M = generator.nextDouble() * (maxM - minM) + minM;
    
                //initialize for loop
                Padded = F/Aa;
                Ptotal = Patm + Padded;
    
                Lt = La + Lb;
    
                B = Lt/La;
    
                //calculate velocity in meter per second
                Vo = Math.sqrt(   ( (2 *(Aa * Ptotal * (La * (Math.log(B)))) ) - 
    
    (Patm * Ab * Lb) - (Ff * Lb)) / M  );
    
                Accel = (Vo * Vo) / (2 * Lb);
    
                //convert velocity to feet per second
                fVo = 3.28 * Vo;
    
                //convert barrel length to millimeter
                fLb = Lb * 1000;
    
                //convert cylinder length to millimeter
                fLa = La * 1000;
    
                //Show ouput results in textarea
                list.append(""+Math.round(fVo)+"fps\t" +Math.round(fLb)
    
    +"mm\t\t"+Math.round(fLa)+"mm\t\t"+Math.round(F)+"N\t\t"+Math.round(Accel)
    
    +"m/s^2\n");
            }
        }
    
        //adding the graph
    
        /** this could be a separate, outer class but okay here */
        public JPanel panel = new JPanel()
        {
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth();
                int h = getHeight();
                // Draw ordinate.
                g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
                // Draw abcissa.
                g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
                // Draw labels.
                Font font = g2.getFont();
                FontRenderContext frc = g2.getFontRenderContext();
                LineMetrics lm = font.getLineMetrics("0", frc);
                float sh = lm.getAscent() + lm.getDescent();
                // Ordinate label.
                String s = "data";
                float sy = PAD + ((h - 2*PAD) - s.length()*sh)/2 + lm.getAscent();
                for(int i = 0; i < s.length(); i++) {
                    String letter = String.valueOf(s.charAt(i));
                    float sw = (float)font.getStringBounds(letter, frc).getWidth();
                    float sx = (PAD - sw)/2;
                    g2.drawString(letter, sx, sy);
                    sy += sh;
                }
                // Abcissa label.
                s = "x axis";
                sy = h - PAD + (PAD - sh)/2 + lm.getAscent();
                float sw = (float)font.getStringBounds(s, frc).getWidth();
                float sx = (w - sw)/2;
                g2.drawString(s, sx, sy);
                // Draw lines.
                double xInc = (double)(w - 2*PAD)/(data.length-1);
                double scale = (double)(h - 2*PAD)/getMax();
                g2.setPaint(Color.green.darker());
                for(int i = 0; i < data.length-1; i++) {
                    double x1 = PAD + i*xInc;
                    double y1 = h - PAD - scale*data[i];
                    double x2 = PAD + (i+1)*xInc;
                    double y2 = h - PAD - scale*data[i+1];
                    g2.draw(new Line2D.Double(x1, y1, x2, y2));
                }
                // Mark data points.
                g2.setPaint(Color.red);
                for(int i = 0; i < data.length; i++) {
                    double x = PAD + i*xInc;
                    double y = h - PAD - scale*data[i];
                    g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
                }
            }
        };
    
            private int getMax() {
                int max = -Integer.MAX_VALUE;
                for(int i = 0; i < data.length; i++) {
                    if(data[i] > max)
                    max = data[i];
                }
                return max;
            }
    
    //    }
    
        public static void main(String[] args)
        {
            SimulationRx application = new SimulationRx();
            application.setDefaultCloseOperation(EXIT_ON_CLOSE);
            //new GraphingData();
        }
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. Plotting a line graph
    By revilo in forum New To Java
    Replies: 1
    Last Post: 10-11-2009, 12:07 AM
  2. Help regarding 3D graph plotting...
    By Megatron in forum New To Java
    Replies: 1
    Last Post: 05-21-2009, 04:26 PM
  3. Replies: 19
    Last Post: 04-25-2009, 08:15 PM
  4. Problems with graph plotting.
    By oveeye in forum AWT / Swing
    Replies: 2
    Last Post: 02-05-2009, 08:20 AM
  5. graph plotting
    By sirine in forum New To Java
    Replies: 5
    Last Post: 01-25-2009, 03:34 PM

Posting Permissions

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