1

I am designing a Pizza Delivery simulator for a class project. My team and I have most of it done, but we are struggling with the GUI.

I need to be able to add items to the order. Each time I click the add item button, it creates a new AddItemPanel (a panel I created that extends JPanel), and adds it to the JScrollPane.

The problem I am running into is it will only add ONE AddItemPanel to the scrollPane. I am not sure if they are being hidden underneath the first one, or if I am just doing something stupid.

Here is the relevant code:

JPanel itemPanel = new JPanel(new GridLayout(0, 1));

JViewPort viewPort = new JViewport();
viewPort.setLayout(new GridLayout(0, 1)); // not sure if I need this line
JScrollPane scrollPane = new JScrollPane(viewPort);
itemPanel.add(scrollPane);

// other stuff

JButton addItemButton = new JButton("Add Item");
addItemButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        viewPort.add(new AddItemPanel());
        validate();
    }
});

So my questions are: Is this even possible with a JScrollPane? If so, how do I do it? If not, how would I accomplish something similar?

(PS. I have linked screen shots in case they are helpful in explaining.)

screen shot 1 screen shot 2

Matthew Denaburg
  • 163
  • 1
  • 15

2 Answers2

4

The best and most straightforward solution that I can think of is to use a JList or JTable that is held by the JScrollPane. These guys are a lot more flexible than I think you realize and can display fairly complex data if you use the right cell renderer. If you can't do this, then have the JScrollPane's viewport hold a JPanel that uses GridLayout. But don't mess with the viewport's layout.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3

You have to add a JPanel to the JScrollPane, then add the additional panels to that JPanel. The JScrollPanel can only manage one child.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186