如何创建我的保存按钮

时间:2016-05-08 22:35:26

标签: java user-interface

所以我创建了一个简单的Employee类,用于存储和检索用户输入的数据。对于保存部分,我创建了一个单独的类来保存文件。我是否应该在employee类中创建读写函数,还是应该将它们保存为自己的类?

以下是我的GUI代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class EmployeeGui2 extends JFrame{

    private Employee employee;
    private FileRead read;
    private FileWrite write;
    private JButton storeEmployee;
    private JButton retrieveEmployee;
    private JTextField field;

    private static final int FRAME_WIDTH = 500;
    private static final int FRAME_HEIGHT = 500;


    public EmployeeGui2(){
        createComponents();
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
    }

    private void createComponents(){
        storeEmployee = new JButton("Store");
        storeEmployee.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                try {
                    write.write(employee);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        retrieveEmployee = new JButton("Retrieve");
        field = new JTextField(20);
        JPanel panel = new JPanel();
        panel.add(storeEmployee);
        panel.add(retrieveEmployee);
        panel.add(field);
        add(panel);
    }

    public static void main(String[] args){
        JFrame frame = new EmployeeGui2();
        frame.setTitle("Employee GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:3)

将代码构建到不同的类/包中可以提供组织,在这种情况下,它将是最佳解决方案。

分成课程时的规则: //感谢下面的链接,因为它更好地描述了条件

- 单一责任原则

- 开放封闭原则

-Liskov替代原则

- 接口分离原则

- 依赖倒置原则

下面是重复问题的链接:

When should I separate my code into separate classes?