Results 1 to 6 of 6
  1. #1
    peterhabe is offline Member
    Join Date
    Jul 2010
    Posts
    43
    Rep Power
    0

    Default If statement and JLabel.setText() problem

    Firstly, the if statement in my actionPerformed() method which checks the source of the event isn't working. I even copied and pasted the test for the if statement from another program that does work. actionPerformed() is near the bottom of the ControlPanelJPanel class.

    My second problem is time.setText() in the last method in the ControlPanelJPanel class. It comes up with the error: java.lang.NullPointerException. The println() before it prints out without a problem. I have the same problem in actionPerformed() as well where I am also trying to reset what the time JLabel is displaying.

    I have also put the AnimationThread class below as well as the value that is displayed comes from this class.

    Background info:
    When the JButton start is pressed, a thread to handle the animation on another JPanel is created. The time JLabel that is to display the time passed since the animation thread began is updated on every loop of the animation thread and settingJLabelTime() is called at the end of the thread loop. The reset button will reset the animation panel and the value displayed by the time JLabel.

    Java Code:
    package projectileProgram;
    
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class ControlPanelJPanel extends JPanel implements ChangeListener, ActionListener, ItemListener{
    	//variables
    	float meter;
    	int panelWidth, panelHeight;
    	ProjectileAnimationJPanel projectileAnimationJPanel;
    	ControlPanelJPanel controlPanelJPanel;
    	JSlider height = new JSlider(0,50,50);
        JSlider angle = new JSlider(0,90,0);
        JSlider speed = new JSlider(0,50,50);
        
        //////////////////////////////////////
        JButton start, reset;
        /////////////////////////////////////
        
        JCheckBox timeSpeedGraph, verticalVelocityGraph, horozontalVelocityGraph;
        
        ////////////////////////////////////////////////////////
        JLabel heightValues, angleValues, speedValues, time;
        ////////////////////////////////////////////////////////
        
        //setting variables elevation, projectionAngle and projectionSpeed
        String heightValue = String.valueOf(height.getValue());
        String angleValue = String.valueOf(angle.getValue());
        String speedValue = String.valueOf(speed.getValue());
        String timePassed = "0";
        float elevation = Float.parseFloat(heightValue);
    	float projectionAngle = Float.parseFloat(angleValue);
    	float projectionSpeed = Float.parseFloat(speedValue);
        //constructor
    	public ControlPanelJPanel(){
    		//height JSlider
    		height.setMajorTickSpacing(10);
    		height.setMinorTickSpacing(1);
    		height.setPaintTicks(true);
    		height.setPaintLabels(true);
    		height.setOpaque(false);
    		height.addChangeListener(this);
    		
    		//Angle JSlider 
    		angle.setMajorTickSpacing(10);
    		angle.setMinorTickSpacing(1);
    		angle.setPaintTicks(true);
    		angle.setPaintLabels(true);
    		angle.setOpaque(false);
    		angle.addChangeListener(this);
    		
    		//Speed JSlider 
    		speed.setMajorTickSpacing(10);
    		speed.setMinorTickSpacing(1);
    		speed.setPaintTicks(true);
    		speed.setPaintLabels(true);
    		speed.setOpaque(false);
    		speed.addChangeListener(this);
    		
    		//////////////////////////////setting time JLabel///////////////////////////////
    		JLabel time = new JLabel("Time/s: "+timePassed);;
    		
    		//creating labels for Sliders	
    		JLabel heightLabel = new JLabel	("Height: ");
            JLabel angleLabel = new JLabel ("Angle: ");
            JLabel speedLabel = new JLabel ("Speed: ");
            
            //creating labels for value of sliders
            heightValues = new JLabel("Height Value: "+heightValue);
            angleValues = new JLabel ("Angle Value: "+angleValue);
            speedValues = new JLabel ("Speed Value: "+speedValue);
            
            ////////////////////////////////start button/////////////////////////////////////
            JButton start = new JButton("start");
            start.setPreferredSize(new Dimension(75,25));
            start.addActionListener(this);
            
            /////////////////////////////////////reset button///////////////////////////////
            JButton reset = new JButton("reset");
            reset.setPreferredSize(new Dimension(75,25));
            reset.addActionListener(this);
            
            
            //setting JCheckBoxes
            JCheckBox timeSpeedGraph = new JCheckBox("Time Speed Graph");
            timeSpeedGraph.setOpaque(false);
            timeSpeedGraph.addItemListener(this);
            
            JCheckBox verticalVelocityGraph = new JCheckBox("Vertical Velocity Graph");
            verticalVelocityGraph.setOpaque(false);
            verticalVelocityGraph.addItemListener(this);
            
            JCheckBox horozontalVelocityGraph = new JCheckBox("Horozontal Velocity Graph");
            horozontalVelocityGraph.setOpaque(false);
            horozontalVelocityGraph.addItemListener(this);
            
            //setting layout
            this.setLayout(new GridBagLayout());
            GridBagConstraints gc = new GridBagConstraints(); 
            
            //column 0
            gc.weightx = 25;
    		gc.weighty = 100;
            //adding start to screen 
    		gc.gridx = 0;
    		gc.gridy = 1;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.NONE;
    		add(start, gc);
    		
    		//adding reset to screen 
    		gc.gridx = 0;
    		gc.gridy = 2;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.NONE;
    		add(reset, gc);
    		
    		//adding timePassed
    		gc.gridx = 0;
    		gc.gridy = 6;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.NONE;
    		add(time, gc);
            
    		//column 1
    		gc.weightx = 25;
    		gc.weighty = 100;
    		//adding heightLabel to screen 
    		gc.gridx = 1;
    		gc.gridy = 1;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.EAST;
    		gc.fill = GridBagConstraints.NONE;
    		add(heightLabel, gc);
    		
    		//column 2
    		gc.weightx = 100;
    		gc.weighty = 100;
    		//adding height to screen
    		gc.gridx = 2;
    		gc.gridy = 0;
    		gc.gridwidth = 1;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(height, gc);
    		
    		//adding heightValues to screen
    		gc.gridx = 2;
    		gc.gridy = 3;
    		gc.gridwidth = 2;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(heightValues, gc);
    		
    		//column 3
    		gc.weightx = 25;
    		gc.weighty = 100;
    		//adding angleLabel to screen
    		gc.gridx = 3;
    		gc.gridy = 1;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.EAST;
    		gc.fill = GridBagConstraints.NONE;
    		add(angleLabel, gc);
    		
    		//column 4
    		gc.weightx = 100;
    		gc.weighty = 100;
    		//adding speed angle to screen
    		gc.gridx = 4;
    		gc.gridy = 0;
    		gc.gridwidth = 1;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(angle, gc);
    		
    		//adding angleValues to screen
    		gc.gridx = 4;
    		gc.gridy = 3;
    		gc.gridwidth = 2;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(angleValues, gc);
    		
    		//column 5
    		gc.weightx = 25;
    		gc.weighty = 100;
    		//adding speedLabel to screen
    		gc.gridx = 5;
    		gc.gridy = 1;
    		gc.gridwidth = 1;
    		gc.gridheight = 1;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.EAST;
    		gc.fill = GridBagConstraints.NONE;
    		add(speedLabel, gc);
    		
    		//column 6
    		gc.weightx = 100;
    		gc.weighty = 100;
    		//adding speed to screen
    		gc.gridx = 6;
    		gc.gridy = 0;
    		gc.gridwidth = 1;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(speed, gc);
    		
    		//adding speedValues to screen
    		gc.gridx = 6;
    		gc.gridy = 3;
    		gc.gridwidth = 2;
    		gc.gridheight = 3;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(speedValues, gc);
    		
    		//column 7
    		gc.weightx = 100;
    		gc.weighty = 100;
    		//adding timeSpeedGraph to screen
    		gc.gridx = 7;
    		gc.gridy = 0;
    		gc.gridwidth = 1;
    		gc.gridheight = 2;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(timeSpeedGraph, gc);
    		
    		//adding horozontalVelocityGraph to screen
    		gc.gridx = 7;
    		gc.gridy = 2;
    		gc.gridwidth = 1;
    		gc.gridheight = 2;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(horozontalVelocityGraph, gc);
    		
    		
    		//adding verticalVelocityGraph to screen
    		gc.gridx = 7;
    		gc.gridy = 4;
    		gc.gridwidth = 1;
    		gc.gridheight = 2;
    		gc.insets = new Insets(5,5,5,5);
    		gc.anchor = GridBagConstraints.CENTER;
    		gc.fill = GridBagConstraints.BOTH;
    		add(verticalVelocityGraph, gc);
    	}
    	//paint method
    	public void paintComponent(Graphics g){
    		super.paintComponent(g);
    		this.setBackground(Color.GREEN);
    	}
    	//returning elevation method
    	public float getElevation(){
    		return elevation;
    	}
    	public float getAngle(){
    		return projectionAngle;
    	}
    	public float getProjectionSpeed(){
    		return projectionSpeed;
    	}
    	//state listener
    	public void stateChanged(ChangeEvent event) {
    		JSlider source = (JSlider) event.getSource();
    		
    		//setting elevation/projectionAngle or projectionSpeed value to new JSlider Value
    		if(source.getValueIsAdjusting() != true){
    			if(event.getSource() == height){
    				heightValue = String.valueOf(height.getValue());
    				elevation = Float.parseFloat(heightValue);
    				heightValues.setText("Height Value: "+heightValue);
    			}else if(event.getSource() == angle){
    				angleValue = String.valueOf(angle.getValue());
    				projectionAngle = Float.parseFloat(angleValue);
    				angleValues.setText("Angle Value: "+angleValue);
    			}else if(event.getSource() == speed){
    				speedValue = String.valueOf(speed.getValue());
    			 	projectionSpeed = Float.parseFloat(speedValue);
    			 	speedValues.setText("Speed Value: "+speedValue);
    			 }
    		}
    	}
    	//////////////////////////////////action listener//////////////////////////////////
    	public void actionPerformed(ActionEvent event){
    		System.out.println("sdfsd");
    		if(event.getSource().equals(start)){
    			System.out.println("start");
    			Thread animationThread = new Thread(new AnimationThread(projectileAnimationJPanel, controlPanelJPanel, getElevation(), getAngle(), getProjectionSpeed(), panelWidth, panelHeight, meter));
    			animationThread.start();
    		}else if(event.getSource().equals(reset)){
    			System.out.println("reset");
    			timePassed = "0";
    			time.setText("Time/s: "+timePassed);/////////////////////////java.lang.NullPointerException
    		}
    	}
    	//item listener
    	public void itemStateChanged(ItemEvent event){
    		
    	}
    	//setting values from ProjectileAnimationJPanel
    	public void settingValues(ProjectileAnimationJPanel p, ControlPanelJPanel c,int w, int h, float m){
    		projectileAnimationJPanel = p;
    		controlPanelJPanel = c;
    		panelWidth = w;
    		panelHeight = h;
    		meter = m;
    	}
    	//setting JLabel time
    	public void settingJLabelTime(double t){
    		timePassed = String.valueOf(t/1000);
    		System.out.println(t);////////////////prints out without a problem
    		time.setText("Time/s: "+timePassed);/////////////////////////java.lang.NullPointerException
    	}
    }
    Java Code:
    package projectileProgram;
    
    import javax.swing.JPanel;
    
    public class AnimationThread implements Runnable{
    	//variables
    	ProjectileAnimationJPanel projectileAnimationJPanel;
    	ControlPanelJPanel controlPanelJPanel;
    	JPanel panel = new JPanel();
    	double elevation, projectionAngle, projectionSpeed,  xVelocity, yVelocity, xPosition, yPosition, height, width, startTime, timeOfLastRun, timeBetweenRuns, meter;
    	double timePassed = 0;
    	//constructor 
    	public AnimationThread(ProjectileAnimationJPanel p, ControlPanelJPanel c, float e, float a, float s, int w, int h, float m){	
    		projectileAnimationJPanel = p;
    		controlPanelJPanel = c;
    		
    		//converting numbers to strings then to doubles
    		meter = Double.parseDouble(String.valueOf(m));
    		elevation = Double.parseDouble(String.valueOf(e));
    		projectionAngle = Double.parseDouble(String.valueOf(a));
    		projectionSpeed = Double.parseDouble(String.valueOf(s))*meter;
    		width = Double.parseDouble(String.valueOf(w));
    		height = Double.parseDouble(String.valueOf(h));
    		
    		//finding horizontal and vertical velocities
    		xVelocity = projectionSpeed*Math.cos(projectionAngle);
    		yVelocity = projectionSpeed*Math.sin(projectionAngle);
    		
    		//setting starting positions
    		xPosition = width/10-height/40;
    		yPosition = height-height/8-elevation*meter-height/40;
    		
    	}
    	public void run(){
    		//setting startTime
    		startTime = System.currentTimeMillis();	
    		
    		//loop
    		do{
    			//making thread sleep
    			try{
    				Thread.sleep(1);
    			}catch(Exception e){}
    			
    			//setting time
    			timeOfLastRun = timePassed;
    			timePassed = System.currentTimeMillis()- startTime;
    			timeBetweenRuns = timePassed - timeOfLastRun;
    			
    			//changing position
    			xPosition += xVelocity*timeBetweenRuns/1000;
    			yVelocity += 9.8*meter*timeBetweenRuns/1000;
    			yPosition += yVelocity*timeBetweenRuns/1000;
    			
    			//setting x and y positions in ProjectileAnimationJPanel class
    			projectileAnimationJPanel.settingXAndYPosisions(xPosition, yPosition);
    			///////////////////////setting time JLabel in ControlPanelJPanel class////////////////////////////
    			controlPanelJPanel.settingJLabelTime(timePassed);
    		}while(yPosition<7*(height/8)-height/40);
    	}
    }
    Last edited by peterhabe; 07-25-2010 at 11:07 AM.

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

    Default

    You are re-declaring the start and reset JButtons, and so while your actionPerformed method checks if the source is the start or reset JButton, these variables have never been constructed or displayed.

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

    Default

    When in doubt, simplify your code to find the error. Here for instance is your code simplified:

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    
    public class ControlPanelTest {
       private static void createAndShowUI() {
          JPanel panel = new ControlPanelJPanel();
    
          JFrame frame = new JFrame("ControlPanel Test");
          frame.getContentPane().add(panel);
          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();
             }
          });
       }
    }
    
    class ControlPanelJPanel extends JPanel implements ActionListener {
    
       JButton start, reset;
    
       public ControlPanelJPanel() {
          JButton start = new JButton("start");
          start.addActionListener(this);
    
          JButton reset = new JButton("reset");
          reset.addActionListener(this);
    
          add(start);
          add(reset);
       }
    
    
       public void actionPerformed(ActionEvent event) {
          System.out.println("sdfsd");
          if (event.getSource().equals(start)) {
             System.out.println("start");
          } else if (event.getSource().equals(reset)) {
             System.out.println("reset");
          }
       }
    
    }

    Now what happens if we don't re-declare the start and reset buttons?

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    
    public class ControlPanelTest {
       private static void createAndShowUI() {
          JPanel panel = new ControlPanelJPanel();
    
          JFrame frame = new JFrame("ControlPanel Test");
          frame.getContentPane().add(panel);
          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();
             }
          });
       }
    }
    
    class ControlPanelJPanel extends JPanel implements ActionListener {
    
       JButton start, reset;
    
       public ControlPanelJPanel() {
          //JButton start = new JButton("start");
          start = new JButton("start");
          start.addActionListener(this);
    
          //JButton reset = new JButton("reset");
          reset = new JButton("reset");
          reset.addActionListener(this);
    
          add(start);
          add(reset);
       }
    
    
       public void actionPerformed(ActionEvent event) {
          System.out.println("sdfsd");
          if (event.getSource().equals(start)) {
             System.out.println("start");
          } else if (event.getSource().equals(reset)) {
             System.out.println("reset");
          }
       }
    
    }
    It now works.

    Other suggestions:
    You don't want to call setBackground from within a paintComponent method but rather put it in your initialization code such as the constructor.
    You really don't want your GUI class to implement all these listeners. You wouldn't have the problem above if you simply used anonymous inner classes for your listeners

  4. #4
    peterhabe is offline Member
    Join Date
    Jul 2010
    Posts
    43
    Rep Power
    0

    Default

    Stupid mistake :(. Thanks for pointing that out Fubarable. One problem down one to go.
    Last edited by peterhabe; 07-24-2010 at 11:14 PM.

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

  6. #6
    peterhabe is offline Member
    Join Date
    Jul 2010
    Posts
    43
    Rep Power
    0

    Default

    I was re-declaring my time JLabel as well, which was again causing the problem. Two problems, two silly mistakes.

Similar Threads

  1. setText() problem
    By Jozo in forum Java Applets
    Replies: 4
    Last Post: 04-27-2010, 06:29 AM
  2. Jlabel update problem
    By fantasyme in forum AWT / Swing
    Replies: 3
    Last Post: 04-14-2010, 06:10 AM
  3. Replies: 2
    Last Post: 04-19-2009, 06:39 AM
  4. setText() problem
    By jls7168 in forum New To Java
    Replies: 2
    Last Post: 02-20-2009, 11:34 PM
  5. JLabel + GUI problem
    By tonyelaltaico in forum Java Applets
    Replies: 5
    Last Post: 02-03-2009, 02:46 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
  •