[英]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 );
}
你可以:
createGraphics()
(對於 Graphics2D 對象)或getGraphics()
(對於 Graphics 對象)獲取其圖形 object.dispose()
就可以了new ImageIcon(myImage)
使用上面的圖像創建一個 ImageIcon.setIcon(myIcon)
在 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);
});
}
}
筆記:
.getGraphics()
,但獲得的 object 將不穩定或持久,這將導致圖像消失或導致 NullPointerException。 我絕對不推薦這個protected void paintComponent(Graphics g)
方法中繪制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.