search
HomeJavajavaTutorialHow to use the paint method to draw pictures in java

The main content of this article is about using the paint method to draw pictures in Java. It has certain reference value. Interested friends can learn about it. hope it is of help to you.

java uses the paint method to draw pictures

You need to inherit the JFrame class to draw the window=> public class Game extends JFrame {}
setTitle(String s); / /Set window title
setLocation(int x, int y); //Set window position
setSize(int width, int height); //Set window width and height
setVisible(true); // The setting window is visible, and the default is flase. It is better to put this method after setLocation() and setSize. I put it in front and the window is black. The default is white.

paint method drawing
Automatically call after definition

public class paint(Graphics g) {
        Color c = g.getColor();   //记录原来的颜色
        Font f = g.getFont();     //记录原来的字体
        g.setColor(Color.BLACK);  //设置画线的颜色
        g.drawLine(int x1, int y1, int x2, int y2); //两点画直线
        g.drawRect(int x, int y, int width, int height);  //左上角顶点加宽高画矩形
        g.fillRect(int x, int y, int width, int height);  //画填充矩形
        g.setFont(new Font("楷体", Font.BOLD, 40));   //设置字体为楷体,粗体,大小为40
        g.drawString(str, int x, int y);  //画出str字符串
        g.setColor(c);  //变回原来的颜色
        g.setFont(f);   //变回原来的字体}

GameUtil tool class import image

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class GameUtil {
    // 工具类最好将构造器私有化。
    private GameUtil() {

    }

    public static Image getImage(String path) {
        BufferedImage bi = null;
        try {
            URL u = GameUtil.class.getClassLoader().getResource(path);
            bi = ImageIO.read(u);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }}

Call GameUtil in Game class
Image imag = GameUtil .getImage("images/picture.png"); //I created an images package to store pictures. The path of the picture is in the quotation marks
g.drawImage(imag, x, y, width, height, null ); //imag picture, position, width and height, observer

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
public class MyGame extends JFrame{
        Image imag = GameUtil.getImage("images/text1.png");  //指定图片
        @Override
        public void paint(Graphics g) {
                Color c = g.getColor();
                Font f = g.getFont();
                g.setColor(Color.BLUE);             //设置线体颜色
                g.drawLine(100, 100, 650, 100);     //直线
                g.drawRect(50, 150, 200, 200);      //空心矩形
                g.fillRect(550, 150, 200, 200);      //实体矩形
                g.drawOval(300, 150, 200, 200);      //圆形
                g.setFont(new Font("楷体", Font.BOLD, 90));   //设置字体
                g.drawString("How are you?", 100, 100);      //写字
                g.drawImage(imag, 250, 400, 300, 300, null);   //插入图片
                g.setColor(c);     //线条颜色变为原来的样子
                g.setFont(f);      //字体变为原来的样子
        }
        public void launchJFrame() {
                this.setTitle("我的游戏");       //设置窗口标题
                this.setSize(800, 800);        //设置窗口大小
                this.setLocation(100, 100);    //设置窗口位置
                this.setVisible(true);         //设置窗口可见
                /*this.addWindowListener(new WindowAdapter() {    //叉掉窗口后,结束窗口所在的应用程序
                        @Override
                        public void windowClosing(WindowEvent e) {
                                System.exit(0);
                        }
                });     */
                this.setDefaultCloseOperation(EXIT_ON_CLOSE);   //叉掉窗口后,结束窗口所在的应用程序

        }
        public static void main(String args[]) {
                        MyGame game = new MyGame();
                        game.launchJFrame();
                }}

Set the size of the picture
public Image getScaledInstance(int width, int height, int hints) //hints - a flag indicating the type of algorithm used for image resampling (I don’t know what this sentence means, just write it as follows)

Image img = GameUtil.getImage("images/text1.jpg");img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);

If you want to get the picture Size, just use the getWidth() and getHeight() methods

width = img.getWidth();height = img.getheight();

Double buffering technology to solve flickering
The principle is probably: first transfer the required Load the drawn things into the buffer, and then draw all the contents in the buffer to the screen. This can avoid the screen from flashing like crazy because too many things are loaded on the screen.

public void paint(Graphics g){
        BufferedImage imag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   //构建缓冲区
        Graphics g2 = imag.creatGraphics();   //新建一支画笔,使用这支画笔来将内容画到缓冲区中
        g2.drawRect(...);    //括号里面的参数就不写了,此处用来说明一些画图操作
        g2.drawImag(...);
        g2.fillOval(...);
        g.drawImage(imag, x, y, width, height, null);   //将内容画到屏幕上}

Related tutorials: Java Video tutorial

The above is the detailed content of How to use the paint method to draw pictures in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function