我不能在秋千上画一个圆圈

时间:2015-01-19 16:45:05

标签: java swing drawing geometry

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

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

而不是:

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