Creating a JPanel with multiple images

Go To StackoverFlow.com

1

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?

2012-04-04 17:08
by user1313386


1

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.

2012-04-04 17:28
by Dan O
Thank you very much. It works really great - user1313386 2012-04-04 18:01


1

you have look at

2012-04-04 17:14
by mKorbel
Thank you for your answer. I have never used Icons with methods like DrawOval before. I only have loaded an image from a file. I don't want to load an image from a file. Can you post any simple example how to draw something and saves it to an icon - user1313386 2012-04-04 17:29
Ads