Sorting and Adding to ArrayList - java

So here's my code, I am making a program that sorts text into object instances that are created automatically when the user starts typing in a JTextArea. In a StudentList class here, I have String firstname, lastname, dateofbirth and year. When the user starts typing a StudentList instance is created, then the first text before the user makes a space stores as firstname and the text after the space lastname, the user presses enter and the text after enter becomes Date of Birth in format (mm/dd/yyyy) and user presses enter again and the text after enter becomes year(in the form "Year num, i.e Year 10, Year 12...).
For example: Joseph\sNancy
\n03/04/1999
\nYear 11
firstname becomes: Joseph, lastname: Nancy. dateofbirth: 03/04/1999 year: Year 11 for the first Object instance created of Type StudentList.
Afterwards, after the first Object is created and year(the last instance variable) is stored, I'll like another instance of StudentList where the process repeats itself if text is entered after Year... Help
All the newly created StudentList gets added to ArrayList
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.*;
public class InfoAdd implements KeyListener {
private JTextArea textar;
private JTextArea textarea;
private JPanel panel;
ArrayList <StudentList> stdlist;
public static void main (String [] args) {
InfoAdd inadd = new InfoAdd();
inadd.go();
}
public void go() {
JFrame frame = new JFrame("InfoAdd");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel = new JPanel();
JPanel btpanel = new JPanel();
JButton button = new JButton("Click");
textarea = new JTextArea(10, 15);
textar = new JTextArea(10, 15);
JScrollPane scrollpane = new JScrollPane(textarea);
JScrollPane scrollpan = new JScrollPane(textar);
textarea.addKeyListener(this);
textarea.setLineWrap(true);
textar.setLineWrap(true);
scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollpan.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpan.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(scrollpane);
panel.add(scrollpan);
btpanel.add(button);
frame.setSize(300, 300);
frame.add(BorderLayout.WEST, panel);
frame.add(BorderLayout.EAST, btpanel);
frame.setVisible(true);
}
public void keyTyped(KeyEvent e) {
String add = textarea.getText();
String [] delimiter = add.split("\\s+");
String [] enter = add.split("[\\r\\n]+");
stdlist = new ArrayList<StudentList>();
for(int i=0;i<add.length();i++) {
StudentList sdt = new StudentList();
if(delimiter.length==2) {
sdt.SetFirstName(delimiter[i]);
}
stdlist.add(sdt);
textar.setEditable(false);
textar.setText("Firstname: "+sdt.getFirstName()+"\nLastName: "+sdt.getLastName()+"\nYear: ");
}
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
class StudentList {
private String firstname;
private String lastname;
private String year;
private String dateofbirth;
public void SetFirstName(String y) {
y = firstname;
}
public void setLastName(String c) {
c = lastname;
}
public void setYear(String t) {
t = year;
}
public void setDateofBirth(String u) {
u = dateofbirth;
}
public String getFirstName() {
return firstname;
}
public String getLastName() {
return lastname;
}
public String getYear() {
return year;
}
public String getDateofBirth(){
return dateofbirth;
}
}
}

as d.j.brown mention your setter creation is wrong and i change some code line in InfoAdd class.(netbeans, intellij idea, eclipse if you are using one of these IDE. this IDE give facility to generate getters and setters. use it then you don't get trouble)
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.*;
public class InfoAdd implements KeyListener {
private JTextArea textar;
private JTextArea textarea;
private JPanel panel;
ArrayList<StudentList> stdlist;
public static void main(String[] args) {
InfoAdd inadd = new InfoAdd();
inadd.go();
}
public void go() {
JFrame frame = new JFrame("InfoAdd");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel = new JPanel();
JPanel btpanel = new JPanel();
JButton button = new JButton("Click");
textarea = new JTextArea(10, 15);
textar = new JTextArea(10, 15);
JScrollPane scrollpane = new JScrollPane(textarea);
JScrollPane scrollpan = new JScrollPane(textar);
textarea.addKeyListener(this);
textarea.setLineWrap(true);
textar.setLineWrap(true);
scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollpan.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollpan.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(scrollpane);
panel.add(scrollpan);
btpanel.add(button);
frame.setSize(300, 300);
frame.add(BorderLayout.WEST, panel);
frame.add(BorderLayout.EAST, btpanel);
frame.setVisible(true);
}
public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) {
String add = textarea.getText();
String[] delimiter = add.split("\\s+");
String[] enter = add.split("[\\r\\n]+");
stdlist = new ArrayList<>();
for (int i = 0; i <= add.length(); i++) {
StudentList studentList = new StudentList();
System.out.println(delimiter.length);
switch (enter.length) {
case 1:
setName(delimiter, studentList);
break;
case 2:
setName(delimiter, studentList);
studentList.setDateofbirth(enter[1]);
break;
default:
setName(delimiter, studentList);
studentList.setDateofbirth(enter[1]);
studentList.setYear(enter[2]);
break;
}
stdlist.add(studentList);
textar.setEditable(false);
textar.setText("Firstname: " + studentList.getFirstname() + "\nLastName: " + studentList.getLastname()+" \nDateOfBirth: "+studentList.getDateofbirth() + "\nYear: " + studentList.getYear());
}
}
private void setName(String[] delimiter, StudentList studentList) {
if (delimiter.length == 1) {
studentList.setFirstname(delimiter[0]);
} else if (delimiter.length == 2) {
studentList.setFirstname(delimiter[0]);
studentList.setLastname(delimiter[1]);
}
}
class StudentList {
private String firstname;
private String lastname;
private String year;
private String dateofbirth;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getDateofbirth() {
return dateofbirth;
}
public void setDateofbirth(String dateofbirth) {
this.dateofbirth = dateofbirth;
}
}
}

Related

How to I get the object's information and then display it all into a GUI frame?

I have a student class and I've implemented all my methods correctly. However, I do not know how to get the information out of the object to display them into the GUI, such as the image file and also the texts to be shown.
So, in the GUI Frame I have their name, title, group and demowhat as labels and then the imageFile to actually show the image from the link.
class PersonInfo
{
protected String name;
protected String title;
protected String imageFile;
public PersonInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
public PersonInfo(PersonInfo pi)
{
this(pi.name, pi.title, pi.imageFile);
}
public String getName()
{ return name; }
public String getTitle()
{ return title; }
public String getImageFile()
{ return imageFile; }
public void SetInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
#Override public String toString()
{
return String.format("name: %s%ntitle: %s%nimageFile:%s%n", name, title, imageFile);
}
}
class Student extends PersonInfo
{
private String group;
private String demoWhat;
public Student(String name, String title, String imageFile, String group, String demoWhat)
{
super(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
public Student(Student s)
{
super(s);
}
public String getGroup()
{
return group;
}
public String getDemoWhat()
{
return demoWhat;
}
public void SetInfo(String name, String title, String imageFile, String group, String demoWhat)
{
super.SetInfo(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
#Override
public String toString()
{
return String.format ("%s" + "group: %s%n" + "demoWhat: %s%n", super.toString (), group, demoWhat);
}
}
class GUI2 extends JFrame
{
private JLabel label1;
private final JLabel image2;
public GUI2()
{
super("Welcome to 121 Demo System");
setLayout( new FlowLayout());
JButton plainJButton = new JButton("Refresh button to get the next student");
add(plainJButton);
ImageIcon image = new ImageIcon(getClass().getResource("images/xx.png"));
Image imageSIM = image.getImage();
Image imageSIMResized = imageSIM.getScaledInstance(260, 180, DO_NOTHING_ON_CLOSE);
image = new ImageIcon(imageSIMResized);
image2 = new JLabel(image);
add(image2);
ButtonHandler handler1 = new ButtonHandler();
plainJButton.addActionListener(handler1);
}
class ButtonHandler implements ActionListener //call student here
{
#Override
public void actionPerformed(ActionEvent event)
{
GUI3 gui3 = new GUI3();
setLayout( new FlowLayout());
gui3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui3.setSize(450,400);
gui3.setVisible(true);
**//I WANT THE GUI TO POP UP WITH THE NAME, TITLE, IMAGEFILE, GROUP AND DEMOWHAT**
Student student1 = new Student("name", "full time student","images/xxx.JPG", "I am from group 12", "I wish to demo A1");
add(label1);
}
}
}
class GUI3 extends JFrame //firststudent
{
private final JLabel image3;
public GUI3()
{
super("Let us welcome xxx");
JButton plainJButton = new JButton("OK");
add(plainJButton);
//ImageIcon image = new ImageIcon(getClass().getResource("images/xxx.JPG"));
//Image imagexxx= image.getImage();
//Image xxxResized = imagexxx.getScaledInstance(210, 280, DO_NOTHING_ON_CLOSE);
//image = new ImageIcon(xxxResized);
//image3 = new JLabel(image);
//add(image3);
ButtonHandler handler2 = new ButtonHandler();
plainJButton.addActionListener(handler2);
}
}
I tried making the student object in the ButtonHandler class, but then I don't know what to do from here.
Create a JPanel that renders your student. Here is a small example, based on your student class:
class StudentPanel extends JPanel {
JTextField tfGroup;
public StudentPanel() {
add(new JLabel("Group"));
tfGroup = new JTextField();
add(tfGroup);
}
public void setStudent(Student student) {
tfGroup.setText(student.getGroup());
}
}
You will want to add more fields and look at the sizing and arrangement of fields and labels. Maybe your application needs more than one way to render a student (short, full, list).
Once you have such a view, use it like so:
public static void main(String[] args) {
Student student = ... // populate the data you want to show somehow
JFrame f = new JFrame();
StudentPanel panel = new StudentPanel();
panel.setStudent(student);
f.add(panel);
f.pack();
f.setVisible(true);
}

Accessing HashMap and displaying object toString in JList

Using Java -- Create a HashMap<String, Customer> and display HashMap in a sorted view using JDialog/JList.
Class - Customer:
Fields:
int id
String firstName
String lastName
Constructor:
public Customer(int id, String firstName, String lastName) {
}
Getters/Setters/toString
Class - CustomerLibrary:
Fields:
HashMap<String, Customer>
Create methods to add customers to hashmap, display entire hashmap and display single customer based on id number.
ie. addCustomer(String key, Customer value)
ie. displayLibrary()
ie. displayChoice(String value)
Class - Driver:
Create a method called init() and inside create 3-5 Customer Objects and store them in a HashMap<String, Customer> using the method you created in CustomerLibrary.
ie. Customer Example: Customer c1 = new Customer(001, “Bob”, “Smith”);
Create another method called loadFrame() which opens a JFrame.
Class – MainFrame
Design a JFrame that contains a MenuBar. In the MenuBar create a dropdown menu called ‘File’ with two options inside called ‘Show Customers’ and ‘Exit’. When ‘Show Customers’ is selected a new JDialog should appear where all the Customers in the HashMap are displayed in sorted order based on ID (ie. 001, 002, 003). When ‘Exit’ is selected, exit the program (ie. Sysytem.exit(0)). Don’t worry about buttons yet, but one of them should dispose the JDialog but leaves the JFrame running.
Class – CustomerDialog
Design a JDialog that features a JList to display all the Customer Objects stored in the HashMap. Don’t worry about buttons yet, but one of them should dispose the JDialog but leaves the JFrame running.
I have 2 issues:
1 - I have created all my classes and can see that my HashMap is filled with 5 objects, however, when I try to access the HashMap in my JDialog I can't get it to work.
2 - I am uncertain of the best way to create/call a JList.
Any help would be super appreciated. Thank You!
**
CUSTOMER CLASS**
class Customer {
private String id;
private String firstName;
private String lastName;
public Customer(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
CUSTOMERLIBRARY CLASS
public class CustomerLibrary {
private HashMap<String, Customer> library;
public CustomerLibrary() {
library = new HashMap<String, Customer>();
}
public void addCustomer(String key, Customer customer) {
if(key == null) {
throw new IllegalArgumentException("invalid key.");
}
else if(customer == null) {
throw new IllegalArgumentException("invalid customer.");
}
library.put(key, customer);
}
public void displayLibrary() {
Iterator itr = library.entrySet().iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
public void displayChoice(String prefix) {
for (Entry<String, Customer> entry : library.entrySet()) {
String key = entry.getKey();
Customer value = entry.getValue();
if(key.equals(prefix)) {
System.out.println(value);
}
}
}
}
MAINFRAME/JFRAME
public class MainFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
}
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("File");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("Show Customers");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CustomerDialog dialog = new CustomerDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Exit");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);;
}
});
mnNewMenu.add(mntmNewMenuItem_1);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[]", "[]"));
}
}
CUSTOMERDIALOG/JDIALOG
public class CustomerDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JList list;
private DefaultListModel listModel;
private CustomerLibrary library;
public static void main(String[] args) {
}
public CustomerDialog() {
this.library = library;
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new MigLayout("", "[grow]", "[grow]"));
JScrollPane scrollPane = new JScrollPane();
{
listModel = new DefaultListModel();
list = new JList(listModel);
listModel.addElement(library.toString());
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedValue());
}
}
});
scrollPane.setViewportView(list);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
public void setCustomers(List<Customer> customers) {
for(Customer customer : customers) {
listModel.addElement(customer);
}
}
}
DRIVER CLASS
public class Driver {
public static CustomerLibrary library;
public static void main(String[] args) {
Driver driver = new Driver();
driver.init();
driver.loadFrame();
}
private void init() {
CustomerLibrary library = new CustomerLibrary();
Customer c1 = new Customer("001", "Joe", "Smith");
Customer c2 = new Customer("002", "Alan", "Shepphard");
Customer c3 = new Customer("004", "Lily", "Issaac");
Customer c4 = new Customer("005", "Jennifer", "Conner");
Customer c5 = new Customer("003", "Jared", "Zartme");
library.addCustomer(c1.getId(), c1);
library.addCustomer(c2.getId(), c2);
library.addCustomer(c3.getId(), c3);
library.addCustomer(c4.getId(), c4);
library.addCustomer(c5.getId(), c5);
//library.displayLibrary();
//library.displayChoice("001");
}
private void loadFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

How do I pass text input from one JTextField to a variable in another class?

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!
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.
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:
User enters a value in a field
The field fires a property change event for the property "value" when it looses focus
The GUI (or controller class) listens for the property change event and fires another event, such as a Vetoable Change Event.
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.
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.
Have you tried making the variables you want to share between classes public static?

Using variable from actionlistener to a class

Help I'm lost I still cant use the previously initiated variable, I dont know if I'm doing this right I'm still new to java. I've been trying to build a payroll system, and I'm stuck at reading a variable from an action listener. Thanks in advance!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.print.attribute.SetOfIntegerSyntax;
import javax.swing. * ;
import java.awt. * ;
import java.awt.event. * ;
#SuppressWarnings("serial")
public class kapoy extends JFrame {
public static JTextField text1;
public static JTextField text2;
public JLabel label1;
public JLabel label2;
public JPanel panel1;
public JPanel panel2;
public JPanel panel3;
public JPanel panel4;
public kapoy() {
text1 = new JTextField();
text1.setPreferredSize(new Dimension(50, 20));
text2 = new JTextField();
text2.setPreferredSize(new Dimension(50, 20));
label1 = new JLabel("Inpute Employee ID: ");
label2 = new JLabel("Input worked Days: ");
panel1 = new JPanel();
panel1.setLocation(0, 0);
panel1.setSize(300, 40);
panel1.setBackground(Color.blue);
panel1.add(label1);
panel1.add(text1);
add(panel1);
panel2 = new JPanel();
panel2.setLocation(0, 40);
panel2.setSize(300, 40);
panel2.setBackground(Color.red);
panel2.add(label2);
panel2.add(text2);
add(panel2);
panel3 = new JPanel();
panel3.setLocation(0, 80);
panel3.setSize(400, 200);
panel3.setBackground(Color.green);
add(panel3);
panel4 = new JPanel();
panel4.setLocation(300, 0);
panel4.setSize(100, 80);
panel4.setBackground(Color.yellow);
add(panel4);
setSize(410, 300);
setLayout(null);
setTitle("Pay Roll by Migz");
}
public static void main(String[]args) {
kapoy cn = new kapoy();
cn.setVisible(true);
text1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
try {
int idnum = Integer.parseInt(text1.getText());
bweset ka = new bweset(idnum);
} catch (NumberFormatException nfe) {
text1.setText("");
}
}
});
try {
File f = new File("D:/Users/DAVID Family/Desktop/Employees.txt");
Scanner sc = new Scanner(f);
List < Employee > people = new ArrayList < Employee > ();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[]details = line.split(" ");
int Id = Integer.parseInt(details[0]);
String name = details[1];
int rate = Integer.parseInt(details[2]);
Employee p = new Employee(Id, name, rate);
if (ka == Id) {
people.add(p);
}
}
for (Employee p : people) {
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class bweset {
private int ka;
public bweset(int ka) {
this.ka = ka;
}
public int getka() {
return ka;
}
public void setka(int ka) {
this.ka = ka;
}
public int ka() {
return this.ka;
}
public int toint() {
return this.ka;
}
}
class Employee {
private int Id;
private String name;
private int rate;
public Employee(int Id, String name, int rate) {
this.Id = Id;
this.setName(name);
this.rate = rate;
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getrate() {
return rate;
}
public void setrate(int rate) {
this.rate = rate;
}
public String toString() {
return this.Id + " " + this.name + " " + this.rate;
}
}

Posting from JTextFields into array

Ok So i have made my array and added an action listener so that when the button named "Submit" is clicked all data from my JTextFields should be entered into an ArrayList although this is not happening, any help on why not would be appreciated. below is the Action Listener action Performed.
public class Main {
String HouseNumber, StreetName, Town, Postcode, Beds, Price, Type;
JTextField HouseNumber1, StreetName1, Town1, Postcode1, Beds1, Price1,
Type1;
JLabel HouseNumberLabel, StreetNameLabel, TownLabel, PostcodeLabel,
BedsLabel, PriceLabel, TypeLabel;
JButton Submit;
JPanel panel;
JFrame frame;
public static void main(String[] args) {
Main gui = new Main();
gui.go();
}
public void go() {
frame = new JFrame();
panel = new JPanel();
HouseNumberLabel = new JLabel("House Number");
HouseNumber1 = new JTextField("");
StreetNameLabel = new JLabel("Street name");
StreetName1 = new JTextField("");
TownLabel = new JLabel("Town");
Town1 = new JTextField("");
PostcodeLabel = new JLabel("Postcode");
Postcode1 = new JTextField("");
BedsLabel = new JLabel("Number of beds");
Beds1 = new JTextField("");
PriceLabel = new JLabel("Price (£)");
Price1 = new JTextField("");
TypeLabel = new JLabel("Building Type");
Type1 = new JTextField("");
Submit = new JButton("Submit");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
// Add contents to JFrame and JPanel
panel.add(HouseNumberLabel);
panel.add(HouseNumber1);
panel.add(StreetNameLabel);
panel.add(StreetName1);
panel.add(TownLabel);
panel.add(Town1);
panel.add(PostcodeLabel);
panel.add(Postcode1);
panel.add(BedsLabel);
panel.add(Beds1);
panel.add(PriceLabel);
panel.add(Price1);
panel.add(TypeLabel);
panel.add(Type1);
panel.add(Submit);
frame.pack();
frame.show();
final ArrayList<Main> p = new ArrayList<Main>();
Submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main array = new Main();
HouseNumber = HouseNumber1.getText();
StreetName = StreetName1.getText();
Town = Town1.getText();
Postcode = Postcode1.getText();
p.add(array);
}
});
}
}
Although your Main class has the fields, since it's also managing the GUI, you don't want to create an ArrayList<Main>
If you just need to collect all the strings then you can create
ArrayList<String> houseDetails = new ArrayList<String>();
houseDetails.add(HouseNumber);
houseDetails.add(StreenName);
houseDetails.add(Town);
houseDetails.add(Postcode);
but the cleaner thing to do would be to create a class to manage these
class House
{
private String houseNumber;
private String streetName;
private String town;
private String postcode;
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
and then create a House and set all the valuse.
final ArrayList<House> houses = new ArrayList<House>();
and in your actionPerformed event
House house = new House();
house.setHouseNumber(HouseNumber);
...
houses.add(house);

Categories