Tyler
Tyler

Reputation: 39

How to create my save button

So I created a simple Employee class that will store and retrieve data that has been entered by the user. For the save portion I created a separate class in order to save the file. Should I have created the read and write functions inside of the employee class or should I keep them as their own classes?

Here is my code for the 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);
    }
}

Upvotes: 0

Views: 162

Answers (1)

DarkV1
DarkV1

Reputation: 1776

Structuring your codes into different classes/ packages provides organization and in this case, it would be the best solution.

RULES when Seperating into Classes://Credit to Link below as it better describes the conditions

-Single Responsability Principle

-Open Closed Principle

-Liskov substitution principle

-Interface segretation principle

-Dependency Inversion principle

Heres a link to the repeat question:

When should I separate my code into separate classes?

Upvotes: 3

Related Questions