Accessing HashMap and displaying object toString in JList - java

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

Related

Sorting and Adding to ArrayList

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

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

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?

Getting information from a text field to use it in a text area in other Class

I've got one class that has two text fields in it: "name" and "surname". I need the information that someone typed in there for a text area in another class. So far I managed to write (Person class):
public class Person extends JPanel implements ActionListener {
TextField nameField;
JTextField surnameField;
public String name;
public String surname;
final static int BIG_BORDER = 75;
final static int SMALL_BORDER = 10;
final static int ELEMENTsLENGHT = 320;
final static int VERTICAL_SPACE = 10;
final static int VERTICAL_SPACE_PLUS = 25;
final static int HORIZONTAL_SPACE = 75;
final static int SPACEforELEMENT_LABEL = 50;
final static int SPACEforELEMENT_TEXT = 40;
final static int H_SPACEforBUTTON = 64;
final static int V_SPACEforBUTTON = 26;
public Person() {
init();
}
public void init() {
JLabel nameLabel = new JLabel("Please enter your name:");
JLabel surnameLabel = new JLabel("Please enter your surname:");
nameField = new JTextField();
nameField.addActionListener(this);
surnameField = new JTextField();
surnameField.addActionListener(this);
nextButton = new JButton("NEXT");
nextButton.setActionCommand(next);
nextButton.addActionListener(this);
JPanel panelButton = new JPanel();
panelButton.add(nextButton);
double size[][] = {
{ BIG_BORDER, ELEMENTsLENGHT, HORIZONTAL_SPACE,
H_SPACEforBUTTON, SMALL_BORDER }, // Columns
{ BIG_BORDER, SPACEforELEMENT_LABEL, VERTICAL_SPACE,
SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
SPACEforELEMENT_LABEL, VERTICAL_SPACE,
SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
SPACEforELEMENT_LABEL, VERTICAL_SPACE,
V_SPACEforBUTTON, SMALL_BORDER } }; // Rows
setLayout(new TableLayout(size));
add(nameLabel, "1,1,1,1");
add(nameField, "1,3,1,1");
add(surnameLabel, "1,5,1,1");
add(surnameField, "1,7,1,1");
add(nextButton, "3,11,1,1");
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Identification");
frame.getContentPane().add(new Person());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
name = nameField.getText();
surname = surnameField.getText();
if (e.getActionCommand().equalsIgnoreCase(next)) {
Person.showNextWindow();
}
}
public static void showNextWindow() {
//cardLayout.next(this);
System.out.println("go to the next window");
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The other class now:
public class Greeting extends JPanel implements ActionListener {
Person person = new Person();
String name = person.name;
String surname = person.surname;
public Greeting() {
super(new BorderLayout());
init();
}
public void init() {
nextButton = new JButton("NEXT");
nextButton.setActionCommand(next);
nextButton.addActionListener(this);
//nextButton.setMnemonic('rightArrow');
String q = "How are you today, "+name+" "+surname+"?";
JTextArea textArea = new JTextArea(q);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
add(textArea, BorderLayout.NORTH);
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS));
btnPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
btnPanel.add(Box.createHorizontalGlue());
btnPanel.add(nextButton);
btnPanel.setAlignmentX(RIGHT_ALIGNMENT);
add(btnPanel, BorderLayout.SOUTH);
} // end init
public static void showNextWindow() {
//cardLayout.next(this);
System.out.println("go to the next window");
}
public void actionPerformed(ActionEvent e) {
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("How are you");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Greeting());
frame.setSize(550, 450);
frame.setResizable(false);
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
But what I see in the window is: "How are you today, null null?" Any fresh eyes to catch what's wrong? Thanks
You never show us that you've proven that the ActionListener's are called after the text has been entered into the fields and before the String variables are used elsewhere. Regardless, it's a bad design.
I'd give the class with the JTextFields public getter methods, not public variables, and in the getter methods, I'd extract the text currently in the corresponding JTextField. For instance, something like:
private JTextField nameField = new JTextField();
private JTextField surnameField = new JTextField();
public String getName() {
return nameField.getText();
}
public String getSurname() {
return surnameField.getText();
}
//... etc...
For example, here is an SSCCE that demonstrates your problem and a solution:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class InfoFromTextFields {
private static void createAndShowUI() {
JFrame frame = new JFrame("InfoFromTextFields");
frame.getContentPane().add(new MainGui());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class NamePanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField surnameField = new JTextField(10);
public NamePanel() {
add(new JLabel("Name:"));
add(nameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Surname:"));
add(surnameField);
}
public String getNameText() {
return nameField.getText();
}
public String getSurnameText() {
return surnameField.getText();
}
}
class MainGui extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField surnameField = new JTextField(10);
public MainGui() {
nameField.setEditable(false);
surnameField.setEditable(false);
add(new JLabel("Name:"));
add(nameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Surname:"));
add(surnameField);
add(Box.createHorizontalStrut(15));
add(new JButton(new AbstractAction("Get Names") {
#Override
public void actionPerformed(ActionEvent arg0) {
NamePanel namePanel = new NamePanel();
int result = JOptionPane.showConfirmDialog(nameField, namePanel,
"Get Names", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
nameField.setText(namePanel.getNameText());
surnameField.setText(namePanel.getSurnameText());
}
}
}));
}
}
As far as I understand it, action will be fired by JTextFields only (?) when the "enter" key is hit. See example here : Java Tutorial
Does it work if you enter text in the textfields AND hit "enter" before starting the other class/frame ?
Then of course a better solution is getters, like Hovercraft already mentioned :
public String getName(){
return nameField.getText();
}
Better use getter methods:
(Person class):
// public String name;
// public String surname;
// ...
public Person()
{
// ...
nameField = new JTextField();
nameField.addActionListener(this);
surnameField = new JTextField();
surnameField.addActionListener(this);
// and in public void actionPerformed(ActionEvent e) {
// name = nameField.getText();
// surname = surnameField.getText();
// ...
}
private String getName(){return nameField.getText();}
private String getSurname(){return surnameField.getText();}
// ...
The other class:
Person person = new Person();
String name = person.getName();
String surname = person.getSurname();
String q = "How are you today, "+name+" "+surname+"?";
JTextArea textArea = new JTextArea(q);
One way would be to create accessors for the values.. So you should have:
String getName()
{
nameField.getText();
}
and
String getName()
{
surnameField.getText();
}
In you other class you just call those methods to return the values..
You should leave your instance variables as private and never make them public (unless you have a very good reason). Read on Encapsulation

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