Java Swing - How can I make next and previous buttons to display variables of objects in an array? -


everyone. i've made array of custom class "human" create "city."
each human has randomly generated name , age.
want use next , previous buttons scroll through each human , view information.
how go doing this?
here source code:

jamiescity.java:

package jamiescity;  import javax.swing.*;  import net.miginfocom.swing.miglayout; import java.awt.event.actionevent; import java.awt.event.actionlistener;  public class jamiescity {      public static void main(string[] args) {         jamiescity j = new jamiescity();         j.createmaingui();     }      city newcity;      public void createmaingui(){             jframe startgui;         startgui = new jframe();         startgui.setsize(485, 85);         startgui.setlocationrelativeto(null);         startgui.settitle("jamie's city");         startgui.setlayout(null);         startgui.setdefaultcloseoperation(jframe.exit_on_close);         startgui.setresizable(false);          jbutton create;         create = new jbutton("new city");         create.setbounds(15, 15, 130, 25);         startgui.add(create);          jtextfield title;         title = new jtextfield("city name");         title.setbounds(155, 15, 305, 25);         startgui.add(title);          create.addactionlistener(new actionlistener() {              public void actionperformed(actionevent e) {                 createcity(title.gettext());             }         });         startgui.setvisible(true);     }      public void createcity(string name){         newcity = new city(name);         dispcityinfo(name, newcity);             }      public void dispcityinfo(string name, city city){         jframe dispcity = new jframe(name);         dispcity.setlocationrelativeto(null);         dispcity.setresizable(false);         dispcity.setdefaultcloseoperation(jframe.dispose_on_close);          jpanel panel = new jpanel();          panel.setlayout(new miglayout("insets 30"));          jlabel personmarker = new jlabel("-------person-------");         jlabel cityname = new jlabel("city name: ");         jlabel citypopulation = new jlabel("city population: ");         jlabel personname = new jlabel("name: ");         jlabel personage = new jlabel("age: ");         jlabel persongender = new jlabel("gender: ");          string thename = new string(city.getfirstnameofperson(0) + " " + newcity.getlastnameofperson(0));         string theage = new string(city.getageofpersonasstring(0));         string thegender = new string(city.getgenderofperson(0));          jlabel thecityname = new jlabel(city.getcityname());         jlabel thecitypopulation = new jlabel(city.getpopulationasstring());         jlabel thepersonname = new jlabel(thename);         jlabel thepersonage = new jlabel(theage);         jlabel thepersongender = new jlabel(thegender);          jbutton next = new jbutton("next");         jbutton previous = new jbutton("previous");          //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------          dispcity.add(panel);         panel.add(cityname);         panel.add(thecityname, "wrap");         panel.add(citypopulation);         panel.add(thecitypopulation, "wrap");         panel.add(personmarker, "span 2, align center, wrap");         panel.add(personname);         panel.add(thepersonname, "wrap");         panel.add(personage);         panel.add(thepersonage, "wrap");         panel.add(persongender);         panel.add(thepersongender, "wrap");         panel.add(next, "cell 0 6 2 1, width 200");         panel.add(previous, "cell 0 7 2 1, width 200");          //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------          next.addactionlistener(new actionlistener() { //show info of next person             public void actionperformed(actionevent e) {              }         });          previous.addactionlistener(new actionlistener() { //show info of previous person             public void actionperformed(actionevent e) {              }         });          //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------          dispcity.pack();         dispcity.setvisible(true);     }  } 

city.java:

package jamiescity;  import java.io.file; import java.io.filenotfoundexception; import java.util.arraylist; import java.util.random; import java.util.scanner;  public class city {      //variables      private string cityname;     private int population;     private int poplength;     public human[] thepeople;     private arraylist<string> malefirsts = new arraylist<string>();     private arraylist<string> femalefirsts = new arraylist<string>();     private arraylist<string> lasts = new arraylist<string>();      //constructor      public city(string cityname){          this.cityname = cityname;          random rand = new random();         int randomnum = rand.nextint((8000000 - 10000) + 1) + 10000;         this.setpopulation(randomnum);            thepeople = new human[(int) population];          malefirstnames();         femalefirstnames();         lastnames();          for(int = 0; < thepeople.length; i++){              string mfirstname = "";             random mfirstnames = new random();             int mfirstnamerand = mfirstnames.nextint((malefirsts.size() - 0) + 0);             mfirstname = malefirsts.get(mfirstnamerand);              string ffirstname = "";             random ffirstnames = new random();             int ffirstnamerand = ffirstnames.nextint((malefirsts.size() - 0) + 0);             ffirstname = femalefirsts.get(ffirstnamerand);              string lastname = "";             random lastnamerand = new random();             int lastnamerandomnumber = lastnamerand.nextint((lasts.size() - 0) + 0);             lastname = lasts.get(lastnamerandomnumber);              random agerand = new random();             int age = agerand.nextint((101 - 1) + 1);              if(i < thepeople.length / 2){                 thepeople[i] = new human(mfirstname, lastname, age, "male");             }             if(i == thepeople.length / 2){                 thepeople[i] = new human(ffirstname, lastname, age, "female");             }            }         this.poplength = thepeople.length;     }      //scan csvs      private void malefirstnames(){         file malefirstscsv = new file("src/jamiescity/male.firstnames.csv");         try {             scanner malefirstnames = new scanner(malefirstscsv);             while(malefirstnames.hasnext()){                 string input = malefirstnames.next();                 string values[] = input.split(",");                 malefirsts.add(values[0]);             }             malefirstnames.close();         } catch (filenotfoundexception e) {             system.out.println("cannot find male first names csv file");         }     }      private void femalefirstnames(){         file malefirstscsv = new file("src/jamiescity/female.firstnames.csv");         try {             scanner femalefirstnames = new scanner(malefirstscsv);             while(femalefirstnames.hasnext()){                 string input = femalefirstnames.next();                 string values[] = input.split(",");                 femalefirsts.add(values[0]);             }             femalefirstnames.close();         } catch (filenotfoundexception e) {             system.out.println("cannot find female first names csv file");         }     }      private void lastnames(){         file malefirstscsv = new file("src/jamiescity/csv_database_of_last_names.csv");         try {             scanner lastnames = new scanner(malefirstscsv);             while(lastnames.hasnext()){                 string input = lastnames.next();                 string values[] = input.split(",");                 lasts.add(values[0]);             }             lastnames.close();         } catch (filenotfoundexception e) {             system.out.println("cannot find last names csv file");         }     }      //getters , setters      public string getfirstnameofperson(int humancount){         string name = thepeople[humancount].getfirstname();         return name;     }     public string getgenderofperson(int humancount){         string gender = thepeople[humancount].getgender();         return gender;     }     public string getlastnameofperson(int humancount){         string name = thepeople[humancount].getlastname();         return name;     }     public int getageofperson(int humancount){         int age = thepeople[humancount].getage();         return age;     }      public string getageofpersonasstring(int humancount){         stringbuilder age = new stringbuilder();         age.append(thepeople[humancount].getage());         string theage = age.tostring();         return theage;     }      public int getpoplength() {         return poplength;     }      public void setpoplength(int i){         this.poplength = i;     }      public int getpopulation() {         return population;     }      public string getpopulationasstring() {         stringbuilder builder = new stringbuilder();         builder.append(population);         string pop = builder.tostring();         return pop;     }      public void setpopulation(int population) {         this.population = population;     }      public string getcityname() {         return cityname;     }      public void setcityname(string cityname) {         cityname = cityname;     }      //end of getters , setters } 

human.java:

package jamiescity;  public class human {      private string firstname = "firstname";     private string lastname = "lastname";     private int age = 99;     private string gender = null;      public int getage(){         return age;     }      public string getgender() {         return gender;     }      public void setgender(string gender) {         this.gender = gender;     }      public void setage(int age){         age = age;     }      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 human(string firstname, string lastname, int age, string gender){         this.firstname = firstname;         this.lastname = lastname;         this.age = age;         this.gender = gender;     }  } 

any appreciated. :)

suggestions:

  • since looks assignment, i'm going avoid giving code, rather general suggestions should started.
  • create int index variable whatever array or collection holds humans -- here looks thepeople array. make index non-static field.
  • in next button's actionlistener, advance index, make sure it's not same size or bigger array or collection, human index, , display in gui.
  • conversely in previous button, decrement index, make sure it's 0 or bigger, , human index, , display in gui.
  • you want decide want happen should index hit boundary -- either become less 0 or equal array's length. if want cycle search, if gets less zero, you'll want assign length - 1 or if gets length size, assign 0.

unrelated suggestions:

  • avoid null layouts. while null layouts , setbounds() might seem swing newbies easiest , best way create complex gui's, more swing gui's create more serious difficulties run when using them. won't resize components when gui resizes, royal witch enhance or maintain, fail when placed in scrollpanes, gawd-awful when viewed on platforms or screen resolutions different original one.
  • you want learn , use java naming conventions. variable names should begin lower letter while class names upper case letter. learning , following allow better understand code, , allow better understand code of others.

ok lied , did create test concepts:

import javax.swing.*; import javax.swing.text.jtextcomponent; import java.awt.borderlayout; import java.awt.component; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.insets; import java.awt.event.actionevent; import java.util.arraylist; import java.util.list;  @suppresswarnings("serial") public class simplecitygui extends jpanel {     private simplecity city = new simplecity();     private simplehumanpanel humanpanel = new simplehumanpanel();      public simplecitygui() {         humanpanel.setfocusable(false);         humanpanel.setborder(borderfactory.createtitledborder("current human"));          jpanel btnpanel = new jpanel();         btnpanel.add(new jbutton(new addhumanaction("add")));         btnpanel.add(new jbutton(new nextaction("next")));         btnpanel.add(new jbutton(new previousaction("previous")));          setlayout(new borderlayout());         add(humanpanel, borderlayout.center);         add(btnpanel, borderlayout.page_end);     }      private class addhumanaction extends abstractaction {         simplehumanpanel innerhumanpanel = new simplehumanpanel();          public addhumanaction(string name) {             super(name);             int mnemonic = (int) name.charat(0);             putvalue(mnemonic_key, mnemonic);         }          @override         public void actionperformed(actionevent e) {             innerhumanpanel.clear();             component parentcomponent = simplecitygui.this;             simplehumanpanel message = innerhumanpanel;             string title = "create human";             int optiontype = joptionpane.ok_cancel_option;             int messagetype = joptionpane.plain_message;             int selection = joptionpane.showconfirmdialog(parentcomponent,                     message, title, optiontype, messagetype);              if (selection == joptionpane.ok_option) {                 city.addhuman(innerhumanpanel.createhuman());                 humanpanel.sethuman(city.getcurrenthuman());             }         }     }      private class nextaction extends abstractaction {          public nextaction(string name) {             super(name);             int mnemonic = (int) name.charat(0);             putvalue(mnemonic_key, mnemonic);         }          @override         public void actionperformed(actionevent e) {             simplehuman nexthuman = city.next();             if (nexthuman != null) {                 humanpanel.sethuman(nexthuman);             }         }     }      private class previousaction extends abstractaction {          public previousaction(string name) {             super(name);             int mnemonic = (int) name.charat(0);             putvalue(mnemonic_key, mnemonic);         }          @override         public void actionperformed(actionevent e) {             simplehuman previoushuman = city.previous();             if (previoushuman != null) {                 humanpanel.sethuman(previoushuman);             }         }     }      private static void createandshowgui() {         simplecitygui mainpanel = new simplecitygui();          jframe frame = new jframe("simplecitygui");         frame.setdefaultcloseoperation(jframe.dispose_on_close);         frame.getcontentpane().add(mainpanel);         frame.pack();         frame.setlocationbyplatform(true);         frame.setvisible(true);     }      public static void main(string[] args) {         swingutilities.invokelater(new runnable() {             public void run() {                 createandshowgui();             }         });     } }  @suppresswarnings("serial") class simplehumanpanel extends jpanel {     private static final int cols = 10;     private static final insets insets = new insets(5, 5, 5, 5);     private jtextfield firstnamefield = new jtextfield(cols);     private jtextfield lastnamefield = new jtextfield(cols);     private jtextcomponent[] textcomponents = { firstnamefield, lastnamefield };     private simplehuman human;      public simplehumanpanel() {         setlayout(new gridbaglayout());         add(new jlabel("first name:"), creategbc(0, 0));         add(firstnamefield, creategbc(1, 0));         add(new jlabel("last name:"), creategbc(0, 1));         add(lastnamefield, creategbc(1, 1));     }      @override     public void setfocusable(boolean focusable) {         super.setfocusable(focusable);         (jtextcomponent jtextcomponent : textcomponents) {             jtextcomponent.setfocusable(focusable);         }     }      public void sethuman(simplehuman human) {         this.human = human;         firstnamefield.settext(human.getfirstname());         lastnamefield.settext(human.getlastname());     }      public simplehuman gethuman() {         return human;     }      public void clear() {         this.human = null;         (jtextcomponent jtextcomponent : textcomponents) {             jtextcomponent.settext("");         }     }      public simplehuman createhuman() {         string firstname = firstnamefield.gettext();         string lastname = lastnamefield.gettext();         human = new simplehuman(firstname, lastname);         return human;     }      private static gridbagconstraints creategbc(int x, int y) {         gridbagconstraints gbc = new gridbagconstraints();         gbc.gridx = x;         gbc.gridy = y;         gbc.insets = insets;         gbc.fill = gridbagconstraints.horizontal;         return gbc;     } }  class simplecity {     private list<simplehuman> humanlist = new arraylist<>();     private int humanlistindex = -1; // start nonsense value      public void addhuman(simplehuman h) {         humanlist.add(h);         if (humanlistindex == -1) {             humanlistindex = 0;         }     }      public simplehuman gethuman(int index) {         return humanlist.get(index);     }      public simplehuman getcurrenthuman() {         if (humanlistindex == -1) {             return null;         }         return humanlist.get(humanlistindex);      }      public simplehuman next() {         if (humanlistindex == -1) {             return null;         }          humanlistindex++;         humanlistindex %= humanlist.size(); // set 0 if == size         return humanlist.get(humanlistindex);     }      public simplehuman previous() {         if (humanlistindex == -1) {             return null;         }          humanlistindex--;         humanlistindex += humanlist.size();         humanlistindex %= humanlist.size();         return humanlist.get(humanlistindex);     } }  class simplehuman {     private string firstname;     private string lastname;      public simplehuman(string firstname, string lastname) {         this.firstname = firstname;         this.lastname = lastname;     }      public string getfirstname() {         return firstname;     }      public string getlastname() {         return lastname;     }      @override     public int hashcode() {         final int prime = 31;         int result = 1;         result = prime * result                 + ((firstname == null) ? 0 : firstname.hashcode());         result = prime * result                 + ((lastname == null) ? 0 : lastname.hashcode());         return result;     }      @override     public boolean equals(object obj) {         if (this == obj)             return true;         if (obj == null)             return false;         if (getclass() != obj.getclass())             return false;         simplehuman other = (simplehuman) obj;         if (firstname == null) {             if (other.firstname != null)                 return false;         } else if (!firstname.equals(other.firstname))             return false;         if (lastname == null) {             if (other.lastname != null)                 return false;         } else if (!lastname.equals(other.lastname))             return false;         return true;     }      @override     public string tostring() {         return "simplehuman [firstname=" + firstname + ", lastname=" + lastname                 + "]";     }  } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -