创建具有多个图像的JPanel

时间:2012-04-04 17:08:50

标签: java image swing jpanel drawrect

我有一个JPanel,我想要为这个JPanel绘制一些非常简单的图像(项目)。我想使用DrawRect或DrawOval等方法。这个面板将有一个滚动条。它应该看起来像this

我需要删除并添加特定索引上的项目(图像)。你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

你看看

答案 1 :(得分:1)

从使用GridLayout或垂直BoxLayout的主JPanel开始。把它放在JScrollPane中。在主要的JPanel中,你需要有JPanel的实例,它扩展了常规的paintComponent()方法,用drawRect(),drawOval()等进行绘图。这应该让你开始:

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);
        }
    }
}

要访问containerPanel的子项,请使用containerPanel.getComponent(int)然后强制转换为MyPanel。