如何在不覆盖 paint(...) 或 paintComponent(...) 的情况下在 JFrame 中绘制圆

How can i draw circle in JFrame without overriding paint(...) or paintComponent(...)

我想使用我创建的方法画圆,但我得到了一个 nullPointerException

public class GenealogyTreeGUI extends JFrame {
JFrame frame;
Graphics2D g2;

public GenealogyTreeGUI(){
    frame = new JFrame("Genealoy Tree");
    JPanel panel = new JPanel();
    frame.add(panel);
    frame.setVisible(true);
    panel.setVisible(true);

}

这是我的方法

 public void drawPerson(int x, int y, Person p1){
    System.out.println("----------------------DrawPerson---------------------------------");
    this.g2.drawOval(x, y, frame.getWidth()/12 , frame.getHeight()/12 );
}

您可以:

  1. 创建所需大小的 BufferedImage
  2. 通过 createGraphics()(对于 Graphics2D 对象)或 getGraphics()(对于 Graphics 对象)获取其 Graphics 对象
  3. 用上面的图形对象绘制,然后.dispose()
  4. 通过 new ImageIcon(myImage)
  5. 使用上图创建一个 ImageIcon
  6. 通过.setIcon(myIcon)
  7. 在JLabel中显示图标

完成

例如,

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.*;

public class SomeDrawingFoo extends JPanel {
    private static final int IMG_W = 400;
    private static final int IMG_H = IMG_W;
    private static final Color COLOR_1 = Color.RED;
    private static final Color COLOR_2 = Color.BLUE;
    private static final float DELTA = 40f;
    private JLabel label = new JLabel();

    public SomeDrawingFoo() {

        // create image and draw with it
        BufferedImage myImage = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);       
        Graphics2D g2 = myImage.createGraphics();
        Paint gradPaint = new GradientPaint(0, 0, COLOR_1, DELTA, DELTA, COLOR_2, true);
        g2.setPaint(gradPaint);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fillOval(10, 10, IMG_W - 20, IMG_H - 20);        
        g2.dispose();

        // put image into Icon and then into JLabel
        Icon myIcon = new ImageIcon(myImage);
        label.setIcon(myIcon);
        add(label);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()-> {
            JFrame frame = new JFrame("Foo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new SomeDrawingFoo());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

}

备注:

  • 您也可以在 JPanel 或 JFrame 上调用 .getGraphics(),但获得的对象将不稳定或持久,这将导致图像消失或导致 NullPointerException。我绝对推荐这个
  • 通常,最简单 的绘图方式就是您声明不希望采用的方式 - 在 JPanel 的 protected void paintComponent(Graphics g) 方法中绘制。