Reputation: 165
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.)
Upvotes: 1
Views: 1547
Reputation: 285430
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.
Upvotes: 4
Reputation: 81724
You have to add a JPanel
to the JScrollPane
, then add the additional panels to that JPanel
. The JScrollPanel
can only manage one child.
Upvotes: 3