0

I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class. package acgregistration;

import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {


public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}



    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }



 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){


          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call 
   //acgMemberModel


          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }


 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox { 
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;


public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}



public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name, 
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another? Any help would be highly appreciated! Thank you!

3 Answers3

0

Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.

P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        MemberModel model = new MemberModel();
        StudentsToOutputListener outputListener
                = new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
        Window studentDialog = new StudentDialogBox(model);
        Window facilityDialog = new FacultyDialogBox();
        Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
        memberDialog.show();
    }
}

class Member {
    private String name;
    private int number;
    private String email;

    public Member(String name, int number, String email) {
        this.name = name;
        this.number = number;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", email='" + email + '\'' +
                '}';
    }
}

interface Window {
    void show();
}

interface Output {
    void output(List<Member> members);
}

interface Listener {
    void update();
}

class MemberDialogBox implements Window {
    private JFrame frame = new JFrame();
    private JComboBox<Window> choiceComboBox = new JComboBox<>();
    private JButton confirmButton = new JButton("Confirm");
    private JLabel selectLabel = new JLabel("Select your ACG Status");

    public MemberDialogBox(Window... windows) {
        for (Window window : windows) {
            choiceComboBox.addItem(window);
        }
        frame();
    }


    public void show() {
        frame.setVisible(true);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(210, 150);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(choiceComboBox);
        panel.add(confirmButton);
        panel.add(selectLabel);
        frame.add(panel);

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Window window = (Window) choiceComboBox.getSelectedItem();
                window.show();
                frame.dispose();
            }

        });
    }

}

class StudentDialogBox implements Window, Listener, Output {
    private JTextField nameField = new JTextField("", 20);
    private JTextField emailField = new JTextField("", 20);
    private JTextField numberField = new JTextField("", 20);
    private JButton confirmButton = new JButton("Confirm");
    private JButton saveButton = new JButton("Save students to file");
    private JFrame frame;
    private JList<Member> list = new JList<>();
    private MemberModel model;


    public StudentDialogBox(MemberModel model) {
        this.model = model;
        model.addListener(this);
        frame();
    }


    public void show() {
        frame.setVisible(true);
    }


    public void output(List<Member> members) {
        list.setListData(members.toArray(new Member[]{}));
    }


    public void update() {
        model.outputStudentsTo(this);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(nameField);
        panel.add(emailField);
        panel.add(numberField);
        panel.add(confirmButton);
        panel.add(list);
        panel.add(saveButton);
        frame.add(panel);

        saveButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.showSaveDialog(frame);
                File selectedFile = fileChooser.getSelectedFile();
                Output output = new FileOutput(selectedFile);
                model.outputStudentsTo(output);
            }
        });

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String number = numberField.getText();
                String email = emailField.getText();
                Member member = new Member(name, Integer.valueOf(number), email);
                model.addNewStudent(member);
            }
        });

    }


    public String toString() {
        return "Student";
    }
}

class FacultyDialogBox implements Window {

    public void show() {
        System.out.println("you need to implement FacultyDialogBox " +
                "in similar way than StudentDialog box");
    }


    public String toString() {
        return "Faculty/Stuff";
    }
}


class MemberModel {
    private List<Member> students = new ArrayList<>();
    private List<Member> stuff = new ArrayList<>();
    private List<Listener> listeners = new ArrayList<>();

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    private void notifyListeners() {
        for (Listener listener : listeners) {
            listener.update();
        }
    }

    public void addNewStudent(Member member) {
        students.add(member);
        notifyListeners();
    }

    public void addNewStuff(Member member) {
        stuff.add(member);
        notifyListeners();
    }

    public void outputStudentsTo(Output output) {
        output.output(Collections.unmodifiableList(students));
    }

    public void outputStuffTo(Output output) {
        output.output(Collections.unmodifiableList(stuff));
    }
}

class FileOutput implements Output {
    private final File destination;

    public FileOutput(File destination) {
        this.destination = destination;
    }

    public void output(List<Member> members) {
        try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
            for (Member member : members) {
                file.write(member.toString());
                file.write("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

class StudentsToOutputListener implements Listener {
    private final MemberModel model;
    private final Output output;

    public StudentsToOutputListener(MemberModel model, Output output) {
        this.model = model;
        this.output = output;
        model.addListener(this);
    }

    public void update() {
        model.outputStudentsTo(output);
    }
}

I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.

fxrbfg
  • 1,756
  • 1
  • 11
  • 17
  • thank you so much! but I have created a JCombo Dialog class with an action event listener that runs the student class when selected or faculty class when selected. - so i wouldn't understand how to proceed. Could I post the full code so you can give me feedback? – desperateundergrad Dec 05 '17 at 19:18
  • @desperateundergrad , yes update this or ask another question when it's not much related to already presented here and provide me a link – fxrbfg Dec 05 '17 at 20:09
  • Great! one question, how do we print the lists? When i click confirm, nothing happens. I want to be able to implement a System.out.print of the lists and save them in a .txt file. – desperateundergrad Dec 06 '17 at 15:13
  • @desperateundergrad better to withdraw list to window, when we deals with windows here instead of console. – fxrbfg Dec 06 '17 at 16:29
  • PERFECT!! Thank you so much! You have saved me! Is there a way to automatically save the details to a default file? – desperateundergrad Dec 07 '17 at 08:24
  • Also, how do I put a JLabel Name, Email and ID, right next to the JTextFields? so that the panel has what the user should input. For example (Name: [ JTextField ]) (Email: [ JTextField ]) ( ID: [ JTextField ]) [Confirm] [Save Text To File] – desperateundergrad Dec 07 '17 at 08:47
  • @desperateundergrad yes, when you want to save to default file it's very easy to add another one listener to Model, it's power of oop. when you need to introduce labels right or left of input fields better to use GridLayout – fxrbfg Dec 07 '17 at 09:09
  • @desperateundergrad answer updated, i add default autosave to file for every change of model. Since i helped you a lot and did almost entire work for you, mark my answer as accepted. – fxrbfg Dec 07 '17 at 09:38
0

You're talking about data binding. I recently posted a demo that shows how to do what you need as an answer to this question: Switching JPanels moves content diagonally

Essentially, the GUI passes information to the model and vice-versa by events, typically Property Change Events but there are lots of options you could choose. The process would look like this:

  1. User enters a value in a field
  2. The field fires a property change event for the property "value" when it looses focus
  3. The GUI (or controller class) listens for the property change event and fires another event, such as a Vetoable Change Event.
  4. The Model (or controller) listens for the Vetoable change and validates the value, saving the "state" in the correct place. If the validation fails, it fires an exception.
  5. The GUI checks for the veto exception and reverts the field if required.

A similar approach can allow the model to send property change requests to the GUI to update the value of fields.

The benefit of using these events is that it keeps the GUI simple, separates the model from the representation and makes it easier to replace/duplicate the GUI with another technology rather easily.

Michael McKay
  • 650
  • 4
  • 11
-2

Have you tried making the variables you want to share between classes public static?

El Fufu
  • 66
  • 1
  • 9