Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Homework
I have created 2 classes in java
1.StudVariables.Java - This contains all the variable that uses the private
identifier. In here I have created all the get() & set() with relevant
variables.

In here I have used private identifier because I wanted to hide some details
in this class to other members (encapsulation). The source code for that is
at the below.

  public class StudVariables {
    
    private String StudNo;
    private String StudName;
    private double Maths;
    private double English;
    private double Science;
    
    private double Total;
    private double Average;
 
    public String getStudNo() {
        return StudNo;
    }
 
    public void setStudNo(String StudNo) {
        this.StudNo = StudNo;
    }
 
    public String getStudName() {
        return StudName;
    }
 
    public void setStudName(String StudName) {
        this.StudName = StudName;
    }
 
    public double getMaths() {
        return Maths;
    }
 
    public void setMaths(double Maths) {
        this.Maths = Maths;
    }
 
    public double getEnglish() {
        return English;
    }
 
    public void setEnglish(double English) {
        this.English = English;
    }
 
    public double getScience() {
        return Science;
    }
 
    public void setScience(double Science) {
        this.Science = Science;
    }
 
    public double getTotal() {
        
        Total = Maths + Science + English;
        return Total;
    }
 
    public void setTotal(double Total) {
        this.Total = Total;
    }
 
    public double getAverage() {
        
        Average = Total/3;
        return Average;
    }
 
    public void setAverage(double Average) {
        this.Average = Average;
    }   
}

 
2. This class used to create the user interface to get and retrieve the data
from the user of the program. This is developed using the Swint framework.
The source code is stated at the below.
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
/**
 *
 * @author Administrator
 */
public class Enter_Stud_Details extends javax.swing.JFrame {
 
    /**
     * Creates new form Enter_Stud_Details
     */
    public Enter_Stud_Details() {
        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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
 
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jTextField6 = new javax.swing.JTextField();
        jTextField7 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jLabel1.setText("Student No");
 
        jLabel2.setText("Student Name");
 
        jLabel3.setText("Maths");
 
        jLabel4.setText("Science");
 
        jLabel5.setText("English");
 
        jLabel6.setText("Total");
 
        jLabel7.setText("Average");
 
        jButton1.setText("Calculate");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jButton2.setText("Cancel");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                    .addComponent(jTextField2)
                    .addComponent(jTextField3)
                    .addComponent(jTextField4)
                    .addComponent(jTextField5)
                    .addComponent(jTextField6)
                    .addComponent(jTextField7))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(28, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        
        
        
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Enter_Stud_Details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Enter_Stud_Details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Enter_Stud_Details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Enter_Stud_Details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Enter_Stud_Details().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    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.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    // End of variables declaration
}
 

But my problem is how I able to insert the values to the variables in the
1st class using the user interface in the 2nd class. Could you please try to
solve my problem as well
 
Thank you
Chiranthaka
Posted 10-Oct-12 6:06am
Edited 10-Oct-12 21:24pm
TorstenH.33.8K
v2
Comments
Ashraff Ali Wahab at 10-Oct-12 11:22am
   
You have the button action Performed event.Instanitate the StudVariables class and set the values of the varaible from the user interface.
 
But why you want to set the values in the StudVariables class?
Chiranthaka Sampath at 10-Oct-12 11:38am
   
I want that to prevent the variables are being accessed by the UI directly!
Ashraff Ali Wahab at 10-Oct-12 15:02pm
   
You already set it as private and you'll not be able to access it.
Chiranthaka Sampath at 11-Oct-12 0:12am
   
I have used getters( ) and setters( ) to access those variables. That is why it is called as Encapsulation.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

- get rid of the main function
The main function is just a starting point for your code to run. It's no more and not less.
So it should only have one thing to do: start your code.
 
  
public static void main(String args[]) {
Enter_Stud_Details oGUI = new Enter_Stud_Details();
oGUI.serVisible(true); 
}

That's all. The complete rest belongs to the class Enter_Stud_Details.
 
- Your GUI uses an Object to store the data. That's good! First step into real programming.
To address the object, the GUI needs to know it:
public class Enter_Stud_Details extends javax.swing.JFrame {
 
private StudVariables oStudent = new StudVariables();  
// rest of code
}
Now you can set the GUI to the initial value and also store changed values in there. (*)
 
To store data in there you need to command the GUI to do so. You have a button "calculate" in there and an ActionListener - great! The function jButton1ActionPerformed is the place where the new values are set to the student. Also the place to let the student object(!) calculate.
 

(*) Extending this one could use a major Object, initialized by the main function, holding a List of Students...there is your general data storage.
A common pattern for that is the facade pattern[^].
 
Edit:
 
You have an instance of the StudVariables in the GUI
 
private StudVariables oStudent = new StudVariables();  
 
// ... other code 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  // TODO add your handling code here:
  oStudent.setStudName(jTextField2.getText());
}
 
I suggest to give the textfields better names like "txtName", so it's easier to identify what is to expect there.
  Permalink  
v2
Comments
Chiranthaka Sampath at 11-Oct-12 7:06am
   
I have a small doubt! How can I possibly do assign values to the variables in StudVariables class using the GUI in the Enter_Stud_Details class? I am new to java so give me some good advice for this. Thanks
TorstenH. at 11-Oct-12 7:33am
   
see the Edit.
Chiranthaka Sampath at 14-Oct-12 10:11am
   
I saw the edit & I want more. That will be stated at the below
 
When I coding the program I wanted to get data from the jTextField3.text(). But it requires to convert to the Double data type from the String data type. The coding will be as the following. oStudent.setMaths(jTextField3.getText());
 
After that I want the following also
Now how can I do the calculations?
Chiranthaka Sampath at 11-Oct-12 9:03am
   
Ok pal I will try that code!
Chiranthaka Sampath at 14-Oct-12 4:05am
   
When I coding the program I wanted to get data from the jTextField3.text(). But it requires to convert to the Double data type from the String data type.
 
The coding will be as the following.
 
oStudent.setMaths(jTextField3.getText());
TorstenH. at 14-Oct-12 10:59am
   
You need to parse the String:
 
String strValue = jTextField3.getText();
double dValue = Double.parseDouble(strValue);
That can woirk - or if entered text is not a number, will throw a NumberFormatException. So better to surround it with a try/catch.
Chiranthaka Sampath at 15-Oct-12 3:54am
   
I am using the encapsulation so how can I able to assign the values using the GUI in the Enter_Stud_Details.java to the private variable in the StudVariables.java. Also if you can please send me a link to an application source code location that I can find some good examples like this. Thanx for all your comments and helps.
TorstenH. at 15-Oct-12 4:18am
   
you are making fun right? You already assigned the values to the Student object.
Now you need to add another function there and call it.
After that assign the new value to the result text box and call for a layout - that's it.
 
I strongly recommend to by a book. Check out Addison Wesley books, those are mostly written very good.
Chiranthaka Sampath at 15-Oct-12 5:10am
   
Ok then which book I should buy? I have no idea what to select!
Chiranthaka Sampath at 14-Oct-12 5:41am
   
Now how can I do the calculations? Please try to help me!
TorstenH. at 14-Oct-12 10:59am
   
Calculation should be done by the object Student - add a function which does the calculation and call it from the GUI.
Chiranthaka Sampath at 16-Oct-12 2:37am
   
Ok pal then assume that I am creating a function or method called
"public double Total(){
//The calculating statement
};"
 
What should be the calculating statement? I think I am not joking with you but I realy apologize if I made you upset! Sorry
TorstenH. at 16-Oct-12 3:17am
   
whatever you want to calculate, you'll figure it out. The method name needs to start with small letter, capital letter is exclusive to class names.
Chiranthaka Sampath at 16-Oct-12 22:11pm
   
Ok then I want to calculate the total of the 3 subjects(maths, science, english). They have being stated at the 01. studVariable.java class file. I am accessing those variable from the 02. enter_stud_details.java class using reference variables and I will calculate the total using the public double total( ){ //the calculating statement. } method or the function. but my problem is how can I use these reference variables to calculate the total within this function? I don't think that I am annoying you! Sorry!
Chiranthaka Sampath at 18-Oct-12 2:16am
   
I really want a help about this pal!
TorstenH. at 18-Oct-12 2:41am
   
to sum 3 double values and divide by 3 - what is the problem?
Chiranthaka Sampath at 22-Oct-12 11:39am
   
Ok then where should I put that function? In StudVariables.java or in the EnterStudDetails.java (the user interface)?
TorstenH. at 23-Oct-12 2:29am
   
StudVariables is the right spot.
Chiranthaka Sampath at 23-Oct-12 4:58am
   
Can I use the set( ) or get () methods to do that?
Chiranthaka Sampath at 24-Oct-12 2:17am
   
Ok I have created the methods or the functions as the below at the StudVariables.java class. Would you kind to confirm that these are correct or not?
 
public void setTotal(double Total) {

Total = Maths + Science + English;
this.Total = Total;
}
 

public void setAverage(double Average) {

Average = Total/3;
this.Average = Average;
}
TorstenH. at 24-Oct-12 4:43am
   
All you need is to calculate with the values that are already set:
 
public double calculateAverage() {
return ( (getMaths() + getScience() + getEnglish()) / 3 );
}

 
Call that from the GUI with "oStudent.calculateAverage()" and it will return the current average value.
 
And PLEASE do not use starting capital letters for variables. You will run into problems, as only classes are written with Capital letter. Your app will figure some class with such a name and try to use that one instead of using your variable. "Maths" is already pretty close to "Math". One lucky hit and you'll loose one life in this game.
It's pretty neat to use a small letter in front indicating the type if variable: dScience (it's a double), iNumber (it's a int) or oStudent(it's a object). It's easier to work with them that way. It's called Hungarian Notation. Not new and a bit out of style, but still worth to follow.
Chiranthaka Sampath at 20-Nov-12 5:52am
   
OK then I have solved my problem with your kind help and now I want to display the results of the 2 methods in a different user interface(jFrame form) and how am I able to do that?
TorstenH. at 20-Nov-12 9:26am
   
I have added another answer (should be Solution 2) to get written up clearly.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

To get a GUI independent application, you will have to change the life cycle of your application.
 
Currently your application is alive as long as the JFrame "Enter_Stud_Details" is visible.
 
Now you need to have a higher instance, that controls life cycle. The application is running as long as this higher instance is available.
The Application ends when MainWindow is closed (triggers Application.close() for additional action).
That one starts a Window in which the different "views" are to be shown:
public class Application{
 
    public Application(){
        this.open();
    }
 
    public static void main(String[] args) {
        MainWindow oMW = new MainWindow("Title");
        oMW.open();
    }
 
    private void open() {
        // additional opening action like triggering a facade
    }
 
    public void close(){
        // additional closing actions like saving state
    }
 
}
 
 
That Window should be a JFrame. Let's call it MainWindow:
public class MainWindow extends JFrame {
 
    public MainWindow(String title) throws HeadlessException {
        super(title);
    }
 
    public void open() {
        setLayout();
        createGUI();
        this.setVisible(true);
    }
 
    private void setLayout() {
        this.setLayout(new BorderLayout());
    }
 
    private void createGUI() {
        Enter_Stud_Details oDetails = new Enter_Stud_Details();
        this.add(oDetails);
    }  
 
 
For the MainWindow you should think about a coolbar (the buttons at the top, those would go to BorderLayout.North
So your current "Enter_Stud_Details" will be converted to be a JPanel, presented in a JFrame "MainWindow" that is on top of all.
 
public class Enter_Stud_Details extends JPanel {
// some parts will have to move one layer up to the MainWindow
}
  Permalink  
Comments
Chiranthaka Sampath at 23-Dec-12 3:23am
   
If I use a menu bar then it should be in the JFrame I think it is the correct way! Then how am I able to open a JPanel using a menu? I already tried the follwoing statement
 
JPanel Enter_Stud_Details oEnterStud = new Enter_Stud_Details();
 
oEnterStud.setVisible = true;
 
But unfortunately the Jpanel did not opend! Then what should I do to open the JPanel? If you have time please try to solve my problem again!
 
Thank You
Chiransj
TorstenH. at 23-Dec-12 3:38am
   
How did the IDE accept oEnterStud.setVisible = true; ?
You can open a second JFrame or a Dialog (e.g. to present a message).
 
When you use a Jframe, you need to be aware of the DefaultCloseOperation - depending on what you set there, the application lifecycle will end when you close the window.
 
Please follow the links and read about all these topics.
Chiranthaka Sampath at 23-Dec-12 15:20pm
   
Sorry my mistake the following statement is declared at the JFrame class MainWindow
 

private Enter_Stud_Details oEntStuDet = new Enter_Stud_Details();
 
private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:

oEntStuDet.setVisible(true);

}
 
But when I click the menu the Enter_stud_details JPanel form didn't opened up! So what I have done wrong here? I used all your code set properly! If you have please try to solve my problem!
TorstenH. at 24-Dec-12 3:52am
   
To make it visible you have to repaint the parent component - in this case it seems like it is the MainWindow.
Please call
 
MainWindow.this.repaint();
 
in the anonymous moue event.
Chiranthaka Sampath at 25-Dec-12 12:10pm
   
I tried that man nothing happened! At the below the coding is resides.
 
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.oInvenDet.setVisible(true);
MainWindow.this.repaint();
}
Chiranthaka Sampath at 25-Dec-12 13:01pm
   
In your Solution 02 you have mentioned that some parts will have to move one layer up to the MainWindow from the Enter_Stud_details jPanel form! What they will be? I am very frustrated about this matter by keep questioning this matter and also I think you feel the same! If you can please post the whole answer and that will be my last request!
 
Thank You
Chiransj
Chiranthaka Sampath at 28-Jun-13 3:48am
   
Casting TextField value to an integer variable can be done as this.
 
oStudent.setMaths(Integer.parseInt(txtMaths.gettext()));
 
Casting Integer to a TextField value.
txtTotal.setText(Integer.toString(oStudent.calTotal()));
TorstenH. at 28-Jun-13 9:47am
   
txtTotal.setText("" + oStudent.calTotal());
 
much simpler.
Chiranthaka Sampath at 30-Jun-13 9:52am
   
Then how am I able to cast the TextField value to an Integer? Because you have shown me a much simpler way to cast an Integer to String. Then there should be a much simpler way to do the same thing in the other way round.
TorstenH. at 1-Jul-13 2:30am
   
One could go for: new Integer(String) and use the Integer object.
By calling Integer.intValue() (there are also .doubleValue() and .floatValue() available) you can get a number value.

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

  Print Answers RSS
0 Marcin Kozub 330
1 OriginalGriff 256
2 Sergey Alexandrovich Kryukov 215
3 Praneet Nadkar 197
4 Richard MacCutchan 182
0 OriginalGriff 8,048
1 Sergey Alexandrovich Kryukov 7,287
2 DamithSL 5,614
3 Manas Bhardwaj 4,986
4 Maciej Los 4,910


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 20 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100