Java Swing collection not right? - java

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.

Related

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

Why add method invoked from ActionListener class doesn't add an element to collection? Java

Ok, here's my GUI class (shorted)
public class GUI {
private DataContainer dataContainer;
public GUI(DataContainer dataContainer){
this.dataContainer = dataContainer;
initGUI();
}
class RegisterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e){
String message;
String firstName = registerPanelFirstNameTextField.getText();
String lastName = registerPanelLastNameTextField.getText();
String login = registerPanelLoginTextField.getName();
String password = registerPanelPasswordTextField.getText();
String adress = registerPanelAdressTextField.getText();
Client client = new Client(firstName, lastName, login, password, adress);
boolean registerCheck = dataContainer.registerClient(client);
if (registerCheck) {
message = "SUCCES!";
} else {
message = "FAILURE!";
}
JOptionPane.showMessageDialog(new JFrame(), message);
}
}
And here's my DataContainer class (also shorted):
public class DataContainer implements Subject {
public boolean workingStatus = true;
private List<Client> clientList = new ArrayList<>();
private List<Auction> auctionList = new ArrayList<>();
private List<Observer> observersList = new ArrayList<>();
public boolean registerClient(Client client) {
String testLogin = client.getLogin();
boolean isClientOnList = isClientOnList(testLogin);
if (isClientOnList) {
return false;
} else {
addClientToList(client);
return true;
}
}
private void addClientToList(Client client) {
clientList.add(client);
System.out.println(clientList);
}
And here's my question - why method invoked from register listener gives empty collection. SysOut prints [null]. I have used JUnit and reflection to directly test addClientToList(), and it works, but it simply doesn't when clicking the button. And yes, in my class I created new DataContainer object, and passed it to GUI constructor.
Oh RIGHT! Found this little guy. Problem was here:
String login = registerPanelLoginTextField.getName();
and it should be:
String login = registerPanelLoginTextField.getText();

How to switch object with event listeners in java?

I need your help. I'm making a controlling program that use Wiimote, and I need to make 2 different type of control. Each controller code is defined in the class controlType1 and controlType2 (which the #2 isn't included here, but mostly it is the same with #1).
The idea is, when I press certain button on the WiiMote, the controller switched from type1 to type2. I've instantiate 2 objects, and it should removes the listener of one of the object when the button is pressed and change it to the other object.
Currently, I've gone this far and get stuck here. Any idea how should I do this?
public class WiiDroneControl implements ControlSwitchListener {
private Wiimote wiimote;
private WiimoteListener control1 = (WiimoteListener) new controlType1(this);
private WiimoteListener control2 = (WiimoteListener) new controlType2(this);
public WiiDroneControl() {
Wiimote wiimotes[] = WiiUseApiManager.getWiimotes(1, true);
if(wiimotes!= null && wiimotes.length > 0)
{
wiimote = wiimotes[0];
wiimote.addWiiMoteEventListeners(control1);
wiimote.addWiiMoteEventListeners(control2);
wiimote.activateMotionSensing();
wiimote.activateContinuous();
wiimote.getStatus();
}
}
#Override
public void onSwitchEvent() {
// TODO Auto-generated method stub
}
}
the other class
public class controlType1 implements WiimoteListener{
ControlSwitchListener listener = null;
public controlType1(ControlSwitchListener l) {
listener = l;
}
#Override
public void onButtonsEvent(WiimoteButtonsEvent e) {
// TODO Auto-generated method stub
listener.onSwitchEvent();
if (e.isButtonOnePressed())
{
//switch controller object when this button is pressed
}
}
}
If I correct understood your question...
public class WiiDroneControl implements ControlSwitchListener {
private Wiimote wiimote;
private WiimoteListener control1 = new controlType1(this);
private WiimoteListener control2 = new controlType2(this);
private WiimoteListener current = control1;
public WiiDroneControl() {
Wiimote wiimotes[] = WiiUseApiManager.getWiimotes(1, true);
if(wiimotes!= null && wiimotes.length > 0)
{
wiimote = wiimotes[0];
wiimote.addWiiMoteEventListeners(current);
wiimote.activateMotionSensing();
wiimote.activateContinuous();
wiimote.getStatus();
}
}
#Override
public void onSwitchEvent() {
current = current.equals(control1) ? control2 : control1;
}
}

jList not displaying data from custom model?

I'm trying to populate a JList through subclassing the AbstractListModel.I have looked through numerous places to try and find what I was doing wrong, but never managed to resolve the problem.So this class handles my GUI...
//View
public class central extends javax.swing.JFrame {
public central() {
initComponents();
list.addMouseListener(new abstracts.mouseActions(list));
}
public void setListModel(ListModel l ){
list.setModel(l);
}
// The rest are auto generated code for the interface, not relevant
Then is my middle class...
public class MainCtrl {
//View reference
private views.central mainFrame = new views.central();
//Model reference
private abstracts.ListData model = new abstracts.ListData();
/*All this was testing purposes and it worked
private DefaultListModel model = new DefaultListModel();
*/
private void showView(){
mainFrame.setListModel(model);
mainFrame.setVisible(true);
models.contact p2 = new models.contact("Alex", "Christopher","alex#hotmail.com","22","Def");
models.contact p1 = new models.contact("Joes", "Smith","joey#hotmail.com","33","Def");
model.addContact(p2);
model.addContact(p1);
/* def version
model.addElement(p2);
*/
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MainCtrl().showView();
}
catch (Exception e) {
e.printStackTrace();
}
}
Then I have got the AbstractListModel implementation
public class ListData extends AbstractListModel {
//Store people info
private Vector<contact> people;
public ListData() {
people = new Vector<contact>();
}
public void addContact(contact newPerson){
people.add(newPerson);
int per = people.indexOf(newPerson);
fireIntervalAdded(this,0,getSize());
}
#Override
public contact getElementAt(int index){
return people.get(index);
}
#Override
public int getSize(){
return people.size();
}
#Override
protected void fireIntervalAdded(Object src, int index, int index2){
System.out.println(index2);
}
.....
I tested DefautListModel and it displayed the values, but when I incorporate a custom model it doesn't display ? Is there a extra step I'm missing ? Also mainCtrl is the main class...
Thanks could really use some help
Instead of
fireIntervalAdded(this,0,getSize());
in your addContact() put
fireContentsChanged(this,0,getSize());
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list = new JList(listModel);
please refer this link it will help you
http://docs.oracle.com/javase/tutorial/uiswing/components/list.html

Java: Filling a JComboBox with objects

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?

Categories