Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
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.

Java
  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.

Java
/*
 * 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
Updated 10-Oct-12 20:24pm
v2
Comments
Ashraff Ali Wahab 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 10-Oct-12 11:38am    
I want that to prevent the variables are being accessed by the UI directly!
Ashraff Ali Wahab 10-Oct-12 15:02pm    
You already set it as private and you'll not be able to access it.
Chiranthaka Sampath 11-Oct-12 0:12am    
I have used getters( ) and setters( ) to access those variables. That is why it is called as Encapsulation.

- 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.

Java
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:
Java
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
Java
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.
 
Share this answer
 
v2
Comments
Chiranthaka Sampath 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. 11-Oct-12 7:33am    
see the Edit.
Chiranthaka Sampath 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 11-Oct-12 9:03am    
Ok pal I will try that code!
Chiranthaka Sampath 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());
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:
Java
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:
Java
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.

Java
public class Enter_Stud_Details extends JPanel {
// some parts will have to move one layer up to the MainWindow
}
 
Share this answer
 
Comments
Chiranthaka Sampath 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. 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 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. 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 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();
}

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