Passing PageParameters From WicketPanel - java

How could I use PageParameters on a Wicketpanel?
I'm willing to load images from filesystem on a WicketPanel, and I found a tutorial for that, but they are using a Page, and in my case, I want to mount the images on a Panel. What should I change in this class or do I HAVE to implement a PageClass for this usecase?
http://wicketinaction.com/2011/07/wicket-1-5-mounting-resources/
https://github.com/martin-g/blogs/blob/master/request-mappers/src/main/java/com/wicketinaction/requestmappers/resources/images/ImageResourcesPage.java
public class ImageResourcesPage extends WebPage {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPage(final PageParameters parameters) {
super(parameters);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}
Thanks

The example code shown does not actually use the pageParameters from the WebPage in the image handling at all, but has an additional PageParameters imageParameters field for the images. There's no reason you can't do the same in a Panel.
Something along the lines of
public class ImageResourcesPanel extends Panel {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPanel(final String wicketId) {
super(wicketId);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}
should work just as well as the page version shown.
I'm not sure final fields for imageParameters and imageResourceReference are appropriate though. I would probably just make them local variables within the populateItem(ListItem<String> item) method.
Update based on comments:
It appears this example produces links to images and what you want is embedded images. A better starting point for that might be the images example in the wicket-library examples page. The
ImageResourceReference code from this example might however still be useful in conjunction with the other example.

Can't you just hand over the page parametersfrom the Panel/Page you embed it in?
Alternatively you can use
RequestCycle.get().getPageParameters()
but I think handing it over from the embedding component would be cleaner.

Got it! I Had just to add the IModel as argument in the ImageResourcePanel-Constructor.
`public class ImageResourcesPanel extends Panel {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPanel(final String wicketId, IModel<Book> book) {
super(wicketId, book);
int refNumber = book.getModelObject().getRefNumber();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
imageParameters.set("ref_number", refNumber);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}`

Related

wicket form clear choice after refresh

I'm currently using three different forms, RadioChoice, DateField and DropDownChoice, in an application where the page reacts based on what the user picks from this form. The problem here is that when I submit the form that is using DateField and DropDownChoice, it does an refresh of the page and the choice from the RadioChoice is remembered but the default choice is shown instead. So my question is if it's either possible to clear the values and set them back to default after a refresh, or make the submit of DateField and DropDownChoice not refresh the page?
//RADIO CHOICE
RadioChoice<String> radioChoice = new RadioChoice<String>("radio", new PropertyModel<String>(this, "selectedRadio"),this.radioChoiceList);
radioChoice.add(new AjaxFormChoiceComponentUpdatingBehavior()
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onUpdate(AjaxRequestTarget target)
{
target.appendJavaScript(changeBaseLayerJS(Page.this.currentMap, Page.this.selectedRadio));
Page.this.currentMap = Page.this.selectedRadio;
}
});
Form<?> radioForm = new Form<Void>("radioForm");
add(radioForm);
radioForm.add(radioChoice);
//DATEFIELD AND DROPDOWNCHOICE
DateField fromDateField = new DateField("fromDateField", new PropertyModel<Date>(
this, "fromDate"));
DateField toDateField = new DateField("toDateField", new PropertyModel<Date>(
this, "toDate"));
DropDownChoice<String> idvNameMenu = new DropDownChoice<String>("idvNameMenu", new PropertyModel<String>(this, "idvTrackName"), individualChoiceList);
Form<?> trackingForm = new Form<Void>("trackingForm"){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit()
{
//do stuff
}
};
Normal (non-Ajax) form submit leads to full page repaint. Ajax form submit will repaint only the components you put into the AjaxRequestTarget.
You can use form.add(new AjaxFormSubmittingBehavior() {...}) to do it with Ajax.
Or you can zero-fy you model objects in onSubmit:
#Override
protected void onSubmit()
{
// do stuff
// save in database
fromDate = null; // or = new Date();
toDate = null;
idvTrackName = "some good default value";
}

getSelectedItem JComboBox with GlazedLists AutocompleteSupport Returns Null

I'm a bit new to programming so sorry if there is a few things that could have been done better
My combobox is successfully filled with my string array and the auto-complete works fine. I just cant get the text in the combobox.
returns java.lang.NullPointerException
private ArrayList<String> arrRekening;
private ArrayList<String> arrEienaar;
private String[] sarrRekening;
private String[] sarrEienaar;
public NewConnectionPoint() {
arrAccount = new ArrayList<String>();
arrOwner = new ArrayList<String>();
FillCombo(arrAccount , "Owners", "OwnerName");
FillCombo(arrOwner , "Accounts", "AccountName");
sarrOwner= arrOwner.toArray(new String[arrOwner .size()]);
sarrAccount= arrAccount.toArray(new String[arrAccount.size()]);
JComboBox<String> comboAccount = new JComboBox<String>();
AutoCompleteSupport<String> supAccount = AutoCompleteSupport.install(comboRekening, GlazedLists.eventList(Arrays.asList(sarrAccount)));
supAccount.setStrict(true);
JComboBox<String> comboOwner = new JComboBox<String>();
AutoCompleteSupport<String> supOwner = AutoCompleteSupport.install(comboOwner,GlazedLists.eventList(Arrays.asList(sarrOwner)));
supOwner.setStrict(true);
JButton btnShow = new JButton("ShowSelectedr");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Error occurs at this line
JOptionPane.showMessageDialog(null, comboOwner.getSelectedItem().toString());
});}
}
//Data loaded into arraylists from a Database with sql
private void FillCombo(ArrayList<String> ComboElements, String sTable, String sColumn){
try{
Data.changeQuery(sTable);// database connection fine returns and fills combobox
while(MyData.rs.next()){
String sReturn= MyData.rs.getString(sColumn);
ComboElements.add(sReturn);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
The fundamental difficulty you're experiencing here is that you're trying to leverage the GlazedLists package without properly embracing it's core utility: EventLists.
You can easily side-step your difficulties if you use EventLists rather than ArrayLists.
If you really want to you can keep your FillCombo method returning an ArrayList (perhaps better name as getElements()) but straight-away initiate an EventList, use the GlazedLists EventComboBoxModel to link the EventList to the JComboBox and then you'll find your combobox getSelectedItem() should work fine.
The modified code to hook a list up to a combobox with autocomplete support will look something like this:
...
FillCombo(arrOwner , "Owners", "OwnerName");
EventList<String> ownerEventList = GlazedLists.eventList(arrOwner);
EventComboBoxModel<String> ownerModel = new EventComboBoxModel<String>(ownerEventList);
JComboBox comboOwner = new JComboBox(ownerModel);
AutoCompleteSupport<String> supOwner = AutoCompleteSupport.install(comboOwner,ownerEventList);
supOwner.setStrict(true);
...

Wicket ImageResourceReference ist mounted multiple times everytime the page is reloaded

I'm trying to mount an ImageResourceReference on my Page, but the ExternalLink is mounted multiple times (everytime I reload the page, I get a new additional link (same one).
For example when I start the server and load the page for the first time, there's just one ExternalLink, the second time, two links, third time three, etc...
What could be the reason for that?
Here is my code:
WebApp.java:
void init() {
.....
mountResource("/book/number/${number}/images/ray/${name}", new ImageResourceReference());
....
}
ImageResourcesPanel:
public class ImageResourcesPanel extends Panel {
private static final long serialVersionUID = -8723530004274531683L;
private static Logger logger = LoggerFactory.getLogger(ImageResourcesPanel.class
.getName());
/**
* The image names for which dynamic images will be generated
*/
private static List<String> IMAGE_NAMES = new ArrayList<String>();
public ImageResourcesPanel(final String wicketId, final IModel<Device> model) {
super(wicketId, model);
String pathToImage = "images";
IMAGE_NAMES.add(pathToImage);
ListView<String> listView = new ListView<String>("list", IMAGE_NAMES) {
private static final long serialVersionUID = 1L;
#Override
protected void populateItem(ListItem<String> item) {
logger.debug("Executed!");
ResourceReference imagesResourceReference = new ImageResourceReference();
PageParameters imageParameters = new PageParameters();
int number = model.getObject().getNumber();
String imageName = item.getModelObject();
String folder = model.getObject().getLinkToFolder();
imageParameters.set("name", imageName);
imageParameters.set("number", number);
imageParameters.set("folder", folder);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}
Got it!
I just had to make the ListView empty after mounting the image on the page. I just added a line of code after adding the link to the ListView-Item:
`IMAGE_NAMES.remove(pathToImage);`

How to get images to display it in Wicket?

I am stuck with images. I need to upload an image and then display it on my page.
What I am doing now is uploading file like this:
private Picture picture; *// picture model*
private FileUploadField fileUpload;
public PictureUploader() {
Form<?> form = new Form<Void>("uploadForm") {
/**
*
*/
private static final long serialVersionUID = -694488846250739923L;
protected void onSubmit() {
FileUpload uploadedFile = fileUpload.getFileUpload();
File newFile = new File(uploadedFile.getClientFileName());
picture.setImage(newFile);
PageParameters pageParameter = new PageParameters();
pageParameter.put("file", picture.getImage());
setResponsePage(DataPage.class,pageParameter);
}
};
add(form);
form.setMultiPart(true);
form.add(setFileUpload(new FileUploadField("fileUpload")));
}
Then I submit it and go to DataPage ( I show only the constructor):
public DataPage(final PageParameters parameters) {
File file;
if (parameters.containsKey("file")) {
// WHAT TO DO HERE? SINCE GET() FROM PAGEPARAMETERS DOES NOT WORK FOR IT!
}
final Label result = new Label("result", ?????);
add(result);
}
Who knows how to make it, please, help me figure it out.

GXT-3 issue to load data for my Chart

My problem is annoying. My server side is generating 12 random numbers (double here).
My Client side received the correct data but nothing is displayed in my Chart. That worked fine with hardcoded data in the store but not with a REST call.
The transfer between my server and my client is that :
[{"key":"key0","value":0.47222548599297787},{"key":"key1","value":0.6009173797369691},{"key":"key2","value":0.13880104282435624},{"key":"key3","value":0.01804674319345545},{"key":"key4","value":0.5547733564202956},{"key":"key5","value":0.8229999661308851},{"key":"key6","value":0.8959346004391032},{"key":"key7","value":0.6848052288628435},{"key":"key8","value":0.10222856671111813},{"key":"key9","value":0.6931371931409103},{"key":"key10","value":0.2994297934549003},{"key":"key11","value":0.47566752196381334}]
Here my simple class used for my test. I am a newbie with GXT 3
public void onModuleLoad() {
final ListStore<JSOModel> store;
final ContentPanel panel = new FramedPanel();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/ws/DocumentService/v1/test");
builder.setHeader("Accept", "application/json");
HttpProxy proxy = new HttpProxy(builder);
final Loader<ListLoadConfig, ListLoadResult<JSOModel>> loader = new ListLoader<ListLoadConfig, ListLoadResult<JSOModel>>(proxy, new DataReader<ListLoadResult<JSOModel>, String>() {
#Override
public ListLoadResult<JSOModel> read(Object loadConfig, String data) {
List<JSOModel> jsoModels = new ArrayList<JSOModel>();
JsArray<JSOModel> jsoModelJsArray = JSOModel.arrayFromJson(data);
if(jsoModelJsArray != null) {
for(int i = 0; i < jsoModelJsArray.length(); i++) {
jsoModels.add(jsoModelJsArray.get(i));
}
}
return new ListLoadResultBean<JSOModel>(jsoModels);
}
});
store = new ListStore<JSOModel>(new ModelKeyProvider<JSOModel>() {
#Override
public String getKey(JSOModel item) {
return item.get("key");
}
});
loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, JSOModel, ListLoadResult<JSOModel>>(store) {
#Override
public void onLoad(LoadEvent<ListLoadConfig, ListLoadResult<JSOModel>> event) {
ListLoadResult<JSOModel> loaded = event.getLoadResult();
if(loaded.getData() == null) {
store.replaceAll(new ArrayList<JSOModel>());
} else {
store.replaceAll(loaded.getData());
}
}
});
Chart<JSOModel> chart = new Chart<JSOModel>();
chart.setStore(store);
chart.setShadowChart(true);
NumericAxis<JSOModel> axis = new NumericAxis<JSOModel>();
axis.setPosition(Chart.Position.LEFT);
axis.addField(new ValueProvider<JSOModel, Number>() {
#Override
public Number getValue(JSOModel JSOModel) {
return JSOModel.getNumber("value");
}
#Override
public void setValue(JSOModel JSOModel, Number number) {
}
#Override
public String getPath() {
return "key";
}
});
axis.setTitleConfig(new TextSprite("Number of hits"));
axis.setWidth(50);
axis.setMinimum(0);
axis.setMaximum(100);
chart.addAxis(axis);
PathSprite odd = new PathSprite();
odd.setOpacity(1);
odd.setFill(new Color("#dff"));
odd.setStroke(new Color("#aaa"));
odd.setStrokeWidth(0.5);
axis.setGridOddConfig(odd);
CategoryAxis<JSOModel, String> horizontalAxis = new CategoryAxis<JSOModel, String>();
horizontalAxis.setPosition(Chart.Position.BOTTOM);
horizontalAxis.setField(new ValueProvider<JSOModel, String>() {
#Override
public String getValue(JSOModel JSOModel) {
return JSOModel.get("key");
}
#Override
public void setValue(JSOModel JSOModel, String s) {
}
#Override
public String getPath() {
return "key";
}
});
horizontalAxis.setTitleConfig(new TextSprite("month of year"));
chart.addAxis(horizontalAxis);
LineSeries<JSOModel> column = new LineSeries<JSOModel>();
column.setYAxisPosition(Chart.Position.LEFT);
column.setStroke(new RGB(148,174,10));
column.setHighlighting(true);
chart.addSeries(column);
axis.addField(column.getYField());
chart.addSeries(column);
chart.setHeight(100);
chart.setWidth(100);
Button b = new Button("ha");
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
loader.load();
}
});
RootPanel.get().add(b);
panel.setCollapsible(true);
panel.setHeadingText("Column Chart");
panel.setPixelSize(620, 500);
panel.setBodyBorder(true);
VerticalLayoutContainer layout = new VerticalLayoutContainer();
panel.add(layout);
chart.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1,1));
layout.add(chart);
chart.setBackground(new Color("#dff"));
RootPanel.get().add(panel);
There are two ways to wire the chart into a store. One is to simply specify that the chart is using a store via setStore, as you have done:
chart.setStore(store);
When you do this, you must also inform the chart when it must redraw everything - you must call:
chart.redrawChart();
This call must be made shortly after the load is completed - consider doing it at the end of onLoad.
Why is this required? In some cases, developers want to make many changes to the store, one at a time, and if the chart automatically updated after each change, that would spawn many slow changes to the data model, and could end up looking strange. In a case like this, you would only call redrawChart() after all changes were complete.
There is another option however - instead of calling setStore, you can call bindStore, and ask the Chart to automatically update whenever any change occurs to the chart:
chart.bindStore(store);
In your case, this is likely the correct answer.

Categories

Resources