I have a JPanel and I want do draw to this JPanel some very simple images (items). I want to use methods like DrawRect or DrawOval.. This panel will have a scrollbar. It should look like this.
I need to remove and add item (images) on a specific index. Can you help me please?
Start with a main JPanel which uses either a GridLayout or a vertical BoxLayout. Put this inside a JScrollPane. Inside the main JPanel, you'll want to have instances of JPanel which extend the regular paintComponent() method to do drawing with drawRect(), drawOval(), etc. This should get you started:
public JScrollPane buildScrollingContainerPanel()
{
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(containerPanel);
containerPanel.add(new MyPanel(true, false));
containerPanel.add(new MyPanel(false, true));
return (scrollPane);
}
private class MyPanel extends JPanel
{
private boolean drawRect;
private boolean drawOval;
public MyPanel(boolean drawRect, boolean drawOval)
{
super();
this.drawRect = drawRect;
this.drawOval = drawOval;
}
public void setDrawRect(boolean b)
{
drawRect = b;
repaint();
}
public void setDrawOval(boolean b)
{
drawOval = b;
repaint();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (drawOval)
{
g.setColor(Color.RED);
g.drawOval(16, 16, 16, 16);
}
if (drawRect)
{
g.setColor(Color.GREEN);
g.drawRect(32, 32, 16, 16);
}
}
}
to access children of the containerPanel, use containerPanel.getComponent(int)
then cast to MyPanel.
you have look at
proper LayoutManager ( probably GridLayout
)