0

在嵌套 JPanel 的布局中,我希望添加一个绘制的椭圆。

为此,我使用以下内容:

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.setColor(Color.GRAY);
    g.fillOval(20, 20, 20, 20);
}

现在在我的一个面板中,我希望添加这个椭圆形,但我似乎无法添加它。

JPanel myPanel = new JPanel();
myPanel.setLayout(new GridLayout(0, 2));
//myPanel.add(...); here i wish to add the drawn oval

任何输入表示赞赏!

4

2 回答 2

4

做到这一点的方法是有一个子类JComponent来完成你想要的绘图,然后将它添加到你的布局中。

class OvalComponent extends JComponent {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GRAY);
        g.fillOval(20, 20, 20, 20);
    }
}

在您的 GUI 构建代码中,您可以拥有以下内容:

JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new OvalComponent());
于 2011-01-12T18:18:52.223 回答
2

您将 mypanel.add(...) 用于其他 GUI 元素。您要绘制的椭圆将是一个 java2d 对象,您必须将其绘制到面板上。为此,您必须使用上面发布的代码覆盖面板的 paint() 方法。

于 2011-01-12T18:20:13.070 回答