用Java绘制最简单的方法是什么?

Boo*_*reg 2 java swing paint

用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,我不知道如何让任何东西出现.

jjn*_*guy 6

最简单的方法:

public class Canvas extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        // painting code goes here.
    }
}
Run Code Online (Sandbox Code Playgroud)

您只需要扩展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);
}
Run Code Online (Sandbox Code Playgroud)

  • @Neo覆盖油漆通常会让它忘记它的组件也需要涂漆.它适用于简单,天真的程序,但随着你变得越来越复杂,你会发现你的底层东西停止被绘制,它没有任何意义. (2认同)