具有2个类的Java封装项目. [英] Java Encapsulation Project with 2 classes.

查看:60
本文介绍了具有2个类的Java封装项目.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中创建了2个类
1.StudVariables.Java-包含使用私有
的所有变量 标识符.在这里,我创建了所有的get()&具有相关
的set() 变量.

在这里我使用了私有标识符,因为我想隐藏一些细节
此类中的其他成员(封装).的源代码是
在下面.

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.此类用于创建用于获取和检索数据的用户界面
来自程序的用户.这是使用Swint框架开发的.
源代码在下面说明.



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
}




但是我的问题是如何将值插入
中的变量中 第一类使用第二类中的用户界面.你能不能尝试
也可以解决我的问题

谢谢
Chiranthaka




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

推荐答案

-摆脱主要功能
主要功能只是代码运行的起点.不多也不少.
因此,它只需要做一件事:启动代码.

- 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); 
}


就这样.完整的其余部分属于Enter_Stud_Details类.

-您的GUI使用对象存储数据.那挺好的!进入真正编程的第一步.
要解决该对象,GUI需要知道它:


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
}


现在,您可以将GUI设置为初始值,也可以在其中存储更改的值. (*)

要在其中存储数据,您需要命令GUI进行存储.您在其中有一个计算"按钮和一个ActionListener-太好了!函数jButton1ActionPerformed是为学生设置新值的地方.也是让学生对象(!)计算的地方.


(*)扩展此对象可以使用一个主要对象,该对象由main函数初始化,并持有学生列表" ...这是您的常规数据存储区.
常见的模式是外观模式 [


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[^].



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());
}



我建议给文本字段更好的名称,例如"txtName",这样可以更容易地识别在那里期望的内容.



I suggest to give the textfields better names like "txtName", so it''s easier to identify what is to expect there.


要获取独立于GUI的应用程序,您必须进行更改应用程序的生命周期.

当前,只要JFrame"Enter_Stud_Details"可见,您的应用程序仍然有效.

现在,您需要一个更高的实例来控制生命周期.只要此更高的实例可用,该应用程序就在运行.
关闭MainWindow时,应用程序结束(触发Application.close()进行其他操作).
那将启动一个窗口,其中将显示不同的视图":
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
    }

}



该窗口应该是一个JFrame.我们称它为MainWindow:



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);
    }  



对于MainWindow,您应该考虑一个Coolbar(顶部的按钮,这些按钮将转到BorderLayout.North
因此,您当前的"Enter_Stud_Details"将被转换为JPanel,并显示在所有顶部的JFrame "MainWindow"中.



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
}


这篇关于具有2个类的Java封装项目.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆