Navvy
Navvy

Reputation: 237

Java GUI adding a JList to class in another file

I'm trying to call a JList that I have in one class and add it to another with no avail, as it's telling me about the static and non static functions

I've got an ArrayList called finalList in one class, which is filled with values, and this has been checked by printing the list out.

Then I have another class in a different file called cupboard, where I want to put the items into a JList there.

    finalList.add(si);

is where the items are being added, where si are array items, and finalList is the new array then in my cupboard class file, currently I have

    public Cupboard() 
{
    cupboardContent = new JList(ShoppingList.finalList.toArray());
}

Where the cupboardContent is the new JList where I want the items to go.

Thanks if anyone has any idea. I'm sure it's something straightforward, and I'm just being quite stupid! It'd seem that when combining normal processes with GUI, as I'm fairy new to working with GUI I'm struggling to make the connections!

//edit

Right, the first bit of code is adding the items to the array absolutely fine, but I need to work out how to call it in the new class. Currently, this is what I have

    public class KitchenCupboard extends JPanel //implements ActionListener
    {
private JList cupboardContent;
private JButton usedItem;

ShoppingList items = new ShoppingList();

public KitchenCupboard() 
{
    System.out.println(ShoppingList.finalList);

    cupboardContent = new JList(items.finalList.toArray());
    cupboardContent.setVisibleRowCount(10);
    cupboardContent.setFixedCellHeight(30);
    cupboardContent.setFixedCellWidth(200);
    cupboardContent.setFont(new Font ("sansserif", Font.BOLD, 13));
    cupboardContent.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    add(new JScrollPane(cupboardContent));
}

}

The array in ShoppingList is

    static ArrayList<ShoppingItem> finalList = new ArrayList<ShoppingItem>();

It's using two classes/files: ShoppingList.java and KitchenCupboard.java

Upvotes: 1

Views: 1892

Answers (3)

BlackBox
BlackBox

Reputation: 2233

I'm not sure if you would be comfortable with this, but may I suggest you use the Observer pattern? Java has built in classes, Observer and Observable to help you with these.

I've made a small example program of how you could use it to tackle your problems, but it far from a working example.

Main.java

public class Main {

    public static void main(String... args){
        final Controller appController = new Controller();
        final ObjectListModel listModel = new ObjectListModel();
        appController.addObserver(listModel);

        //Event is fired, lists are updated.
        appController.addObject(new Object()); 
    }
}

Controller.java

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

public class Controller extends Observable {

    private final List<Object> objectList = new ArrayList<>();

    public void addObject(Object obj) {
        objectList.add(obj);
        this.setChanged();
        this.notifyObservers(obj);
    }
}

ObjectListModel.java

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.AbstractListModel;

public class ObjectListModel extends AbstractListModel implements Observer{

    private List<Object> objectList = new ArrayList<>();

    @Override
    public int getSize() {
        return objectList.size();
    }

    @Override
    public Object getElementAt(int index) {
        return objectList.get(index);
    }

    @Override
    public void update(Observable o, Object arg) {
        if(arg instanceof Object){
            objectList.add(arg);
        }
    }

}

Simplistically, how this all works is as follows:

You have 1 Controller class which is where all you different components talk to each other. The rest, in this example, listen on the Controller to tell them what to do.

As Controller extends Observable, it is able to tell all registered Observer classes that a state has changed and that they need to update.

In our example, we set the ListModel of your future JList to wait for changes to the main data source, which is controlled by the controller. When a user adds another data object is added, an event is fired which updates the main data source and tells the list model to also update.

Upvotes: 2

Sinkingpoint
Sinkingpoint

Reputation: 7634

Because finalList is a member of ShoppingList, you can do one of two things. Either:

Declare finalList as a static member of ShoppingList, thus allowing you to access it exactly as you have above:

cupboardContent = new JList(ShoppingList.finalList.toArray());

or pass a reference to a ShoppingList object into the constructor of Cupboard allowing you to access the finalList through that reference:

public Cupboard(ShoppingList list) 
{
    cupboardContent = new JList(list.finalList.toArray());
}

and then create a new Cupboard:

Cupboard c = new Cupboard(<some ShoppingList instance>);

Can I also suggest that you cast the generated Array to the type you need, as Java 7 introduces new Generics based swing components, thus an Array of whatever is in finalList is probably more useful.

Upvotes: 2

akki0996
akki0996

Reputation: 713

Check this one, in this program , I have list "cities list", in which I added my all elements, after that I have list "second list" on which I A moving my elements, This program also reverses the , means it moves elements, from second list to cities list. For better understanding please run this program...

import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

/*
 * Combo BOX pROBLEM
 */

public class ComboBoxProblem extends JFrame 
    {
        // made them static , so I can use them over & over
        static JLabel citiesLabel = new JLabel();

        static JList citiesList = new JList();
        static JScrollPane citiesScrollPane = new JScrollPane();

        static JLabel SecondLabel = new JLabel();
        static JList SecondList = new JList();
        static JScrollPane SecondScrollPane = new JScrollPane();


        // these are button to move the elements
        static JButton AssignButton = new JButton();
        static JButton RemoveButton = new JButton();

        static JList made_list = new JList();

public static void main(String args[]) 
    {
        new ComboBoxProblem().show();
    }


public ComboBoxProblem() 
    {
        // create frame
        setTitle("Flight Planner");
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridBagLayout());


        GridBagConstraints gridConstraints;
        citiesLabel.setText("Destination City");
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 0;
        gridConstraints.gridy = 1;
        gridConstraints.insets = new Insets(10, 0, 0, 0);

        getContentPane().add(citiesLabel, gridConstraints);
        citiesScrollPane.setPreferredSize(new Dimension(150, 100));
        citiesScrollPane.setViewportView(citiesList);
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 0;
        gridConstraints.gridy = 2;
        gridConstraints.insets = new Insets(10, 10, 10, 10);
        getContentPane().add(citiesScrollPane, gridConstraints);

        final DefaultListModel List1= new DefaultListModel();
        List1.addElement("San Diego");
        List1.addElement("Los Angeles");
        List1.addElement("Orange County");
        List1.addElement("Ontario");
        List1.addElement("Bakersfield");

        citiesList.setModel(List1);

        SecondLabel.setText("Moved");
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 1;
        gridConstraints.gridy = 1;
        gridConstraints.insets = new Insets(10, 0, 0, 0);

        getContentPane().add(SecondLabel, gridConstraints);
        SecondScrollPane.setPreferredSize(new Dimension(150, 100));
        SecondScrollPane.setViewportView(SecondList);
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 1;
        gridConstraints.gridy = 2;
        gridConstraints.insets = new Insets(10, 10, 10, 10);
        getContentPane().add(SecondScrollPane, gridConstraints);

        final DefaultListModel List2 = new DefaultListModel();

        SecondList.setModel(List2);

        AssignButton.setText("Move");
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 0;
        gridConstraints.gridy = 3;
        gridConstraints.insets = new Insets(0, 0, 10, 0);
        getContentPane().add(AssignButton, gridConstraints);
        AssignButton.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                    {
                        for(int i = 0; i < List1.getSize(); i++)
                            {
                                if(citiesList.isSelectedIndex(i))
                            {
                                List2.addElement(List1.getElementAt(i));
                                List1.removeElementAt(i);
                                i--;
                            }

                    }
            }
            });

        RemoveButton.setText("Reverse");
        gridConstraints = new GridBagConstraints();
        gridConstraints.gridx = 1;
        gridConstraints.gridy = 3;
        gridConstraints.insets = new Insets(0, 0, 10, 0);
        getContentPane().add(RemoveButton, gridConstraints);
        RemoveButton.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                    {

                        for(int i = 0; i < List2.getSize(); i++)
                            {
                                if(SecondList.isSelectedIndex(i))
                                {
                                    List1.addElement(List2.getElementAt(i));
                                    List2.removeElementAt(i);
                                    i--;
                                }
                            }

                    }
            });

        pack();

      }
 }

Upvotes: 0

Related Questions