Java 通过将jpanel组件作为参数传递来绘制一个圆

Java 通过将jpanel组件作为参数传递来绘制一个圆,java,swing,jpanel,Java,Swing,Jpanel,我真的很困惑如何通过将它作为一个参数传递来在jpanel上画一个圆圈 public class test extends JPanel{ public test(JPanel jpanelcomponent) { } @Override protected void paintComponent(Graphics g) { // TODO Auto-generated method stub

我真的很困惑如何通过将它作为一个参数传递来在jpanel上画一个圆圈

public class test extends JPanel{

        public test(JPanel jpanelcomponent) {

        }
        @Override
        protected void paintComponent(Graphics g) {
            // TODO Auto-generated method stub
            super.paintComponent(g);
            int width = getWidth()/2;
            int height = getHeight()/2;
            g.fillOval(5, 5, width, height);
        }


    }

我认为一个更好的设计会让您将从重写
JPanel的
paintComponent(…)
获得的
Graphic
s对象传递给将绘制到图形对象的类

下面是我举的一个例子:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final DrawingClass dc = new DrawingClass();
        JPanel testPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);
                Graphics2D g2d = (Graphics2D) grphcs;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                dc.draw(g2d, getWidth(), getHeight());

            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 300);
            }
        };

        frame.add(testPanel);

        frame.pack();
        frame.setVisible(true);
    }
}

class DrawingClass {

    public void draw(Graphics2D g2d, int w, int h) {
        g2d.setColor(Color.BLACK);
        g2d.fillOval(5, 5, w / 2, h / 2);
    }
}


@David的答案更好,但你可以尝试使用他们显示的那样。

因此,为了澄清你希望能够传递一个JPanel实例,并且类应该能够在面板上绘制图形?是的,这正是我想要的。“我真的很困惑如何通过传递它作为参数在JPanel上绘制一个圆…”一种方法是使用一个
Circle
类,该类有自己的
draw(Graphics)
draw(Graphics2D)
方法。在主面板中保留它们的列表。在
paintComponent(Graphics)
上,绘制形状实例。