Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created 3 classes. 1st class is used to store variable. other classes are use to input data and to display data.

1st Class

Java
public class Student {

    /**
     * @param args the command line arguments
     */
    
    private String strStudNo;
    private String strStudName;
    private int iMaths;
    private int iScience;
    private int iEnglish;

    public String getStrStudNo() {
        return strStudNo;
    }

    public void setStrStudNo(String strStudNo) {
        this.strStudNo = strStudNo;
    }

    public String getStrStudName() {
        return strStudName;
    }

    public void setStrStudName(String strStudName) {
        this.strStudName = strStudName;
    }

    public int getiMaths() {
        return iMaths;
    }

    public void setiMaths(int iMaths) {
        this.iMaths = iMaths;
    }

    public int getiScience() {
        return iScience;
    }

    public void setiScience(int iScience) {
        this.iScience = iScience;
    }

    public int getiEnglish() {
        return iEnglish;
    }

    public void setiEnglish(int iEnglish) {
        this.iEnglish = iEnglish;
    }
    
    public double  calTotal(){
        return (getiMaths()+getiScience()+getiEnglish());   
    }
    
    public double  calAverage(){
        
        return (calTotal()/3);  
    }
    
    public String findGrade(){
        
        String strGrade = new String();
        
        if (calAverage()>70){
            
            strGrade = "A";
            
        }else if(calAverage()>60){
            
            strGrade = "B";
            
        }else if (calAverage()>50){
            
            strGrade = "S";
            
        }else{
            strGrade = "Fail";
        }
        return strGrade;
    }
    
    public static void main(String[] args) {
        // TODO code application logic here
    }
}


2nd Class

This is class is designed using the Swing JPanel object and used to enter StudNo, StudName, Marks for 3 subjects. This also include 2 buttons as btnCalculate and btnCancel. This user interface was developed using Java swing class by auto generating. When the btnCalculate clicks the data within the textfields will be assign to the 1st classes variables. And at there the calculations will be done using 3 methods.

Java
 import javax.swing.JFrame;

/**
 *
 * @author Administrator
 */
@SuppressWarnings("serial")
public class EnterDetails extends javax.swing.JPanel {

    /**
     * Creates new form EnterDetails
     */
    
    public static void main(String[] args) {
        
        JFrame oJFrame = new JFrame();
        oJFrame.getContentPane().add(new EnterDetails());
        oJFrame.setDefaultCloseOperation(oJFrame.EXIT_ON_CLOSE);
        oJFrame.setSize(500, 500);
        oJFrame.setVisible(true);
        
    }
    public EnterDetails() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
                    

    private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        
        JPanelOnJFrameMulti oJpanelOnJFrameMulti = new JPanelOnJFrameMulti();
        
        oJpanelOnJFrameMulti.setStrStudNo(txtStudId.getText());
        oJpanelOnJFrameMulti.setStrStudName(txtStudName.getText());
        
        oJpanelOnJFrameMulti.setiMaths(Integer.parseInt(txtMaths.getText()));
        oJpanelOnJFrameMulti.setiScience(Integer.parseInt(txtScience.getText()));
        oJpanelOnJFrameMulti.setiEnglish(Integer.parseInt(txtEnglish.getText()));
        
        oJpanelOnJFrameMulti.calTotal();
        oJpanelOnJFrameMulti.calAverage();
        oJpanelOnJFrameMulti.findGrade(); 
       
        DisplayDetails oDisplayDet = new DisplayDetails();
        
        oDisplayDet.setVisible(true);
        
        
        JFrame oJFDisDet = new JFrame();
       
      
        oJFDisDet.getContentPane().add(new DisplayDetails());
        oJFDisDet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        oJFDisDet.setSize(500, 500);
        oJFDisDet.setVisible(true);    
        
    }                                            

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnCalculate;
    private javax.swing.JButton btnCancel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtEnglish;
    private javax.swing.JTextField txtMaths;
    private javax.swing.JTextField txtScience;
    private javax.swing.JTextField txtStudId;
    private javax.swing.JTextField txtStudName;
    // End of variables declaration                   
}


3rd Class

The other user interface that used to view the final results of the calculations i.e. Total marks, Average marks and the grade. When the btnCalculate clicks the result should pass to the 3rd class i.e. DisplayInfo JPanel class. My Problem is when I click the btnCalculate button it does calculate the total marks, average marks and the grade. The 3rd class i.e. the DisplayInfo JPanel form will also displayed but the data did not pass the text fields were empty.

I do not know what I have done wrong? Please can someone help me.

Update

Java
public class DisplayDetails extends JPanel {

    /**
     * Creates new form DisplayDetails
     */
    
    
    public void load(){
        
      Student oStudent = new Student();
      txtStudId.setText(oStudent.getStrStudName());
      txtStudId.setText(oStudent.getStrStudNo());
      
      txtTotal.setText(Double.toString(oStudent.calTotal()));
      txtAverage.setText(Double.toString(oStudent.calAverage()));
      
      txtGrade.setText(oStudent.findGrade()); 
        
    }
   
    public DisplayDetails() {
        initComponents();
    }
    
   // DisplayDetails.

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          

    }// </editor-fold>                        
    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtAverage;
    private javax.swing.JTextField txtGrade;
    private javax.swing.JTextField txtStudId;
    private javax.swing.JTextField txtStudName;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration                   
}


THank You
Chiranthaka.
Posted
Updated 6-Dec-17 13:58pm
v3

Do not place your data in the JPanel:

Java
public static void main(String[] args) {

        MyData oData = new MyData();// create data object

        JFrame oJFrame = new JFrame(); 
        oJFrame.getContentPane().add(new EnterDetails(oData));// pass Object to GUI Component as an argument
        oJFrame.setDefaultCloseOperation(oJFrame.EXIT_ON_CLOSE);
        oJFrame.setSize(500, 500);
        oJFrame.setVisible(true);
        
    }


and please rip that main-function out of the JPanel. the main function belongs into a seperate class:

Java
public class Application{
      public static void main(String[] args) {

        // create data object
        MyData oData = new MyData();

        JFrame oJFrame = new JFrame(); 
        oJFrame.getContentPane().add(new EnterDetails(oData));// pass Object to GUI Component as an argument
        oJFrame.setDefaultCloseOperation(oJFrame.EXIT_ON_CLOSE);
        oJFrame.setSize(500, 500);
        oJFrame.setVisible(true);
        
    }
}


That class "Application" defines your application's lifecycle.
The GUI components are only for visual representation. You can create, change and destroy them whenever you need to.
 
Share this answer
 
Comments
Chiranthaka Sampath 3-Jul-13 6:01am    
Ok pal then what does MyData class do? Is it similar to the "public class JPanelOnJFrameMulti{}" in my program that stores values?
TorstenH. 3-Jul-13 7:07am    
Yes, please split the class and seperate GUI and data. That is a common design in applications, here in a light version, sometimes (*) in an enhanced version and in big frameworks in a heavy version.

(*) Java SE Application Design With MVC
Chiranthaka Sampath 3-Jul-13 7:18am    
My GUIs are in separate classes and the variables are in a separate class. I cannot understand what you are telling me sir!
Chiranthaka Sampath 3-Jul-13 7:34am    
Ok sir I have deleted the main() from the JPanel Forms. Then I have executed the 1st class and it was a sucess. But as the previous attempts the results from the 1st class i.e. calTotal(),calAverage() and the findGrade() will return any answers but the 2nd GUIs doesn't seem to grab that results from the 1st class i.e. the variables and the other calculations are reside. I can't find the problem please help me.
TorstenH. 3-Jul-13 7:46am    
You need to have more than one student - and then to setz the values to the student object via the set methods.

Please be aware that you have to much main-methods in there. only one main method should be used. it#s the entry point for the machine to execute the code - it would cause confusion if the code can be accessed from different locations.

I have solved my problem by using the static keyword. I changed all the variables in the Student class from non-static to static content
and also I changed all the getter () and setter () from non-static to static content.

Then the access of the variables and other methods are as the below.

Java
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
       // TODO add your handling code here:

       Student.setStrStudNo(txtStudId.getText());
       Student.setStrStudName(txtStudName.getText());
       Student.setiMaths(Integer.parseInt(txtMaths.getText()));
       Student.setiScience(Integer.parseInt(txtScience.getText()));
       Student.setiEnglish(Integer.parseInt(txtEnglish.getText()));

       Student.calTotal();
       Student.calAverage();
       Student.findGrade();

       DisplayDetails oDisplayDet = new DisplayDetails();

       oDisplayDet.setVisible(true);

       JFrame oJFDisDet = new JFrame();

       oJFDisDet.getContentPane().add(new DisplayDetails());
       oJFDisDet.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       oJFDisDet.setSize(500, 500);
       oJFDisDet.setVisible(true);

   }


   private void load(){

     txtStudId.setText(Student.getStrStudNo());
     txtStudName.setText(Student.getStrStudName());

     txtTotal.setText(Double.toString(Student.calTotal()));
     txtAverage.setText(Double.toString(Student.calAverage()));

     txtGrade.setText(Student.findGrade());

     repaint();

   }

   public DisplayDetails() {
       initComponents();

       this.load();

   }
 
Share this answer
 
Comments
TorstenH. 5-Jul-13 5:41am    
Kind of evil do do it like that. You might be forced to code Visual Basic in hell for this ;)

You have getter and setters - as long as you pass the Student object to the panel, it should be able to access the getters and to load the data.
If done after creating the panel, the panel must be updated and forced to lay out newly to display the data.
Chiranthaka Sampath 5-Jul-13 10:21am    
Then what should I do sir ? Because I tried that and couldn't get the results to the 2nd JPanel() Then what should I do? Please give me some help.
Short solution.
I used one student and the Observer pattern[^] (*) , which makes it pretty slick.
You're welcome to play with it and extend the basic schema.

(*) bookmark that, Lars Vogel has pretty good tutorials.

Java
public class Application extends JFrame{

	private ShowPanel oShowPanel;
	private EnterPanel oEnterPanel;
	
	public Application(){
		super("Example");
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setSize(200, 300);
		this.ignition();
		this.setVisible(true); // makes itself visible
	}

	private void ignition() {
		this.setLayout(new GridLayout(2, 1));

		// create data object
		Student oStudent = new Student();
		// pass Object to JPanels
		oEnterPanel = new EnterPanel(oStudent);
		oShowPanel = new ShowPanel(oStudent);
		
		// Student is observed by ShowPanel
		oStudent.addObserver(oShowPanel);
		
		// add Panels to GUI
		this.add(oEnterPanel, 0);
		this.add(oShowPanel, 1);
	}

	/**
	 * <p>simple JPanel, which owns a text field and a button.<br>
	 * Clicking the button sets the name of the Object Student.</br></p>
	 */
	public class EnterPanel extends JPanel{

		public EnterPanel(Student oStudent){
			super();
			this.ignition(oStudent);
		}

		private void ignition(final Student oStudent) {
			this.setLayout(new GridLayout(3, 1));
			
			this.add(new JLabel("Enter name:"));
			final JTextField oText = new JTextField();
			this.add(oText);
			JButton oButton = new JButton("Click me hard!");
			oButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent oEvent) {
					oStudent.setName(oText.getText());
				}
			});
			this.add(oButton);
		}
	}
	
	/**
	 * <p>ShowPanel observes the data Object Student. <br>
	 * When notified, it updates the Label to present the name.</br></p>
	 */
	private class ShowPanel extends JPanel implements Observer {
		
		JLabel oLabel;
		public ShowPanel(Student oStudent){
			this.ignition(oStudent);
		}

		private void ignition(Student oStudent) {
			this.setLayout(new GridLayout(2, 1));
			this.add(new JLabel("Name is:"));
			
			oLabel= new JLabel();
			this.add(oLabel);
		}

		@Override
		public void update(Observable oObservable, Object oObject) {
			// we do not figure who kicked us, we just repaint.
			System.out.println("TEST");
			Student oStudent = ((Student)oObservable); // cast
			this.oLabel.setText(oStudent.getName()); // renew value
		}
	}
	
	/**
	 * <p>data Object, which holds the name of one student.<br>
	 * Classic POJO which extends Observable. The setter notifies the Observers.</br></p>
	 */
	public class Student extends Observable{
		private String strName;
		public Student() { /* doany() */}
		
		public void setName(String strName) {
			this.strName = strName;
			setChanged();
			notifyObservers();
		}

		public String getName() {
			return strName;
		}
	}
	
	// entry point
	public static void main(String[] args) {
		new Application(); // create Object
	}
}
 
Share this answer
 
v2
Comments
Chiranthaka Sampath 8-Jul-13 2:18am    
Ok sir I solved my problem using the solution you have provided. Thanx anyway. I have bookmarked the tutorial from Lars Vogal and I appreciate your opinion really.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900