Java-图形界面-paintComponent

3,303 阅读2分钟

自己如何创建绘图组件:创建JPanel的子类并覆盖掉paintComponent()这个方法

//需要引入这些包
import javax.swing.*;
import java.awt.*;
//创建JPanel的子类
public class MyDrawPanel extends JPanel {
    //这是非常重要的方法,你绝不能自己调用,要由系统来调用
    public void paintComponent(Graphics g){
        //你可以把g想象成绘图装置,告诉它要用什么颜色画出什么形状
        g.setColor(Color.orange);
        g.fillRect(20, 50, 100, 100);
    }
}

调用:

import javax.swing.*;
public class getCP {
    public static void main(String[] args) {
        JFrame frame=new JFrame();
        MyDrawPanel myDrawPanel=new MyDrawPanel();
        frame.getContentPane().add(myDrawPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
        frame.setVisible(true);
    }
}

效果:

示例一:在paintComponent()中显示图片

@Override
protected void paintComponent(Graphics g) {
    Image image=new ImageIcon("src/images/cat.jpg").getImage();
    g.drawImage(image, 3,4,this);
}

示例二:在paintComponent()中画上随机色彩的圆圈

public class RandomCircle extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        //以默认颜色填充
        //前两个参数是起点的坐标,后面两个参数分别是宽度和高度。
        //此处取得本身的宽高,因此会把panel填满
        g.fillRect(0,0,this.getWidth(),this.getHeight());

        int red=(int)(Math.random()*255);
        int green=(int)(Math.random()*255);
        int blue=(int)(Math.random()*255);
        //传入3个参数来代表RGB值
        Color randomColor=new Color(red,green,blue);
        g.setColor(randomColor);
        //填满参数指定的圆形区域
        g.fillOval(70,70,100,100);
    }
}

效果:

示例三:在paintComponent()中画上渐层颜色的圆圈

public class GradientColor extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        //实际上是个Graphics2D对象
        Graphics2D graphics2D=(Graphics2D)g;
                                                     //起点  开始的颜色   终点  渐层最后的颜色
        GradientPaint gradientPaint=new GradientPaint(70,70,Color.blue,150,150,Color.orange);
        //将虚拟的笔刷换成渐层
        graphics2D.setPaint(gradientPaint);
        //用目前的笔刷设定来填满圆形区域
        graphics2D.fillOval(70,70,100,100);
    }
}

效果:

示例四:在paintComponent()中画上随机渐层颜色的圆圈

public class GradientColor extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D graphics2D=(Graphics2D)g;
        
        int red=(int)(Math.random()*255);
        int green=(int)(Math.random()*255);
        int blue=(int)(Math.random()*255);
        Color startColor=new Color(red,green,blue);

        red=(int)(Math.random()*255);
        green=(int)(Math.random()*255);
        blue=(int)(Math.random()*255);
        Color endColor=new Color(red,green,blue);
        
        GradientPaint gradientPaint=new GradientPaint(70,70,startColor,150,150,endColor);
        graphics2D.setPaint(gradientPaint);
        graphics2D.fillOval(70,70,100,100);
    }
}