ArrayList in ActionListener isnt working - java

i have made a java program named DoctorsCare in which patients can book their appointment with a doctor. So in the appointment panel I have included patient id, name, gender, date of birth, address and a brief patient history.
All these string values will be taken in an array list and will eventually be returned to a new tab (Doctors tab) after the appointment form is filled and the submit button is clicked. the the array list code I wrote has some problems but I can run the program.
I just need to know where I made the mistake and how can I return the array list values to the doctors tab.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
public class NewPage extends JFrame implements ActionListener{
JFrame frame1= new JFrame();
JTextField id;
JLabel label = new JLabel("Patient ID:");
JLabel label2 = new JLabel("Name:");
JLabel label3 = new JLabel("Gender:");
JLabel label4 = new JLabel("Date of Birth:");
JLabel label5 = new JLabel("Address:");
JLabel label7 = new JLabel("Phone:");
JLabel label6= new JLabel("brief patient history:");
JPanel panel1 = new JPanel();
JTextArea phistry = new JTextArea(11,31);
JTextField text1 = new JTextField(20);
JTextField text2 = new JTextField(20);
JTextField text3 = new JTextField(20);
JTextField text4 = new JTextField(20);
JTextField text5 = new JTextField(20);
JTextField text6 = new JTextField();
JTextField text7 = new JTextField(20);
JButton button = new JButton("SUBMIT");
NewPage()
{
frame1.setTitle("Booking Appointment");
frame1.setVisible(true);
frame1.setSize(330,470);
frame1.add(panel1);
panel1.add(label);
panel1.add(text1);
panel1.add(label2);
panel1.add(text2);
panel1.add(label3);
panel1.add(text3);
panel1.add(label4);
panel1.add(text4);
panel1.add(label5);
panel1.add(text5);
panel1.add(label7);
panel1.add(text7);
panel1.add(label6);
panel1.add(phistry);
panel1.add(button);
button.setPreferredSize(new Dimension(160,40));
button.addActionListener(this);
}
\\the button code
public void actionPerformed(ActionEvent e) {
List<List<String>> model = new ArrayList<List<String>>();
text1.selectAll(); \\selects the input from user
text2.selectAll();
text3.selectAll();
text4.selectAll();
text5.selectAll();
text6.selectAll();
String ID = text1.getSelectedText(); \\initializes ID
String PName = text2.getSelectedText();
String Gender = text3.getSelectedText();
String DoB = text4.getSelectedText();
String Address = text5.getSelectedText();
//String phone = text7.getSelectedText();
String phistry = text6.getSelectedText();
//String phistry = text6.getSelectedText();
List<String> line = Arrays.asList(new String[]{ID, PName, Gender, DoB, Address, phistry});
model.add(line);
StringBuilder sb = new StringBuilder();
sb.append("ID\tFirst\tLast\tCourse\tYear\n");
for(List<String> input : model) {
for (String item : input) {
sb.append(item);
if (input.indexOf(item) == input.size()-1) {
sb.append("\n");
} else {
sb.append("\t");
}
}
}
}
}

First your List contains the model information, but you haven't set it in the text area you have like below in the actionPerformed method,
this.phistry.setText(sb.toString());
Assuming that you have the Doctors tab in a separate class like below (else you can set the model directly in the NewFrame,
class DoctorsPanel extends JPanel {
private List<List<String>> model;
JTextArea history;
public DoctorsPanel() {
model = new LinkedList<>();
history = new JTextArea(11, 31);
setLayout(new GridLayout(1, 1));
add(history);
}
public void setModel(List<List<String>> model) {
this.model = model;
setHistory();
}
private void setHistory() {
this.history.setText(getModelData());
}
private String getModelData() {
StringBuilder sb = new StringBuilder();
sb.append("ID\tFirst\tLast\tCourse\tYear\n");
for (List<String> input : model) {
for (String item : input) {
sb.append(item);
if (input.indexOf(item) == input.size() - 1) {
sb.append("\n");
} else {
sb.append("\t");
}
}
}
return sb.toString();
}
}
You can have your tabbed pane like below in the NewFrame,
JTabbedPane jTab = new JTabbedPane();
panel1 = new JPanel();
panel2=new DoctorsPanel();
jTab.add("Book", panel1);
jTab.add("Doctors", panel2);
frame1.add(jTab);
Then you can set it whenever the appointment is made. i.e. when an action performed on tab1 component
public void actionPerformed(ActionEvent e) {
List<List<String>> model = new ArrayList<List<String>>();
String ID = text1.getText();
String PName = text2.getText();
String Gender = text3.getText();
String DoB = text4.getText();
String Address = text5.getText();
String phistry = text6.getText();
List<String> line = Arrays.asList(new String[]{ID, PName, Gender, DoB, Address, phistry});
model.add(line);
StringBuilder sb = new StringBuilder();
sb.append("ID\tFirst\tLast\tCourse\tYear\n");
for(List<String> input : model) {
for (String item : input) {
sb.append(item);
if (input.indexOf(item) == input.size()-1) {
sb.append("\n");
} else {
sb.append("\t");
}
}
}
this.phistry.setText(sb.toString());//sets the text in tab1
panel2.setModel(model);//sets the model in Doctors panel
}
But I suggest to keep the variable model List at class NewFrame as a member rather than a local variable to hold the previously added information

Related

The reason why I cannot find the value that I enter first from JTextField

Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Phone{
private String name;
private String phone_number;
private String address;
public Phone(String name,String phone_number, String address) {
this.name = name;
this.phone_number = phone_number;
this.address = address;
}
String getName() {return this.name;}
String getNumber() {return this.phone_number;}
String getAddress() {return this.address;}
}
public class Phone_Book extends JFrame{
private JTextArea ta = new JTextArea();
private JButton lookup = new JButton("lookup");
private JButton search = new JButton("search");
private JButton input = new JButton("input");
private JButton remove = new JButton("remove");
private JLabel name = new JLabel("name");
private JLabel phone_number = new JLabel("phone_number");
private JLabel address = new JLabel("address");
private JTextField name_input = new JTextField();
private JTextField phone_number_input = new JTextField();
private JTextField address_input = new JTextField();
private HashMap<String,Phone> hashPhoneBook = new HashMap<String, Phone>();
public Phone_Book() {
setTitle("Phone Book");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
//*********************PhoneBook Design ********************************************
JPanel buttonPanel = new JPanel();
buttonPanel.add(inquiry);
buttonPanel.add(search);
buttonPanel.add(input);
buttonPanel.add(remove);
buttonPanel.setLayout(new GridLayout(1,4));
buttonPanel.setSize(350,30);
buttonPanel.setLocation(670,70);
JPanel labelPanel = new JPanel();
labelPanel.add(name);
labelPanel.add(phone_number);
labelPanel.add(address);
labelPanel.setLayout(new GridLayout(3,1));
labelPanel.setSize(80,150);
labelPanel.setLocation(670,110);
JPanel textPanel = new JPanel();
textPanel.add(name_input);
textPanel.add(phone_number_input);
textPanel.add(address_input);
textPanel.setLayout(new GridLayout(3,1,0,25));
textPanel.setSize(260, 140);
textPanel.setLocation(750, 120);
JScrollPane js = new JScrollPane(ta);
js.setSize(600, 300);
js.setLocation(20, 10);
c.add(js);
c.add(buttonPanel);
c.add(labelPanel);
c.add(textPanel);
//********************** PhoneBook Function **************************************************
...
//---- problem occurs-------------------------------------
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.setText(" ");
Phone p = hashPhoneBook.get(name_input.getText());
if(p == null) ta.append(name_input.getText()+"doesn't exist\n");
else {
ta.append(p.getName()+" "+p.getNumber()+" "+p.getAddress()+"\n");
}
name_input.setText(" ");
}
});
//------------------------------------------------------
...
setSize(1100,400);
setVisible(true);
}
public static void main(String[] args) {
new Phone_Book();
}
}
Here is the problem.
I can see all values (including a first value that I first entered after running a program) when I click the 'lookup'button (I thought it isn't needed, I didn't put it in this code).
When I try to find or remove the first value from HashMap, it didn't work.
Only I got the 'null'
But, when I pressed the 'space' and entered the value, it worked well.
(for example, 'David' -----> ' David')
I wonder why this is happening?
It seems like the keys in your HashMap are not set up right. You haven't included the code where this is set.
IMO though, I'd implement the phone book with a simple line delimited text file & load all records in a string instead of using a HashMap for your phone book. The reason being that you can then use regular expressions to match case-insensitive and partial records. Using a HashMap, the key must be an exact match

Passing data from ArrayList in back end to JComboBox GUI front end - Java Swing

This is my FileIOManagement class that I want to handle all of the reading from text files etc that grabs data to display in the GUI.
This is the code for my current FileIOManagement class:
package swinging;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
public class FileIOManagement {
private ArrayList<String> nameList = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
private ArrayList<String> semesterList = new ArrayList<String>();
private ArrayList<String> moderatorList = new ArrayList<String>();
private ArrayList<String> programList = new ArrayList<String>();
private ArrayList<String> majorList = new ArrayList<String>();
public FileIOManagement(){
readTextFile();
}
private void readTextFile(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] tokens = line.split("~");
String course = tokens[0].trim();
String examiner = tokens[1].trim();
String moderator = tokens[2].trim();
String semester = tokens[3].trim();
String program = tokens[4].trim();
String major = tokens[5].trim();
courseList.add(course);
semesterList.add(semester);
nameList.add(examiner);
moderatorList.add(moderator);
programList.add(program);
majorList.add(major);
HashSet hs = new HashSet();
hs.addAll(nameList);
nameList.clear();
nameList.addAll(hs);
Collections.sort(nameList);
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
This is the class I need the ArrayList data passed to. As you can see I am attempting to populate comboBox1 and comboBox2 with data I am attempting to get via ArrayList:
package swinging;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
FileIOManagement fileName;
ArrayList<String> names = new ArrayList<String>(fileName.getNameList());
ArrayList<String> courses = new ArrayList<String>(fileName.getCourseList());
public ReportGUI(){
reportInterface();
allReportsBtn();
// fileRead();
comboBoxes();
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = names.toArray (new String[names.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewCourseGUI();
}
});
String[] comboBox2Array = courses.toArray(new String[courses.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
viewPrograms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewProgramGUI();
}
});
add(panel, BorderLayout.LINE_START);
}
}
However when I attempt to compile, I get a NullPointerException as in the below image:
What am I doing wrong here?
What you did is that you are trying to get the fileName.getNameList() where fileName was never instantiated as a result it will return null.
problem:
FileIOManagement fileName; //was not instantiated
ArrayList<String> names = new ArrayList<String>(fileName.getNameList()); //fileName.getNameList() is null
ArrayList<String> courses = new ArrayList<String>(fileName.getCourseList()); //fileName.getCourseList() is null
solution:
Instantiate your FileIOManagement fileName before getting the List of it.
Figured it out.
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private FileIOManagement fileManage = new FileIOManagement();
private ArrayList<String> nameList = new ArrayList();
private ArrayList<String> courseList = new ArrayList();
// filename = fileManage.nameList();
//FileIOManagement fileName = new FileIOManagement(fileName.getNameList());
public void getData(){
nameList = fileManage.getNameList();
courseList = fileManage.getCourseList();
}
public ReportGUI(){
getData();
reportInterface();
allReportsBtn();
comboBoxes();
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = nameList.toArray (new String[nameList.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
viewPrograms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewProgramGUI();
}
});
add(panel, BorderLayout.LINE_START);
}
}

Java Error: IllegalArgumentException: adding a window to a container

I keep receiving the error:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:483)
at java.awt.Container.addImpl(Container.java:1084)
at java.awt.Container.add(Container.java:966)
at Lab2.EmployeeGUI.main(EmployeeGUI.java:28)
Can someone please help me and tell me what I'm doing wrong?
I am beginner programmer.
package Lab2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* #author Jim Doyle
*/
public class EmployeeGUI extends JFrame implements ActionListener {
JTextField fName, mName, lName, phone, sal, years;
JComboBox boxTitle, boxDept;
DefaultListModel lstdefault;
JList project;
DbWork dbw = new DbWork("Lab2");
DbWork Title = new DbWork("Lab2");
DbWork Dept = new DbWork("Lab2");
DbWork Prjs = new DbWork("Lab2");
DbWork PrjList = new DbWork("Lab2");
public static void main(String[] args) {
EmployeeGUI app = new EmployeeGUI();
JFrame frame = new JFrame("Employee Interface by Jim Doyle");
frame.getContentPane().add(app, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public EmployeeGUI() {
JPanel labels = new JPanel();
labels.setLayout(new GridLayout(8,1));
labels.add(new JLabel("First Name"));
labels.add(new JLabel("MI"));
labels.add(new JLabel("Last Name"));
labels.add(new JLabel("Title"));
labels.add(new JLabel("Telephone"));
labels.add(new JLabel("Salary"));
labels.add(new JLabel("Department"));
labels.add(new JLabel("Years in Service"));
getContentPane().add(labels, BorderLayout.WEST);
JPanel fields = new JPanel();
fields.setLayout(new GridLayout(8,1));
fName = new JTextField(15);
mName = new JTextField(15);
lName = new JTextField(15);
phone = new JTextField(15);
sal = new JTextField(15);
years = new JTextField(15);
boxTitle = new JComboBox();
boxDept = new JComboBox();
fields.add(fName);
fields.add(mName);
fields.add(lName);
fields.add(boxTitle);
fields.add(phone);
fields.add(sal);
fields.add(years);
getContentPane().add(fields, BorderLayout.CENTER);
JPanel prjinfo = new JPanel();
prjinfo.setLayout(new GridLayout(1,2));
prjinfo.add(new JLabel("Project Description"));
project = new JList();
lstdefault = new DefaultListModel();
// add items to title combo box
while(Title.nextRecord()) {
String txtTit = Title.getField(1);
if(txtTit!=null) {
boxTitle.addItem(Title.getField(1));
}
}
// add items to department combo box
while(Dept.nextRecord()) {
String txtDept = Dept.getField(2);
if(txtDept!=null) {
boxDept.addItem(Dept.getField(2));
}
}
while(PrjList.nextRecord()) {
lstdefault.addElement(PrjList.getField(1));
}
project = new JList(lstdefault);
project.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
prjinfo.add(project);
getContentPane().add(prjinfo, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
String button = e.getActionCommand();
if(button == "First") {
if(dbw.firstRecord()) {
Execute();
}
}
else if(button == "Next") {
if(dbw.nextRecord()) {
Execute();
}
}
else if(button == "Save") {
String sql = "UPDATE FirstName, MiddleName, LastName, WorkPhone, Salary, YearsInService FROM Employee;";
dbw.processQuery(sql);
}
}
private void action() {
boxTitle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox)e.getSource();
String ntitle = (String)b.getSelectedItem();
updateTitle(ntitle);
}
});
}
private void Execute() {
fName.setText(dbw.getField(1));
mName.setText(dbw.getField(2));
lName.setText(dbw.getField(3));
phone.setText(dbw.getField(5));
sal.setText(dbw.getField(6));
years.setText(dbw.getField(8));
String ftext = dbw.getField(4);
int dx = TitleList(ftext);
boxTitle.setSelectedIndex(dx);
String dtext = dbw.getField(7);
int dx2 = DeptList(dtext);
boxDept.setSelectedIndex(dx2);
action();
}
int TitleList(String title) {
int dx = 0;
for(int z=0; z<boxTitle.getItemCount(); z++) {
if(title.equals(boxTitle.getItemAt(z))) {
dx = z;
}
}
return dx;
}
int DeptList(String dept) {
int dx = 0;
for(int z=0; z<boxDept.getItemCount(); z++) {
if(dept.equals(boxDept.getItemAt(z))) {
dx = z;
}
}
return dx;
}
private void updateTitle(String title) {
}
}
EmployeeGUI extends from JFrame, but in your main method, you are creating a new JFrame and are trying to add an instance of EmployeeGUI to it.
Change EmployeeGUI so it extends from JPanel instead
Here:
frame.getContentPane().add(app, BorderLayout.CENTER);
you're trying to add a JFrame to a JFrame which makes no sense.
Why not instead just try to display app rather than add it to a JFrame. Or even better, not have EmployeeGUI extend JFrame.
You can't add a JFrame to another JFrame.
But you can add a JPanel to a JFrame, in other words change EmployeeGUI to make it extends JPanel.

Attempting to get GUI to cycle through data starting back at the beginning

I am attempting to get the GUI to fully cycle through
but I run into an error after third next button click array element[2]. What I need to do is have the whole thing cycle through when clicking the next button. once it gets to the last iteration of the array will need to go back to the beginning. The thing also is the array is sorted alphabetically to begin with so it would need to start with titles [3] once it has cycled through. Thanks for all the help
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame implements ActionListener {
JButton next;
JButton previous;
JButton first;
JButton last;
private JLabel itmNum = new JLabel("Item Number: ", SwingConstants.RIGHT);
private JTextField itemNumber;
private JLabel proNm = new JLabel ("Product Name: ", SwingConstants.RIGHT);
private JTextField prodName;
private JLabel yr = new JLabel("Year Made: ", SwingConstants.RIGHT);
private JTextField year;
private JLabel unNum = new JLabel("Unit Number: ", SwingConstants.RIGHT);
private JTextField unitNumber;
private JLabel prodPrice = new JLabel("Product Price: ", SwingConstants.RIGHT);
private JTextField price;
private JLabel restkFee = new JLabel("Restocking Fee", SwingConstants.RIGHT);
private JTextField rsFee;
private JLabel prodInValue = new JLabel("Product Inventory Value", SwingConstants.RIGHT);
private JTextField prodValue;
private JLabel totalValue = new JLabel("Total Value of All Products", SwingConstants.RIGHT);
private JTextField tValue;
private double toValue;
Movies[] titles = new Movies[9];
int nb = 0;
public GUI()
{
super ("Inventory Program Part 5");
setSize(800,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
first = new JButton("First");
previous = new JButton("Previous");
next = new JButton("Next");
last = new JButton("Last");
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
//Movies[] titles = new Movies[9];
titles [0] = new Movies(10001, "King Arthur", 25 , 9.99, 2004, .05);
titles [1] = new Movies(10002,"Tron", 25, 7.99, 1982, .05);
titles [2] = new Movies(10003, "Tron: Legacy",25,24.99,2010,.05);
titles [3] = new Movies(10004,"Braveheart", 25,2.50,1995,.05);
titles [4] = new Movies(10005,"Gladiator",25,2.50,2000,.05);
titles [5] = new Movies(10006,"CaddyShack SE",25,19.99,1980,.05);
titles [6] = new Movies (10007,"Hackers",25,12.50,1995,.05);
titles [7] = new Movies (10008,"Die Hard Trilogy",25,19.99,1988,.05);
titles [8] = new Movies (10009,"Terminator",25,4.99,1984,.05);
Arrays.sort (titles, DVD.prodNameComparator);
itemNumber = new JTextField(Double.toString(titles[3].getitemNum()));
prodName = new JTextField(titles[3].getprodName());
year= new JTextField(Integer.toString(titles[3].getYear()));
unitNumber= new JTextField(Integer.toString(titles[3].getunitNum()));
price= new JTextField(Float.toString(titles[3].getprice()));
rsFee= new JTextField(Double.toString(titles[3].getRestkFee()));
prodValue= new JTextField(Double.toString(titles[3].getprodValue()));
tValue= new JTextField("2636");
nb=0;
next.addActionListener(this);
setLayout(new GridLayout(8,4));
add(itmNum);
add(itemNumber);
add(proNm);
add(prodName);
add(yr);
add(year);
add(unNum);
add(unitNumber);
add(prodPrice);
add(price);
add(restkFee);
add(rsFee);
add(prodInValue);
add(prodValue);
add(totalValue);
add(tValue);
add(first);
add(previous);
add(next);
add(last);
setLookAndFeel();
setVisible(true);
}
public void updateFields()
{
nb++;
itemNumber.setText(Double.toString(titles[nb].getitemNum()));
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(Double.toString(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
if (titles[nb]== titles[8])
{
titles[nb] = titles[0];
}
else {
nb++;
}
updateFields();
}
}
private void setLookAndFeel()
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println("couln't use the system"+ "look and feel: " + e);
}
}
}
The reason you are advancing so quickly through the records is that you have added your ActionListener to your next JButton twice:
next.addActionListener(this);
This, in turn, increments your record index (nb) in the ActionListener as well as in your updateFields method. Remove this increment from one of these locations.
Also, when you check if you've reached the last title, you never reset your record index nb. You could do:
if (titles[nb] == titles[8]) {
nb = 0;
...

how can I pass value from textfield to object or file(serializable file)?

ive got the layout codes ready(i have 3 classes).
after i inputed the
first name, last name, address, age and salary then i clicked the button "save", it should save on the Employee.ser file and it should not overwrite every time i save the input information.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class EmployeeApp extends JFrame
{
private ArrayList <Employee> list;
public EmployeeApp()
{
list = new ArrayList<Employee>();
}
JPanel panel;
JLabel label;
JTextField field;
JFrame frame;
JButton save;
public void initialize()
{
panel = new JPanel();
frame = new JFrame("Mark");
save = new JButton("save");
frame.add(BorderLayout.SOUTH, save);
getContentPane().setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350,350);
frame.setVisible(true);
panel.setLayout(new GridLayout(12,0));
JLabel label = new JLabel("Enter First Name ");
field = new JTextField(20);
frame.add(BorderLayout.CENTER,panel);
panel.add(label);
panel.add(field);
label = new JLabel("Enter Last Name ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
label = new JLabel("Enter Adress ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
label = new JLabel("Enter Age ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
label = new JLabel("Enter Salary ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
}
public void start()
{
initialize();
}
private void load()
{
File empFile = new File("Employee.ser");
if(empFile.exists())
{
try
{
FileInputStream fis = new FileInputStream(empFile);
ObjectInputStream ois = new ObjectInputStream(fis);
Employee emp = null;
while((emp = (Employee) ois.readObject()) != null)
{
list.add(emp);
}
}
catch(Exception e){}
}
}
}
import java.io.*;
public class Employee implements Serializable
{
private String firstName;
private String lastName;
private String address;
private int age;
private double salary;
public void setFirstName(String first) {
firstName = first;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String last) {
lastName = last;
}
public String getLastName() {
return lastName;
}
public void setAddress(String ad) {
address = ad;
}
public String getAddress() {
return address;
}
public void setAge(int ag){
age = ag;
}
public int getAge(){
return age;
}
public void setSalary(double sal){
salary = sal;
}
public double getSalary(){
return salary;
}
}
public class EmployeeLauncher
{
public static void main(String[] args) throws Exception
{
EmployeeApp em = new EmployeeApp();
em.start();
}
}
Add an ActionListener to the save button.
Override actionPerformed to handle save action (Get the values from textFields).
Load all the object inside the file (What you done in load())
Create a FileOutputSteram and use writeObject() method of ObjectOutputStream to write all objects in your list.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class EmployeeApp extends JFrame implements ActionListener
{
private ArrayList <Employee> list;
public EmployeeApp()
{
list = new ArrayList<Employee>();
}
Employee obj = new Employee();
JPanel panel;
JLabel label;
JTextField field;
JFrame frame;
JButton save;
private JTextField nameField;
public void initialize()
{
nameField = new JTextField();
panel = new JPanel();
frame = new JFrame("Mark");
save = new JButton("save");
frame.add(BorderLayout.SOUTH, save);
getContentPane().setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350,350);
frame.setVisible(true);
panel.setLayout(new GridLayout(12,0));
JLabel label = new JLabel("Enter First Name ");
field = new JTextField(20);
frame.add(BorderLayout.CENTER,panel);
panel.add(label);
panel.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Enter Last Name ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Enter Adress ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Enter Age ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Enter Salary ");
field = new JTextField(20);
panel.add(label);
panel.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
save.addActionListener(this);
load();
}
public void actionPerformed(ActionEvent e)
{
load();
obj.setFirstName(nameField.getText());
obj.setLastName(nameField.getText());
obj.setAge(nameField.getText());
obj.setAddress(nameField.getText());
obj.setSalary(nameField.getText());
}
public void start()
{
initialize();
}
private void load()
{
File empFile = new File("Employee.ser");
if(empFile.exists())
{
try
{
FileInputStream fis = new FileInputStream(empFile);
ObjectInputStream ois = new ObjectInputStream(fis);
Employee emp = null;
while((emp = (Employee) ois.readObject()) != null)
{
list.add(emp);
}
}
catch(Exception e){}
}
}
private void saveObject()
{
try
{
File empFile = new File("Employee.ser");
FileOutputStream fos = new FileOutputStream(empFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(Employee emp : list)
{
oos.writeObject(emp);
}
oos.close();
}
catch(Exception e){}
}
}

Categories