Calling method from another class which relates to Arraylist - java

I am building an application with a Room class which is abstract and a Standard class which inherits from Room. I have then created a Hostel class. Within the Hostel class is ArrayList<Room> rooms to which rooms can be added. I have created a method in the Hostel class which shows all available rooms but when I try and instantiate this in another class (MainGUI) nothing is shown. As far as I can see this is because I am creating a new hostel each time I click the button but would like to know how to pass the data across instead of creating a new hostel each time. Below are the relevant snippets of code.
Hostel Class
public Hostel()
{
rooms = new ArrayList<Room>();
}
public void showAvail()
{
for (Room room : rooms)
{
if (room.available == true)
{
theString = room.getRoomData() + "\n";
//System.out.println("Available Rooms" + "\n" + theString);
JOptionPane.showMessageDialog(null,theString);
}
}
}
public void addRoom(Room theRoom)
{
rooms.add(theRoom);
}
MainGUI Class
roomsFreeB.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Hostel host = new Hostel();
host.showAvail();
}
});
Any help would be appreciated

Unless you omitted code between the Hostel host = new Hostel(); and host.showAvail();, you never add any rooms to the hostel so there are no available rooms (or any at all) to show. You need to either add rooms to host after you create it and before you showAvail, or create a Hostel instance variable, fill it somewhere, and then call showAvail on that.

Would be good to see how you initialize your rooms inside Hostel. And if you like to initialize Hostel once only, do it outside of Listener. In this case it must not be a field inside MainGUI.

public void actionPerformed(ActionEvent e)
{
Hostel host = new Hostel();
host.showAvail();
}
In the previous code, the object is created and then destroyed once the method is done. The variable host is a local variable and consequently lives only during the execution of the method.
Depending on what you want to do, you should declare your host variable inside the main method or declare an array of hostel inside the main method again.

Since you are creating new Hostel each time. I guess there will be to Rooms in the ArrayList.
You need to create the Hostel Object outside the actionPerformed. And in your case it should be created only one time. And on this created Hostel object you will be adding the Room object.
If the question is where to do it.. Its left to you. Its upon your design.
For eg it can be.
You can create a class called ABC inside which you can create the hostel object. Write a static method called getHostel(). Then call ABC.getHostel()

Yes you are right that everytime action is performed a new Hostel is created and so is the list of rooms associated with hostel.
On click of button you would know which hostel you want to show (May be reading your application database or something), in case this is the first time your hostel will have empty room, else once you have read the hostel information you would also know about rooms which belong to the hostel, which can then be passed to your hostel object either through constructor or setter method.
Code snippet:
createHostel(String hostelName) {
//read from database
//No hostel with hostelname found create a new hostel else if hostel is found send the same (by this time hostel object would have room information also
}
Your action
public void actionPerformed(ActionEvent actionEvent) {
//MyFactory.getHostel(String hostelName)
//Once you have hostel object call showAvail on it, if its new you will get nothing else you will get all the rooms available
}
Hope this gives you some insight.

Your problem is exactly what you thought, you are making a new ArrayList each time you click the button so you will never see the data. You should begin by creating a hostel object in your MainGUI class,
private Hostel hostel;
this will allow previously entered information to be referenced

Related

Updating JList by pressing button

first of all I will introduce what I am trying to do. This is an assignment in university we are making Hotel booking system with JAVA. To go straight to the point, all I need to know is how to update JList when I press button.
listModel = new DefaultListModel<Hotel>();
bookingList = new JList(listModel);
class MouseAdapterMod extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if(e.getSource() == searchButton){
for(lists.getRoomsList() p : lists.getRoomsList())
{
listModel.addElement(p);
}
bookingList.setModel(listModel);
}
In this GUI class I have instance variable (lists) of Hotel class, in Hotel class there are methods
public ArrayList<Rooms> getRoomsList()
{
return roomsList.getListRooms();
}
public ArrayList<Suite> getSuitesList()
{
return roomsList.getListSuites();
}
this returns whole ArrayList of Room class objects and also ArrayList of Suite class.
QUESTION would be is how to show whole ArrayList of Rooms when I press button, in other words how to update JList which consists of objects, by pressing button?
I hope I explained alright.
Your for-each loop is wrong. Try this and see:
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(searchButton)){
ArrayList<Rooms> rooms = lists.getRoomsList();
for(Rooms r : rooms) {
listModel.addElement(r);
}
bookingList.setModel(listModel);
}
}
This still looks sorta messy to me though. A more appropriate approach would be to set an event handler on the searchButton, to populate the JList when searchButton is clicked.
Also, are Rooms and Suites sub classes of Hotel? If not, you'll have to create listModel like this (for rooms):
listModel = new DefaultListModel<Rooms>();

Create a class based on a variable

I have a base class Accounts, that handles all of the information and methods of basic account functions. Then I have subclasses of Checkings and Savings to handle specific functions for the different classes. I have an action listener that will add the account,
addBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// add the account
//this is where I am stuck!
Account account = new Savings(amount);
}
});
and based on a variable in a JComboBox I want to be able to differentiate what kind of class is created.
//get the types of accounts
ArrayList<String> accountTypes = Account.getAccountTypes();
JComboBox box = new JComboBox(accountTypes.toArray());
contentPanel.add(box);
What can I do to better handle this?
If you need this only in action listener just put there simple if/else or switch/case. If there is a chance that somewhere else you will need to create objects in similar way read about design patterns like Factory Method.

Passing string and variable from one class to another. JAVA

I coded Chat in java with gui. Now I made a simple Login with MySQL. If you login you open main chat class. But problem is I want to pass username string from login class to main class.
How to do it. And how to pass variable from one to another class too. thx guys
CODE:
Here is where you login and it opens new class
Login class. login2.java
if (res.next()) {
JOptionPane.showMessageDialog(this, "Login Sucessfull.");
new ClientGUI("localhost", 1500);
dispose();
}
else {
JOptionPane.showMessageDialog(this, "Invalid User Name/Passw");
}
Thank you for help.
Here is what I would do...create a public variable or a public object like:
public static String keepInfo; // on top of your code
Instantiate it in your code by giving it whatever value you want in the constructor. Then the class that wants to call should create an object of the class. In your case, it would something like:
ClientGUI client = new ClientGUI();
// to call your String you can do something like:
String getInfo = client.keepInfo; // if you don't have get or set methods

action on jbutton press

I can't figure out how to make the following code work. When you press a jbutton I want it to run the following code. My problem is that the ArrayList list is located in the main and I don't know how to pass it into this method provided to me by the GUI builder so that, that actionperformed method will know what list is and return an ArrayList back to the main to replace it with the new changes.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Student temp;
Picker pick = new Picker(list);
temp = pick.randomNoReplace(); //replace randomNoReplace() with radio button choice
list.remove(temp); //the next line must be temp.increaseScore() or temp.decreaseScore() or neither
list.add(temp);
}
}
What you are looking for is something like this:
class Foo {
private ArrayList<Student> list;
...
This will declare list as an ArrayList of Students as an instance variable so that each object of this class can access list from any instance method. Just be sure to instantiate list before using it, preferably inside your constructor doing something like this:
list = new ArrayList<Student>();

Possible thread issue?

I have 2 classes, one class is a datamodel class and the other is a gui class.
class datamodel .........
Takes user selected data and creates a arraylist
class gui .........
Has a tableviewer that is using the array from the datamodel class
My issue is I need to fresh the tableviewer when the user has added more data to the array.
I created a updateTableViewer method in the gui class.
public void updateTableViewer() {
if(getViewer() != null) {
viewer.refresh();
{
Then I made a reference to the gui class in the datamodel class.
AplotBaseDialog abd = new AplotBaseDialog(null, null);
Then I added the method call to the method adding more data to the array
public void add(TCComponentItemRevision tcRevision, TCComponentDataset selectedDataset) {
AplotDatasetData pp = new AplotDatasetData(tcRevision, selectedDataset);
if (!dataArrayList.contains(pp)) {
dataArrayList.add(pp);
}
abd.updateTableViewer();
}// end add()
This does not work. The getViewer() call always returns null, even if the gui class is created and open.
So I create a boolean value;
Boolean hasViewerBeenCreated = false;
I am setting the value to true after the tableviewer is created.
viewer = new AplotDataTableViewer(parent, SWT.BORDER|SWT.V_SCROLL|SWT.FULL_SELECTION);
viewer.setInput(AplotDataModel.getInstance().getArrayData());
hasViewerBeenCreated = true;
Then I created a method to return the boolean value.
I am calling the method from a button on the dailog.
I also replaced the updateTableViewer method call in the datamodel class
if (!dataArrayList.contains(pp)) {
dataArrayList.add(pp);
}
abd.getBooleanValue();
}
Here are the results.
I execute the add method in the datamodel class -
It returns false - That makes sense because the dailog has not been created at this time
I execute and create the gui class
I click the button and it returns true - This makes sense because the viewer has been created
Here is where I get confused.
With the gui still open, I can execute the add method again and it stills returns a false value. Then I can click the button and see it is true value.
I would think that when the gui is created and the boolean value is set to true. I would be able to get the current value of the boolean in other classes.
I am not sure if I am not referencing the gui class correctly or when the gui is created I am not accessing the current thread or tableviewer?
I don't know if this is a thread issue or I am just not getting the current value from the gui correctly.
This is a big issue with my application right now. I have to be able to refresh the tableviewer any time new data is added to the array. I can not have the user having to manually refresh the table every time that select new data

Categories