These are my classes.
public class Prova {
private static HashMap<String,UtenteAstratto> map = new HashMap<String,UtenteAstratto>();
public static void main(String[] args) {
DatiPersonali dp1 = new DatiPersonali("a", "a", "a", "a", "a", "a", "a", "a");
UtenteRegistrato u1 = new UtenteRegistrato(dp1);
map.put(u1.getUsername(), u1);
DatiPersonali dp2 = new DatiPersonali("b", "b", "b", "b", "b", "b", "b", "b");
UtenteRegistrato u2 = new UtenteRegistrato(dp2);
AdminDecorator ad = new AdminDecorator(u2);
map.put(ad.getUsername(), ad);
DatiPersonali dp3 = new DatiPersonali("c", "c", "c", "c", "c", "c", "c", "c");
UtenteRegistrato u3 = new UtenteRegistrato(dp3);
GestoreDecorator gd = new GestoreDecorator(u3);
map.put(gd.getUsername(), gd);
System.out.println(map.toString());
System.out.println();
save(map);
load();
}
private static void load() {
try {
String nomeFile = "fileProva.sav";
FileInputStream fis = new FileInputStream(nomeFile);
ObjectInputStream ois = new ObjectInputStream( fis );
Object o = ois.readObject();
if( !o.equals("") ) {
map = (HashMap<String,UtenteAstratto>) o;
for(Entry elem: map.entrySet()) {
System.out.println("username= " + elem.getKey() + " " + elem.getValue());
}
}
ois.close();
fis.close();
}catch( Exception e ) {
e.printStackTrace();
}
}
public static void save(Object o) {
try {
FileOutputStream fos = new FileOutputStream("fileProva.sav");
ObjectOutputStream oos = new ObjectOutputStream( fos );
oos.writeObject(o);
oos.close();
fos.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
With this error.
java.lang.NullPointerException
at Utilities_Utente.UtenteDecorator.toString(UtenteDecorator.java:9)
at java.base/java.lang.String.valueOf(String.java:3352)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:166)
at Utilities_Utente.Prova.load(Prova.java:43)
at Utilities_Utente.Prova.main(Prova.java:31)
Class GestoreDecorator
public class GestoreDecorator extends UtenteDecorator implements Serializable{
private static final long serialVersionUID = 8246098147192933576L;
public GestoreDecorator (UtenteAstratto u){
DatiPersonali dp =new DatiPersonali(u.getDatiPersonali());
utente = new UtenteRegistrato(dp);
utente.setPermesso(Permesso.GESTORE);
}
public void setPermesso(){
}
}
Class AdminDecorator
public class AdminDecorator extends UtenteDecorator implements Serializable{
private static final long serialVersionUID = -8816003037658470920L;
public AdminDecorator (UtenteAstratto u){
DatiPersonali dp = new DatiPersonali(u.getDatiPersonali());
utente = new UtenteRegistrato(dp);
// utente = (UtenteRegistrato) u;
utente.setPermesso(Permesso.ADMIN);
}
#Override
public void setPermesso() {
// TODO Auto-generated method stub
}
}
Class UtenteAstratto
public abstract class UtenteAstratto implements Comparable<UtenteAstratto>{
public enum Permesso { UTENTE, ADMIN, GESTORE };
public abstract String getUsername();//questo metodo serve nella classe Squadra.Squadra
public abstract String getPassword();//questo metodo serve nella classe Squadra.Squadra
public abstract DatiPersonali getDatiPersonali();//questo metodo serve nella classe Squadra.Squadra
public abstract Permesso getPermesso();
}
Class UtenteDecorator
public abstract class UtenteDecorator extends UtenteAstratto {
protected UtenteRegistrato utente;
public abstract void setPermesso();
public String toString(){
return utente.toString();
}
public int compareTo(UtenteAstratto o) {
return utente.compareTo(o);
}
public String getUsername() {
return utente.getUsername();
}
public String getPassword() {
return utente.getPassword();
}
public DatiPersonali getDatiPersonali() {
return utente.getDatiPersonali();
}
public Permesso getPermesso(){
return utente.getPermesso();
}
}
Class UtenteRegistrato
public class UtenteRegistrato extends UtenteAstratto implements Serializable{
private static final long serialVersionUID = -2593162236417203422L;
private DatiPersonali dp;
private Permesso permesso;
public UtenteRegistrato (DatiPersonali d) {
this.dp = d;
permesso = Permesso.UTENTE;
}//Costruttore
public Permesso getPermesso(){
return permesso;
//return
}
public void setPermesso(Permesso p) {
permesso = p;
}
public DatiPersonali getDatiPersonali (){
return dp;
}
public int hashCode() {
int parziale = super.hashCode();
final int primo = 41;
int result = parziale + primo * dp.hashCode() ;
return result;
}
public boolean equals(Object o) {
if (!(o instanceof UtenteRegistrato))
return false;
if (this == o)
return true;
UtenteRegistrato user = (UtenteRegistrato) o;
if (!getUsername().equals(user.getUsername()))
return false;
return true;
}//equals
public String toString() {
StringBuilder sb = new StringBuilder (500);
sb.append(permesso.toString() + " ");
sb.append(getDatiPersonali().toString());
return sb.toString();
}
public int compareTo(UtenteAstratto o) {
UtenteAstratto u = null;
if (o instanceof UtenteDecorator)
u= (UtenteDecorator) o;
else
u= (UtenteRegistrato) o;
if (getUsername().compareTo(u.getUsername())==0)
return 0;
if (dp.getCognome().compareTo(u.getDatiPersonali().getCognome()) <0)
return -1;
if (dp.getCognome().compareTo(u.getDatiPersonali().getCognome()) ==0 && dp.getNome().compareTo(u.getDatiPersonali().getNome()) <0)
return -1;
return 1;
}
#Override
public String getUsername() {
return dp.getUsername();
}
#Override
public String getPassword() {
return dp.getPassword();
}
}
And the views of debugger.
The view save.
enter image description here
The view load.
enter image description here
Now, my question is: Why when I load the Hashmap the value 1 and 2 (AdminDecorator and GestoreDecorator) are null?
You should read What is a NullPointerException, and how do I fix it?.
In particular, the stack trace is telling you which line of code is the problem:
java.lang.NullPointerException
at Utilities_Utente.UtenteDecorator.toString(UtenteDecorator.java:9)
The error occurred in UtenteDecorator.toString at line 9.
There is only one line of code in that toString method:
return utente.toString();
The only possible cause of a NullPointerException in that line of code is that utente is null.
The best thing you can do is force that field to never be null, by adding a constructor:
protected UtenteDecorator(UtenteRegistrato utente) {
this.utente = Objects.requireNonNull(utente,
"utente cannot be null.");
}
(Objects is the java.util.Objects class.)
If you don’t want to change the constructor, an alternative is to defensively code your toString method, so it won’t break when utente is null:
public String toString() {
return Objects.toString(utente, "(utente not defined)");
}
Related
So... My goal here to run this class through an array then fill the array with a .txt document with 43 instances which I will then take user data and compare the two to find an ideal match. I should note that this is for a seating plan -
The text document looks like so -
01 STANDARD True False True F False
public class Seat {
private String eMail = "";
private int number;
private String type;
private boolean window;
private boolean aisle;
private boolean table;
private String f;
private String b;
private boolean ease;
public Seat(int number, String type, boolean window, boolean aisle, boolean table, String f, String b, boolean ease) {
this.number = number;
this.type = type;
this.window = window;
this.aisle = aisle;
this.table = table;
this.f = f;
this.b = b;
this.ease = ease;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isWindow() {
return window;
}
public void setWindow(boolean window) {
this.window = window;
}
public boolean isAisle() {
return aisle;
}
public void setAisle(boolean aisle) {
this.aisle = aisle;
}
public boolean isTable() {
return table;
}
public void setTable(boolean table) {
this.table = table;
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public boolean isEase() {
return ease;
}
public void setEase(boolean ease) {
this.ease = ease;
}
}
public class Driver {
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("//Users//Mike//Desktop//Seats-2.txt"));
String reservation = inFile.nextLine();
Seat seat [] = new Seat [43];
//while (inFile.hasNextLine()){
//for(int i = 0; i <= reservation.length(); i++){
//System.out.println(reservation.toString(seat));
//}
//}
I've tried methods such as equals(reservation.toString()) how ever these won't work due to the array being built from the Class Seat.
Any guidance will be very helpful.
I'm not looking for easy fix, just some guidance on where to look.
Thank you
If the text file is small, let's just read it whole in a String
public static String ReadWholeFile(String filename) throws IOException
{
final File file = new File(filename);
final FileInputStream fis = new FileInputStream(file);
final byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return new String(data, "UTF-8");
}
And then parse line by line, converting in Seats
public List<Seat> getSeats(String filename) throws IOException {
final String[] lines = ReadWholeFile(filename).split("\n");
final List<Seat> ret = new ArrayList<Seat>();
for (int i=0; i<lines.length; i++)
try {
final String[] parts = lines[i].split("\\s"); // split on whitespaces
final int num = Integer.parseInt(parts[0]);
ret.add(new Seat(num, parts[1], isTrue(parts[2]), isTrue(parts[3]), isTrue(parts[4]), isTrue(parts[5]), isTrue(parts[6]));
}
catch (Exception e) { /* whatever */ }
return ret;
}
Strings that mean true are "T", "true", ...? If that's the case:
public static isTrue(String x) {
return x.startsWith("T") || x.startsWith("t");
}
if you really don't want to read the whole file, you could go with:
public static List<Seat> getSeats2(String filename) {
final List<Seat> ret = new ArrayList<Seat>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line;
while (line = br.readLine()) {
final String[] parts = line.split("\\s"); // split on whitespaces
// as above
}
}
catch (Exception e) { /* handle errors */ }
finally {
if (br != null)
try { br.close(); }
catch (Exception e) {}
}
return res;
}
Currently, I'm receiving this JSON input, which I have no control whatsoever:
{
"A" : {
"B" : {
"B" : [{
"Whatever" : "String",
"Number": 123
}
],
"SiblingObject" : true
}
}
}
Basically, I want to deserialize the B array that's inside the B object directly into the A class without having to create another extra class to wrap the B object. Something like this:
public class A {
private List<B> bList;
public List<B> getB() {
return bList;
}
#JsonProperty("B")
public void setB(List<B> bList) {
this.bList = bList;
}
}
I've tried doing
public class A {
private List<B> bList;
public List<B> getB() {
return bList;
}
#JsonProperty("B")
public void setB(Map<String, Object> bList) {
this.bList = (List<B>) bList.get("B");
}
}
but to no avail.
Any ideas?
There is one way of doing it. However, it will require traversing the input JSON twice.
In first pass, you create the normal A instance without the List.
In second pass, you use Jackson's node traversal to reach the correct B object and parse from there.
See the code below:
public class WrapperJsonTest {
public static void main(String[] args) {
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("wrapper.json");
A a = null;
try {
a = om.readValue(in, A.class);
} catch (Exception e){
e.printStackTrace();
}
in = Thread.currentThread().getContextClassLoader().getResourceAsStream("wrapper.json");
try {
JsonNode node = om.readValue(in, JsonNode.class).get("B").get("B");
JsonParser parser = node.traverse();
List<B> bList = om.readValue(parser, List.class);
a.setB(bList);
System.out.println(a.isSibling());
System.out.println(a.getB());
} catch (Exception e){
e.printStackTrace();
}
}
#JsonIgnoreProperties
public static class A {
#JsonIgnore
private List<B> bList;
private boolean sibling;
public List<B> getB() {
return bList;
}
public void setB(List<B> bList) {
this.bList = bList;
}
public boolean isSibling() {
return sibling;
}
public void setSibling(boolean sibling) {
this.sibling = sibling;
}
}
public static class B {
private String whatever;
public String getWhatever() {
return whatever;
}
public void setWhatever(String whatever) {
this.whatever = whatever;
}
#Override
public String toString() {
return whatever;
}
}
}
I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}
I trying to read an arraylist from a file into another arraylist but I keep getting errors. The file is called eventos.dat and the arraylist is from the type Evento. I want to create a new ArrayList<Evento> with the objects from the array on the file. Here is the method i'm using:
public class ListaEventos implements Serializable{
private ArrayList<Evento> eventos = new ArrayList();
public String adicionarEvento(Evento novo){
for (Evento evento : eventos) {
if(novo.equals(evento)){
return "Evento já existe";
}
}
eventos.add(novo);
return "ADICIONEI";
}
public ArrayList<Evento> getEventos() {
return eventos;
}
public Evento procuraEvento(String tituloEvento){
for (Evento evento : eventos){
if(tituloEvento.equals(evento.getTitulo())){
return evento;
}
}
return null;
}
public String editaEvento(Evento antigo, Evento novo){
for (int i=0;i<eventos.size();i++){
if(antigo.equals(eventos.get(i))){
eventos.get(i).setTitulo(novo.getTitulo());
eventos.get(i).setData(novo.getData());
eventos.get(i).setDescricao(novo.getDescricao());
eventos.get(i).setLocal(novo.getLocal());
eventos.get(i).setPrivado(novo.getPrivado());
return "Editei evento";
}
}
return "Evento não existe";
}
public String removeEvento(String removeTitulo){
Evento aux= procuraEvento(removeTitulo);
if(aux != null){
eventos.remove(aux);
return "Evento removido!";
}
return "Evento não existe";
}
public void gravaFicheiro(){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
out.writeObject(eventos);
out.close();
}
catch(IOException ex){
System.out.println("Não conseguiu gravar");
}
}
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
}
here is the Evento class:
public class Evento implements Serializable {
private String titulo = "Nao preenchido";
private String data = "Nao preenchido";
private String local = "Nao preenchido";
private String descricao = "Nao preenchido";
private String privado = "Nao preenchido";
private ArrayList<Contacto> convidados = new ArrayList();
public Evento() {
}
public Evento(String titulo, String data, String local, String descricao, String privado) {
this.titulo = titulo;
this.data = data;
this.local = local;
this.descricao = descricao;
this.privado = privado;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setData(String data) {
this.data = data;
}
public void setLocal(String local) {
this.local = local;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setPrivado(String privado) {
this.privado = privado;
}
public String getTitulo() {
return titulo;
}
public String getData() {
return data;
}
public String getLocal() {
return local;
}
public String getDescricao() {
return descricao;
}
public String getPrivado() {
return privado;
}
public ArrayList<Contacto> getConvidados() {
return convidados;
}
public void setConvidados(ArrayList<Contacto> convidados) {
this.convidados = convidados;
}
public String adicionaConvidado(String nomeConvidado){
Contacto novo = new Contacto();
for (Contacto contacto : this.convidados) {
if(nomeConvidado.equals(contacto.getNome())){
return "Contacto já foi convidado";
}
}
novo.setNome(nomeConvidado);
novo.setEmail("");
novo.setTelefone("");
convidados.add(novo);
return "ADICIONEI CONVIDADO";
}
public Evento(String titulo, String local) {
this.titulo = titulo;
this.local = local;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.local, other.local)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
Changed the method CarregaEvento to:
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
No errors but still doesn't work.
eventos=(ArrayList<Evento>) in.readObject();
This will not create a new type of an ArrayList<Evento>.
although you can create a new instance of an Evento with the String that is provided when you read the text file. you can use the split(String par1) method in the String class to create a new instance of Evento and add it to an arraylist.
refer to the JavaDocs for more info on splitting.
I have a DropDownChoice :
DropDownChoice timePeriod = new DropDownChoice("timePeriod", Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
My question is:
How to set the selected index to 2 or any other?
How to remove first default blank option?
Thank you.
You should be able to set the selected index by using a PropertyModel instead of hard-coding the values of the dropdown. I can't test at the moment, but it would be something like
String timePeriodValue = "Bi-Weekly";
DropDownChoice timePeriod = new DropDownChoice("timePeriod",
new PropertyModel(this, "timePeriodValue"),
Arrays.asList(/* your options */),
new IChoiceRenderer() {
// ...
// Again, this is pseudocode only
As a bonus, the very act of setting a default value should eliminate the blank option problem.
DropDownChoice has a constructor which accepts the default value.
Or in your code you can add timePeriod.setModel(Model.of(new TimePeriod(2, "Bi-Weekly")))
I guess TimePeriod has proper #equals() and #hashCode() implementations.
About the blank option: see org.apache.wicket.markup.html.form.AbstractSingleSelectChoice.isNullValid()
Lord Torgamus and martin-g thank you both of you. I did a small test. And it is working perfectly. As Lord Torgamus indicated,
#SuppressWarnings({ "unchecked", "rawtypes", "serial" })
public class MyPage extends WebPage {
public MyPage() {
add(new MyForm("form"));
}
private class MyForm extends Form {
public MyForm(String id) {
super(id);
setOutputMarkupPlaceholderTag(true);
setModel(new Model(new FormModel()));
final DropDownChoice timePeriod = new DropDownChoice("timePeriod", new PropertyModel(getModel(), "timePeriod"), Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
add(timePeriod);
timePeriod.setOutputMarkupPlaceholderTag(true);
timePeriod.add(new AjaxFormComponentUpdatingBehavior("onChange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
MyForm form = (MyForm) timePeriod.getParent();
FormModel formModel = (FormModel) form.getModelObject();
formModel.setTimePeriod(new TimePeriod(4, "Monthly"));
form.setModel(new Model(formModel));
target.addComponent(form);
}
});
}
#Override
public void onSubmit() {
System.out.println(getModelObject());
}
}
private class FormModel implements Serializable {
private TimePeriod timePeriod = new TimePeriod(2, "Bi-Weekly");
public FormModel() {
}
public TimePeriod getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(TimePeriod timePeriod) {
this.timePeriod = timePeriod;
}
#Override
public String toString() {
return "FormModel [timePeriod=" + timePeriod + "]";
}
}
private class TimePeriod implements Serializable {
private int id;
private String periodType;
public TimePeriod(int id, String periodType) {
super();
this.id = id;
this.periodType = periodType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPeriodType() {
return periodType;
}
public void setPeriodType(String periodType) {
this.periodType = periodType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + id;
result = prime * result + ((periodType == null) ? 0 : periodType.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;
TimePeriod other = (TimePeriod) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (id != other.id)
return false;
if (periodType == null) {
if (other.periodType != null)
return false;
} else if (!periodType.equals(other.periodType))
return false;
return true;
}
private LoginPage getOuterType() {
return LoginPage.this;
}
#Override
public String toString() {
return "TimePeriod [id=" + id + ", periodType=" + periodType + "]";
}
}
}
The above code is provided for other users as it might be helpful and I wrote it for testing purpose so all the classes are written in one .java file although it is not advisable.
Thank you.