[英]What is the simplest way to draw in Java?
在 Java 中繪制最簡單的方法是什么?
import java.awt.*;
import javax.swing.*;
public class Canvas
{
private JFrame frame;
private Graphics2D graphic;
private JPanel canvas;
public Canvas()
{
frame = new JFrame("A title");
canvas = new JPanel();
frame.setContentPane(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g){
BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Grapics2D g2 = offImg.createGraphics();
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
}
}
這不起作用,我不知道如何讓任何東西出現。
最簡單的方法:
public class Canvas extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// painting code goes here.
}
}
您只需要擴展JPanel
並覆蓋面板的paintComponent
方法。
我想重申一下,您不應該覆蓋paint
方法。
這是一個非常簡單的例子。
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel p = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, 0, 100, 100);
}
};
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
// No. 1
// Create a graphics context on the buffered image
Graphics2D g2d = bimage.createGraphics();
// Draw on the buffered image
g2d.setColor(Color.red);
g2d.fill(new Ellipse2D.Float(0, 0, 200, 100));
g2d.dispose();
// No.2
// In case the buffered image supports transparency
g2d = bimage.createGraphics();
// Transparency is created on all the filled pixels
Color transparent = new Color(0, 0, 0, 0);
g2d.setColor(transparent);
g2d.setComposite(AlphaComposite.Src);
g2d.fill(new Rectangle2D.Float(20, 20, 100, 20));
g2d.dispose();
要使某些內容出現在paint(Graphics g) 中,您需要調用該Graphics 上的繪圖方法(如fillRect)。 您正在創建位圖,然后繪制到位圖,而不是屏幕。
public void paint(Graphics g){
g.setColor(new Color(255,0,0));
g.fillRect(10,10,200,50);
}
jjnguy 已經寫了如何正確地做到這一點......但是這里為什么它在你的例子中不起作用:
import java.awt.*;
import javax.swing.*;
public class Canvas
這里有一個與 Swing 或 AWT 沒有任何關系的類。 (順便說一句,您可能需要選擇另一個名稱以避免與java.awt.Canvas
混淆。)
{
private JFrame frame;
private Graphics2D graphic;
private JPanel canvas;
public Canvas()
{
frame = new JFrame("A title");
canvas = new JPanel();
frame.setContentPane(canvas);
在這里,您將創建一個新的 JPanel(也稱為canvas
混淆),並將其添加到框架中。 Is 是該面板的paint
和paintComponent
方法,它們在系統顯示您的框架時被調用。
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g){
BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Grapics2D g2 = offImg.createGraphics();
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
}
這個paint方法從不使用(因為它不是組件的一部分),如果它會被調用,那么你只是在繪制一些BufferedImage,而不是屏幕。
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.