java - how can I pass value from textfield to object or file(serializable file)? -
ive got layout codes ready(i have 3 classes). after inputed first name, last name, address, age , salary clicked button "save", should save on employee.ser file , should not overwrite every time save 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 actionlistener save button.
- override actionperformed handle save action (get values textfields).
- load object inside file (what done in
load()
) - create
fileoutputsteram
, usewriteobject()
method ofobjectoutputstream
write objects in list.
Comments
Post a Comment