【问题标题】:Adding a Oval to a JPanel (paintComponent)将椭圆添加到 JPanel (paintComponent)
【发布时间】:2023-03-11 18:51:01
【问题描述】:

在嵌套 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

任何意见表示赞赏!

【问题讨论】:

    标签: java swing jpanel paintcomponent


    【解决方案1】:

    这样做的方法是拥有一个 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());
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        • 2023-01-20
        相关资源
        最近更新 更多