《Java数字图像处理:编程技巧与应用实践》——1.3 用Java Swing绘制自定义的JPanel...

本节书摘来自华章计算机《Java数字图像处理:编程技巧与应用实践》一书中的第1章,第1.3节,作者 贾志刚,更多章节内容可以访问云栖社区“华章计算机”公众号查看。

1.3 用Java Swing绘制自定义的JPanel

Swing的JPanel组件是GUI编程中最重要的面板组件,可以通过重写JPanel中paint-Component方法实现对JPanel面板组件的背景颜色的调整或添加背景图片,进而实现自定义版本的面板(JPanel)组件。只要完成如下几步就可以实现一个简单自定义JPanel面板的绘制。

1)实现对JPanel面板的继承,代码如下:

public class CustomJPanel extends JPanel
{
    // 更多代码
}

2)完成对paintComponent(Graphics g)对象的重载,代码如下:

Protected void paintComponent(Grahpics g)
{
    // 绘制代码
}

3)访问Graphics绘制引擎,设置画笔颜色并完成绘制,在Java 2D中paint支持三种不同的画笔颜色填充策略,它们分别是:

单一颜色填充,如Color.BLUE、Color.RED等。代码如下:

// 单一颜色背景填充
g2.setPaint(Color.BLUE);

线性渐变颜色填充(GradientPaint),可以细分为水平与竖直方向。代码如下:

// 水平方向线性渐变颜色填充
Color sencondColor = new Color(99, 153, 255);
GradientPaint hLinePaint = new GradientPaint(0, 0, Color.BLACK, 
        this.getWidth(), 0,sencondColor);
g2.setPaint(hLinePaint);
    
// 竖直方向线性渐变颜色填充
Color controlColor = new Color(99, 153, 255);
GradientPaint vLinePaint = new GradientPaint(0, 0, Color.BLACK, 
        0, getHeight() ,controlColor);
g2.setPaint(vLinePaint);

圆周径向渐变颜色填充(RadialGradientPaint),支持两种以上的颜色渐变。代码如下:

// 圆周径向渐变颜色填充
float cx = this.getWidth() / 2;
float cy = this.getHeight() / 2;
float radius = Math.min(cx, cy);
float[] fractions = new float[]{0.1f, 0.5f, 1.0f};
Color[] colors = new Color[]{Color.RED, Color.GREEN,
                Color.BLUE};
// cx, cy表示圆周的中心点距离
// radius 表示半径长度, 
// fractions表示色彩渐变关键帧位置,每个值取值在0~1之间
// colors 表示颜色数组
RadialGradientPaint rgp = new RadialGradientPaint(cx, cy,
    radius, fractions, colors, CycleMethod.NO_CYCLE);
g2.setPaint(rgp);

4)设置背景图片支持。很多时候我们希望JPanel背景是一张图片而不是颜色填充,此时只需要将BufferedImage对象通过drawImage()方法放在paintComponent()中即可,唯一需要注意的地方就是确保BufferedImage对象不为NULL。代码如下:

// 图片作为背景填充
if(image != null)
{
    // 0,0表示图像起始位置,相对于坐标为左上角位置
    g2.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

5)实现一个测试的main方法代码如下:

public static void main(String[] args)
{
    JFrame ui = new JFrame("Custom JPanel");
    ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ui.getContentPane().setLayout(new BorderLayout());
    ui.getContentPane().add(new CustomJPanel(), 
            BorderLayout.CENTER);
    ui.setPreferredSize(new Dimension(380, 380));
    ui.pack();
    ui.setVisible(true);
}

读者可以下载相关文档查看完整的源代码,源代码是本书的一部分,请读者尽量运行源代码,这样可以更好地帮助读者理解所学内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值