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);
}
I'm just looking some another efficient way to pass an object parameter to method.
So I have some method like this:
private void dashboardMenu() {
Dashboard dashboard = new Dashboard();
body.removeAll();
body.add(dashboard);
dashboard.setSize(body.getWidth(), body.getHeight());
dashboard.setVisible(true);
}
private void dataMenu() {
Data data = new Data();
body.removeAll();
body.add(data);
data.setSize(body.getWidth(), body.getHeight());
data.setVisible(true);
}
And I want an efficient method to call between this two method with object parameter (dashboard = new Dashboard(), and data = new Data()).
What I think it should be like this for example:
private void dasboardMenu() {
navigateMenu(Type object);
}
private void dataMenu() {
navigateMenu(Type object);
}
private void navigateMenu(Type object) {
object menu = new object();
body.removeAll();
body.add(menu);
menu.setSize(body.getWidth(), body.getHeight());
menu.setVisible(true);
}
Is it possible to do that?
Please give me an example. I don't even know what keyword should I do.
How about this (assuming your Dashboard and Data are Swing Components)?
private void dashboardMenu() {
navigateMenu(new Dashboard());
}
private void dataMenu() {
navigateMenu(new Data());
}
private void navigateMenu(JComponent c) {
body.removeAll();
body.add(c);
c.setSize(body.getWidth(), body.getHeight());
c.setVisible(true);
}
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.
I am writing a Java (Swing) application and I'm trying to store stuff in an ArrayList.
My plan is to first instantiate a class, set some variables in that class and then add that class to an ArrayList.
So I have this class:
public class CollectionClass {
private ArrayList<OwnerClass> owners;
public CollectionClass() {
owners = new ArrayList<OwnerClass>();
}
public void AddOwner(OwnerClass oc) {
owners.add(oc);
}
}
And this class:
public class OwnerClass {
public int id = 0;
public String name = "";
public String employeeNr="";
}
Now in my dialog I have this:
CollectionClass myCC;
public InvoerNewOwner(CollectionClass cc) {
myCC = cc;
btSave.setActionListener(new ActionListener() {
OwnerClass oc = new OwnerClass();
oc.name = txtOwner.getText(); <<<
oc.employeeNr = txtEmployeeNr.getText(); <<<
myCC.addOwner(oc); <<<
});
I get an error on the 3 lines marked with <<<. The error is "error: <identifier> expected"
What am I doing wrong here?
Is this not a good way to create a collection of objects?
btSave.setActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
OwnerClass oc = new OwnerClass();
oc.name = txtOwner.getText();
oc.employeeNr = txtEmployeeNr.getText();
myCC.addOwner(oc);
}
});
You must wrap all of the things you want to do inside an actionPerformed event.
I'm trying to fill a jComboBox with objects. I have it working in one class, but in this class it's giving a NullPointerException but the code is almost the same. What am I missing here?
The code I'm using to fill the comboboxes:
I have translated every variable to English and removed some unnescessary stuff. I hope it's more clear for you guys now:
package unive.billing.boundary.clientmanager.frames;
import unive.billing.control.ClientsManager;
import unive.billing.control.InsuranceManager;
/**
*
* #author Forza
*/
public class ClientFrame extends javax.swing.JFrame {
/**
* Creates new form AddClientGUI
*/
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
public void updateComboBoxCompany()
{
for (Object object : insurancemanager.getCompanyNames())
{
companyComboBox.addItem(object);
}
}
public void updateComboBoxInsurance()
{
for (Object object : insurancemanager.getPolicyNames())
{
insuranceComboBox.addItem(object);
}
}
Here are the methods used:
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
This is how my lists are initialized:
public class InsuranceManager {
private String insurancePath;
private String insurancecompanyenPath;
private static List<InsurancesCompany> insurancecompanyList;
private static List<Insurance> insuranceList;
private Insurance currentInsurance;
public InsuranceManager() {
insurancecompanyenPath = "Files/company.txt";
insurancePath = "Files/insurance.txt";
insuranceList = new List<>();
}
public void createNewList()
{
insurancecompanyList = new List<>();
System.out.println("Creates list");
}
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
Edit: Here's the MainGUI which calls createNewList (maakLijstAan)
private ClientsManager clientsmanager;
private BillingManager billingmanager;
private InsuranceManager insurancemanager;
public MainGUI() {
clientsmanager = new ClientsManager();
clientsmanager.CreateNewList();
insurancemanager = new InsuranceManager();
insurancemanager.CreateNewList();
insurancemanager.loadInsuranceCompanyList();
initComponents();
jMenuItem1.setText("Save clients");
jMenuItem2.setText("Load clients");
jMenuItem3.setText("Exit");
}
You never initialize verzekeringBeheer, therefore you get a NullPointerException when you try to invoke methods on that variable.
You should have somewhere in your constructor, something like this:
verzekeringbeheer = new VerzekeringBeheer();
Also, try to avoid making your code coupled with other parts of your code. For example:
public VerzekeringBeheer() {
...
//verzekeringmaatschappijLijst is never initialized!!!
}
public void maakLijstAan()
{
verzekeringmaatschappijLijst = new Lijst<>();
System.out.println("Maak lijst aan");
}
public Object[] getMaatschappijNamen()
{
ArrayList<String> mnamen = new ArrayList<String>();
// Here you use verzekeringmaatschappijLijst without checking that is not null!!!
for (VerzekeringsMaatschappij maatschappij : verzekeringmaatschappijLijst)
{
mnamen.add(maatschappij.getMaatschappijNaam());
}
return mnamen.toArray();
}
If nobody calls maakLijstAan, you will get a NullPointerException in getMaatschappijNamen. Try to avoid code that is so dependent of external code, in order to run without problems.
all data for JComboBox are stored in ComboBoxModel
set ComboBoxModel for proper Objects type (String, Integer, Icon or simple Object), Java7 implements Generics, there are significant differiences in compare with Java6
all updates (to the JComboBox or its Model) must be done on Event Dispatch Thread
I only see you useing variables but for me they are nit initialized. So they are null and you get a NPE.
So how are verzekeringmaatschappijLijst and verzekeringLijst initialized?