明天就圣诞节了(虽然感觉和我没什么关系。。)

在各个网站上都有发很多圣诞树的编码,一些学编程的朋友也分享了他们写的圣诞树

因为我Java刚学一个多月,还没有自己做过东西,所以不禁怀疑自己能不能用Java做出圣诞树

然后。。事实就是,能做一个勉勉强强的圣诞树(但是没有女朋友!。。)。

先看看效果

先加上背景图片链接:百度安全验证

这个背景大家可以自己网上找,然后保存到文件夹图片名改简单一点,要能找到路径)

后面是代码:

package com.itmeteors;
import javax.swing.*;
import java.awt.*;

class util {
    public static Image bg = Toolkit.getDefaultToolkit().getImage("D:\\idea\\bjtp\\sdbj2.jpg");
}

public class Test extends JFrame {
    public static void main(String[] args) {
        Test TuPian = new Test();
            TuPian.launch();
    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(util.bg,0,0,null);
        g.setColor(Color.green);
        g.setFont(new Font("黑体",Font.BOLD,10));
//        g.drawString("圣",295,100);
//        g.drawString("圣诞快",285,115);
        String[] s = {"圣","诞","快","乐","!","圣","诞","快","乐","!","圣","诞","快","乐","!"
                ,"圣","诞","快","乐","!","圣","诞","快","乐","!","圣","诞","快","乐","!"
                ,"圣","诞","快","乐","!","圣","诞","快","乐","!","圣","诞","快","乐","!"
                ,"圣","诞","快","乐","!","圣","诞","快","乐","!","圣","诞","快","乐","!"};
        //第一块
        for (int i =110;i < 230;i += 15){
            for(int j = 0;j < (i-110)*2/15+1;j ++){
                g.drawString(s[j],295-(i-110)/3*2+10*j,i);
            }
        }
        //第二块
        for (int i =230;i<355;i+=15){
            for (int j = 0;j < (i-215)*2/15+3;j ++)
            g.drawString(s[j],275-(i-230)/3*2+10*j,i);
        }
        //第三块
        for (int i =365;i<560;i+=15){
            for (int j = 0;j < (i-365)*2/15+9;j ++)
            g.drawString(s[j],255-(i-365)/3*2+10*j,i);
        }
        g.setColor(new Color(230,120,0));
        for (int i =560;i<630;i+=15){
            g.drawString("圣诞快乐!",275,i);
        }
    }

    public void launch() {
//       设置窗口是否可见
        this.setVisible(true);
//        设置窗口大小
        this.setSize(600,700);
//        设置窗口位置
        this.setLocationRelativeTo(null);
//        设置窗口标题
        this.setTitle("圣诞树");
    }
}

我是在单元下建了个包写的,写在分开的类也没关系,两个类间能访问到就行。

旁边的目录大概长这样(很多没用的不要管,我背景图片放在的bjtp里):

你自己也可以对树进行加工。 

希望文章对你有所帮助!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐