Is it possible - to template this method? - java

I am new in Java and i have a few questions for more advanced developers.
I have Swing-based GUI application in which I have several AbstractActions.
A large group of AbstractActions creates new tab based on JPanel. For example:
// opens "Documents" tab
documentsAction = new AbstractAction(DOCUMENTS) {
#Override
public void actionPerformed(ActionEvent e) {
try {
int index = getTabIndex(DOCUMENTS);
if (index >= 0) {
// Tab exists, just open it.
tabbedPane.setSelectedIndex(index);
} else {
// No tab. Create it and open
newCatalogTab(new DocumentService(), DOCUMENTS);
}
} catch (ServiceException ex) {
printError(ex.getMessage());
}
}
};
documentsItem.setAction(documentsAction);
Where getTabIndex is:
private int getTabIndex(String tabName) {
int result = -1;
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (tabName.equals(tabbedPane.getTitleAt(i))) {
result = i;
break;
}
}
return result;
}
and newCatalogTab is:
private void newCatalogTab(ICatalog service, String Name) throws ServiceException {
CatalogPanel panel = new CatalogPanel(service);
tabbedPane.add(Name, panel);
tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
checkTabs(); // changes activity of buttons like "edit" and "delete"
}
So, many AbstractAction do the similar work:
Create instance of class, that extends AbstractPanel;
Pass data access interface (DocumentService in example) to instance;
Create a new tab with instance.
Can I somehow template this if data access interfaces will use different POJO's?
Can I create Generic interface and use it?
Can you show me right direction for thinking?
Thanks for wasting your time.

There are no templates in Java, so there will be some code duplication in any case. However, you can cut some of the boilerplate code by using factories. For example:
interface CatalogFactory {
public ICatalog makeCatalog();
}
class DocumentServiceFactory implements CatalogFactory {
#Override
public ICatalog makeCatalog() {
return new DocumentService();
}
}
class TabAction extends AbstractAction {
private final String name;
private final CatalogFactory factory;
//Appropriate constructor...
#Override
public void actionPerformed(ActionEvent e) {
//...
newCatalogTab(factory.makeCatalog(), name);
//...
}
}
Then you can do
documentsItem.setAction(new TabAction(DOCUMENTS, new DocumentServiceFactory()));
without having to create a separate anonymous AbstractAction for each tab.
Similarly for panels and possibly other objects where this pattern fits.

Related

Codename One: i want to send a JsonArray to the server using a Hashtable in connection request

I am building an app that will be submitting the details of your siblings to the database.
MY idea is since i dont know number of your children, i just have a floating button that am using to call a class that adds a contaner with some textFields to be filled.
so I have like a Form here....
private Button btnSubmit;
private Container cnt_box;
public class ChildrenForm extends Form
{
private List<Child> listofchildren;
public ChildrenForm()
{
super("CHILDREN DETAILS",BoxLayout.y());
FloatingActionButton fab=FloatingActionButton.createFAB(FontImage.MATERIAL_ADD);
fab.bindFabToContainer(this);
fab.addActionListener((e) -> addNewChild());
getToolbar().addMaterialCommandToRightBar("", FontImage.MATERIAL_CLEAR_ALL, (e) ->
clearAll());
btnSubmit=new Button("Submit");
cnt_box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
cnt_box.add(btnSubmit);
add(cnt_box);
}
//....here i have some other methods...
}
i have a method to enable the editing here....
public void edit()
{
txtname.startEditingAsync();
txtname3.startEditingAsync();
txtbirth.startEditingAsync();
txtdbirth.startEditingAsync();
}
the floatingAction Button calls this method here....
public void addNewChild()
{
Childdetails td=new Childdetails("","","","",false);
add(td);
revalidate();
td.edit();
}
that method now called this class which i want to take the details showing this container.....
public class Childdetails extends Container
{
private TextField txtname;
private TextField txtname3;
private TextField txtbirth;
private TextField txtdbirth;
private CheckBox done=new CheckBox();
private Container cnt_child;
public Childdetails(String name,String name3,String birthcertno,String dateofbirth ,boolean checked)
{
super(new BorderLayout());
cnt_child=new Container();
cnt_child.addComponent(new Label("First Name"));
txtname = new TextField(name);
txtname.setHint("First Name");
cnt_child.addComponent(txtname);
cnt_child.addComponent(new Label("Surname"));
txtname3 = new TextField(name3);
txtname3.setHint("Surname");
cnt_child.addComponent(txtname3);
cnt_child.addComponent(new Label("Birth Certificate/Notification No"));
txtbirth = new TextField(birthcertno);
txtbirth.setHint("Birth Certificate No:");
cnt_child.addComponent(txtbirth);
cnt_child.addComponent(new Label("Date of Birth"));
txtdbirth = new TextField(dateofbirth);
txtdbirth.setHint("dd/MM/yyyy");
cnt_child.addComponent(txtdbirth);
add(CENTER,cnt_child);
add(LEFT,done);
done.setSelected(checked);
}
public void edit()
{
txtname.startEditingAsync();
txtname3.startEditingAsync();
txtbirth.startEditingAsync();
txtdbirth.startEditingAsync();
}
public boolean isChecked(){
return done.isSelected();
}
public String getText(){
return txtname.getText();
}
}
this is the method which am using to delate any selected container....but i understand its because of that save method......
private void clearAll()
{
int cc=getContentPane().getComponentCount();
for(int i=cc-1; i>=0; i--)
{
Childdetails t=(Childdetails)getContentPane().getComponentAt(i);
if(t.isChecked())
{
t.remove();
}
}
save();
getContentPane().animateLayout(300);
}
the save method....which after following some tutorial i believe its saving the taken data.... here
private void save()
{
listofchildren = new ArrayList<>();
Childdetails detail=new Childdetails("","","","",false);
Child child=new Child()
.name.set(detail.getText())
.name3.set(detail.getText())
.birthcertno.set(detail.getText())
.dateofbirth.set(detail.getText())
.checked.set(detail.isChecked());
listofchildren.add(child);
PropertyIndex.storeJSONList("child.json", listofchildren);
}
i also have a class i constructed following certain tutorial to save the data.....here
public class Child implements PropertyBusinessObject
{
public final Property<String,Child> name=new Property<>("firstname","");
public final Property<String,Child> name3=new Property<>("Surname","");
public final Property<String,Child> birthcertno=new Property<>("BirthCertNo","");
public final Property<String,Child> dateofbirth=new Property<>("dateofbirth","");
public final BooleanProperty<Child> checked=new BooleanProperty<>("checked", false);
private final PropertyIndex idx=new PropertyIndex(this,"Todo", name, name3, birthcertno, dateofbirth, checked);
#Override
public PropertyIndex getPropertyIndex(){
return idx;
}
now my main main problem... i just want when that submit button is pressed, to send the filled details..... i tried this,,,
btnSubmit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent evt)
{
Log.p("Button pressed", 1);
save();
Log.p("data saved...", 1);
if(existsInStorage("child.json"))
{
Log.p("loading data ...", 1);
listofchildren=new Child().getPropertyIndex().loadJSONList("child.json");
String NationalID=Storage.getInstance().readObject("NationalID").toString();
String UserName=Storage.getInstance().readObject("UserName").toString();
Hashtable hash=new Hashtable();
hash.put("ChildDet", listofchildren);
hash.put("ReadIdCopy", NationalID);
hash.put("UserName",UserName);
final Result res=Result.fromContent(hash);
final String checkthis=res.toString();
//--------check url......
String myUrl="http://localhost:50111/AddChildren";
String Reply="";
requestclass c=new requestclass();
try {
Reply=c.checking(checkthis,myUrl);
} catch (IOException ex) {
// Logger.getLogger(AddChildren.class.getName()).log(Level.SEVERE, null, ex);
} catch (requestclass.JSONException ex) {
// Logger.getLogger(AddChildren.class.getName()).log(Level.SEVERE, null, ex);
}
if(Reply.equals("SuccesfullyRecieved"))
{
Dialog.show("SuccesfullyRecieved", "Details Succesfuly Recieved", "OK", null);
/*----redirect---*/
nextofkin nkin=new nextofkin();
nkin.nxtofkscreen();
}
else if(Reply.equals("sorry"))
{
Dialog.show("SORRY!!!", "Seems their is a problem updating Next of kin details... try again", "OK", null);
}
else
{
Dialog.show("Error", "Something went wrong, try checking your connection and try again later.", "OK", null);
}
}
else
{
ToastBar.showErrorMessage("Sorry, no data to submit....");
}
}
});
i dont know how to do it,,,, also my save method has some errors...please help me out, thanks in advance
This is caused by this line:
Childdetails t=(Childdetails)getContentPane().getComponentAt(i);
What you are doing here is looping over all the components in the content pane and downcasting them to Childdetails.
This is bad. You don't check instanceof which would be helpful. You might have other problems but this line:
add(cnt_box);
Specifically adds a non Childdetails component to the content pane (doing add without a context on a Form implicitly adds to the content pane).
Also about startEditingAsync. This is wrong.
This isn't the way to make them visible.
Notice your code adds a lot of components before the form is shown and uses animateLayout on these instances. This is probably why things aren't visible since you do that on a Form that isn't shown yet (from the constructor) and so the animation "runs" without any effect. The components are probably in the wrong area.
I suggest removing that whole block of startEditingAsync and also try:
if(getContentPane().isInitialized()) {
getContentPane().animateLayout(300);
}

Javafx Link/Bind Treeview Items to ObservableList

I'm trying to find an easy way of linking a TreeView of type Download to an ObservableList of the same type.
MainController.java
public class MainController {
private ObservableList<Download> downloads = FXCollections.observableArrayList();
#FXML private TreeView<Download> $TreeDownloads;
#FXML
public void initialize() {
$TreeDownloads.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
$TreeDownloads.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT);
$TreeDownloads.setShowRoot(false);
downloads.addListener(new ListChangeListener<Download>() {
#Override
public void onChanged(Change<? extends Download> c) {
if (c.wasAdded()) {
addDownloads(c.getAddedSubList());
}
if (c.wasRemoved()) {
//
}
}
});
downloads.add(new Download("3847"));
downloads.add(new Download("3567"));
downloads.add(new Download("2357"));
}
private void addDownloads(List<? extends Download> downloads) {
downloads.forEach(download -> {
TreeItem<Download> treeItem = new TreeItem<>(download);
$TreeDownloads.getRoot().getChildren().add(treeItem);
new Thread(download::start).start();
});
}
private void removeDownloads(List<? extends Download> downloads) {
// remove treeitems from the treeview that hold these downloads
}
}
Download.java
public class Download {
private DoubleProperty progress = new SimpleDoubleProperty(0D);
private StringProperty id = new SimpleStringProperty("");
public Download(String id) {
this.id.set(id);
}
public void start() {
while (progress.getValue() < 1) {
try {
Thread.sleep(1000);
progress.add(0.1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public String toString() {
return id.getValue();
}
}
How do i implement a remove by Object(Download) mechanism, and is there an easier way to bind observablelist's items to a treeview?
Still not entirely certain what the exact problem is, all pretty straightforward:
First off, your list change listener implementation is incorrect, it must advance the subChanges before accessing its state (you did run your posted code, or not ;)
downloads.addListener(new ListChangeListener<Download>() {
#Override
public void onChanged(Change<? extends Download> c) {
// this while was missing
while (c.next()) {
if (c.wasAdded()) {
addDownloads(c.getAddedSubList());
}
if (c.wasRemoved()) {
// accessing the list of removed elements is .. plain standard api
removeDownloads(c.getRemoved());
}
}
}
});
Now implement the removal of the corresponding treeItems:
private void removeDownloads(List<? extends Download> downloads) {
// remove treeitems from the treeview that hold these downloads
List<TreeItem<Download>> treeItemsToRemove = treeDownloads.getRoot().getChildren().stream()
.filter(treeItem -> downloads.contains(treeItem.getValue()))
.collect(Collectors.toList());
treeDownloads.getRoot().getChildren().removeAll(treeItemsToRemove);
}
Asides:
java naming conventions use lowercase letters for members: treeDownloads (not $TreeDownloads)
the "verifiable" in MCVE implies being runnable as-is: the poster should be the first to verify that ;) yours wasn't due to incorrect implementation of the listener
the "minimal" in MCVE means leaving out everything that's not needed: f.i. calling the threading code - which in your first snippet was particularly distracting because violating fx' threading rule is a rather common error

Not able to sort CellTable Column

Trying to make my CellTable Colum sortable but I'm not getting it to work. I'm having an MVP application which gets data from a rest service. To show the data within the table works fine but to sort is doesn't work.
public class LicenseUsageUserViewImpl<T> extends Composite implements LicenseUsageUserView<T> {
#UiTemplate("LicenseUsageUserView.ui.xml")
interface LicenseDataViewUiBinder extends UiBinder<ScrollPanel,LicenseUsageUserViewImpl> {}
private static LicenseDataViewUiBinder uiBinder = GWT.create(LicenseDataViewUiBinder.class);
#UiField
CellTable<GWTLicenseUser> licenseUserCellTable;
List<GWTLicenseUser> licenseUsers;
ListDataProvider<GWTLicenseUser> dataProvider;
public List<GWTLicenseUser> getLicenseUsers() {
return licenseUsers;
}
public void setLicenseUsers(List<GWTLicenseUser> licenseUsers) {
this.licenseUsers = licenseUsers;
}
#UiField Label header;
ListHandler<GWTLicenseUser> sortHandler;
public LicenseUsageUserViewImpl() {
initWidget(uiBinder.createAndBindUi(this));
initCellTable();
}
#Override
public void setLicenseUsersTable(List<GWTLicenseUser> tmpLicenseUsers) {
if (tmpLicenseUsers.isEmpty()) {
licenseUserCellTable.setVisible(false);
} else {
setLicenseUsers(tmpLicenseUsers);
licenseUserCellTable.setWidth("100%");
licenseUserCellTable.setVisible(true);
licenseUserCellTable.setPageSize(getLicenseUsers().size());
licenseUserCellTable.setRowCount(getLicenseUsers().size(), false);
licenseUserCellTable.setRowData(0, getLicenseUsers());
licenseUserCellTable.setVisibleRange(new Range(0, licenseUserCellTable.getRowCount()));
sortHandler.setList(getLicenseUsers());
dataProvider.getList().clear();
dataProvider.getList().addAll(getLicenseUsers());
}
}
#Override
public void initCellTable() {
sortHandler = new ListHandler<GWTLicenseUser>(getLicenseUsers());
licenseUserCellTable.addColumnSortHandler(sortHandler);
licenseUserCellTable.setWidth("100%");
licenseUserCellTable.setVisible(true);
licenseUserCellTable.setVisibleRange(new Range(0, licenseUserCellTable.getRowCount()));
// Create a data provider.
dataProvider = new ListDataProvider<GWTLicenseUser>();
// Connect the table to the data provider.
dataProvider.addDataDisplay(licenseUserCellTable);
licenseUserCellTable.setWidth("100%");
licenseUserCellTable.setAutoHeaderRefreshDisabled(true);
licenseUserCellTable.setAutoFooterRefreshDisabled(true);
// userID
TextColumn<GWTLicenseUser> userIdColumn = new TextColumn<GWTLicenseUser>() {
#Override
public String getValue(GWTLicenseUser object) {
if (object != null ){
return object.getUserId();
} else {
return "NULL";
}
}
};
userIdColumn.setSortable(true);
sortHandler.setComparator(userIdColumn, new Comparator<GWTLicenseUser>() {
#Override
public int compare(GWTLicenseUser o1, GWTLicenseUser o2) {
return o1.getUserId().compareTo(o2.getUserId());
}
});
licenseUserCellTable.addColumn(userIdColumn, "User ID");
// more column entries
licenseUserCellTable.getColumnSortList().push(userIdColumn);
licenseUserCellTable.getColumnSortList().push(countColumn);
licenseUserCellTable.addColumnSortHandler(sortHandler);
}
}
setLicenseUsersTable is called from my activity with the response list of my users. When I start my application and make a rest call my data is provide and put into my list also shown within the CellTable but its not sortable, but I have this sort icon before my colum name. I figured I post the whole code because I think its know easier to see what I'm trying to do.
Thanks for any help.
Remove this line:
sortHandler.setList(getLicenseUsers());
You already passed a List into the SortHandler constructor in
sortHandler = new ListHandler<GWTLicenseUser>(getLicenseUsers());
Also, instead of
setLicenseUsers(tmpLicenseUsers);
you may need to use
licenseUsers.addAll(tmpLicenseUsers);
I hope one of them fixes the problem.

GWT Editors - how to add N sub-editors of the same type based on a Collection

I have an object, Supply, that can either be an ElecSupply or GasSupply (see related question).
Regardless of which subclass is being edited, they all have a list of BillingPeriods.
I now need to instantiate N number of BillingPeriodEditors based on the contents of that list, and am pretty baffled as to how I should do it.
I am using GWTP. Here is the code of the SupplyEditor I have just got working:
public class SupplyEditor extends Composite implements ValueAwareEditor<Supply>
{
private static SupplyEditorUiBinder uiBinder = GWT.create(SupplyEditorUiBinder.class);
interface SupplyEditorUiBinder extends UiBinder<Widget, SupplyEditor>
{
}
#Ignore
final ElecSupplyEditor elecSupplyEditor = new ElecSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor> elecSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor>(
elecSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof ElecSupply);
if(!(value instanceof ElecSupply))
{
showGasFields();
}
else
{
showElecFields();
}
}
};
#Ignore
final GasSupplyEditor gasSupplyEditor = new GasSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor> gasSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor>(
gasSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof GasSupply);
if(!(value instanceof GasSupply))
{
showElecFields();
}
else
{
showGasFields();
}
}
};
#UiField
Panel elecPanel, gasPanel, unitSection;
public SupplyEditor()
{
initWidget(uiBinder.createAndBindUi(this));
gasPanel.add(gasSupplyEditor);
elecPanel.add(elecSupplyEditor);
}
// functions to show and hide depending on which type...
#Override
public void setValue(Supply value)
{
if(value instanceof ElecSupply)
{
showElecFields();
}
else if(value instanceof GasSupply)
{
showGasFields();
}
else
{
showNeither();
}
}
}
Now, as the list of BillingPeriods is a part of any Supply, I presume the logic for this should be in the SupplyEditor.
I got some really good help on the thread How to access PresenterWidget fields when added dynamically, but that was before I had implemented the Editor Framework at all, so I think the logic is in the wrong places.
Any help greatly appreciated. I can post more code (Presenter and View) but I didn't want to make it too hard to read and all they do is get the Supply from the datastore and call edit() on the View.
I have had a look at some examples of ListEditor but I don't really get it!
You need a ListEditor
It depends of how you want to present them in your actual view, but the same idea apply:
public class BillingPeriodListEditor implements isEditor<ListEditor<BillingPeriod,BillingPeriodEditor>>, HasRequestContext{
private class BillingPeriodEditorSource extends EditorSource<BillingPeriodEditor>{
#Override
public EmailsItemEditor create(final int index) {
// called each time u add or retrive new object on the list
// of the #ManyToOne or #ManyToMany
}
#Override
public void dispose(EmailsItemEditor subEditor) {
// called each time you remove the object from the list
}
#Override
public void setIndex(EmailsItemEditor editor, int index) {
// i would suggest track the index of the subeditor.
}
}
private ListEditor<BillingPeriod, BillingPeriodEditor> listEditor = ListEditor.of(new BillingPeriodEditorSource ());
// on add new one ...
// apply or request factory
// you must implement the HasRequestContext to
// call the create.(Proxy.class)
public void createNewBillingPeriod(){
// create a new one then add to the list
listEditor.getList().add(...)
}
}
public class BillingPeriodEditor implements Editor<BillingPeriod>{
// edit you BillingPeriod object
}
Then in you actual editor edit as is in the path Example getBillingPeriods();
BillingPeriodListEditor billingPeriods = new BillingPeriodListEditor ();
// latter on the clickhandler
billingPeriods.createNewBillingPeriod()
You are done now.

JComboxBox setSelectedItem

I am facing problem to set a perticulat value of a custom JComboBox. If I call setSelectedItem() from the initialize() method of the following class it is not selecting the particular value.
The extended JComboBox class is:
public class ThemeComboBox extends JComboBox {
private static final long serialVersionUID = 50L;
public ThemeComboBox(DefaultComboBoxModel model) {
super(model);
initialize();
LibraryLogger.initMessage(getClass().getSimpleName());
}
public void initialize() {
ThemeComboBoxModel model = (ThemeComboBoxModel) getModel();
for(ThemeModel themeModel : model.getThemeModels()) {
if(themeModel.getThemeClass().equals(ConfigurationManager.getInstance().getUiManager().getUiProperties().getTheme())) {
setSelectedItem(themeModel);
System.out.println("=========");
break;
}
}
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ThemeComboBox themeComboBox = (ThemeComboBox) actionEvent.getSource();
System.out.println(themeComboBox.getSelectedItem());
}
});
}
}
While if I override the getSelectedItem() of custom DefaultComboBoxModel then it is selecting that value but on choosing other value the selection remain same or it remain unchange.
The model class is:
public class ThemeComboBoxModel extends DefaultComboBoxModel {
private static final long serialVersionUID = 51L;
private Vector<ThemeModel> themeModels;
public ThemeComboBoxModel(Vector<ThemeModel> models) {
super(models);
}
public Vector<ThemeModel> getThemeModels() {
return themeModels;
}
public void setThemeModels(Vector<ThemeModel> themeModels) {
this.themeModels = themeModels;
}
/*#Override
public Object getSelectedItem() {
for(ThemeModel themeModel : themeModels) {
if(themeModel.getThemeClass().equals(ConfigurationManager.getInstance().getUiManager().getUiProperties().getTheme())) {
return themeModel;
}
}
return null;
}*/
}
I am unable to understand what I am doing wrong. Any information will be very helpful to me.
Thanks in advance.
1) I hope that main method is initialized from invokeLater
2) Swing is single threaded, where output to the GUI is done quite in one moment
3) there isn't any guarantee that all events have got any order, basically isn't possible ordering events for Swing GUI, same/especially on GUI startup
4) show GUI (setVisible(true);), then last codeline will be JComboBox#setSelectedItem(int or Object), wrapped inside invokeLater
5) add Listeners only if needed, remove useless Listeners

Categories