我无法在 swing 中画圆

I can't draw a circle in swing

我想画一个红色边框的圆圈。 但是我的代码没有任何内容:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class DrawCircle extends JPanel{

    public DrawCircle() {
        setBackground(Color.green);
        setOpaque(true);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(new Color(0, 255,0));
        g.drawOval(100, 100, 50, 50);
        super.paint(g);
    }

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

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(400, 400));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new DrawCircle(), BorderLayout.CENTER);

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

你对super.paint(g)的调用清除了你画的圆圈,改变顺序:

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.setColor(new Color(0, 255,0));
    g.drawOval(100, 100, 50, 50);    
}

而不是这个:

 public void paint(Graphics g) {
        g.setColor(new Color(0, 255,0));
        g.drawOval(100, 100, 50, 50);
        super.paint(g);
    }

这样做:

 public void paintComponent(Graphics g) { // you should be overriding paint component, not paint
        super.paintComponent(g); // your super.paint call was painting the background, clearing out the drawing you were doing
        g.setColor(new Color(0, 255,0));
        g.drawOval(100, 100, 50, 50);
    }