蹭个热度用Java画个圣诞树,整体思路就是先画树和灯,画完以后加顶端的星星,之后再加飘雪特效和音乐,最后另做一个窗口,用来读取用户自定义的参数。
首先是画树和灯(Tree.java),这里主要是用 fillRect 和 fillOval来画,最后效果如下:
这里用两张图是想说明,灯串其实做了闪烁效果,也就是repaint的时候,灯的颜色会由有色变无色,无色变有色,所以为了呈现效果,我把树中间的空隙也用fillRect画上了背景色。
接下来是画顶端的星星和飘雪特效(Snow.java),这里为了图方便,飘雪特效用的是自己画的GIF图,星星则是一个button,点击可打开/关闭飘雪特效。同时BGM也放在了这个类里。
最后就是自定义部分。颜色部分(RGB.java)用到了ColorChooser类来选择颜色,还有一个JRadioButton来选择是否使用默认颜色。而树高部分(Xmas.java)则是用的JComboBox来选择对应高度(高度会影响之后画有圣诞树的窗口的大小)。为了美观(乐趣?),我还做了一个开始页面,效果如下:
开始页面:
自定义页面:
完整代码如下:
public class Xmas extends JFrame implements ActionListener{
private int Width, Height;
private boolean submit = false;
JLayeredPane lp = new JLayeredPane();
JLabel ct;
JButton button;
JComboBox<Integer> layerSelected = new JComboBox<>(new MyComboBox());
RGB p1, p2, p3, p4;
ArrayList<Integer> colours = new ArrayList<Integer>();
public Xmas() {
this.setTitle("狐狸子的圣诞树售卖店");
URL iconUrl = this.getClass().getResource("/sources/tree.png");
Image tree = Toolkit.getDefaultToolkit().getImage(iconUrl);
this.setIconImage(tree);
this.setLayout(null);
this.setResizable(false);
this.setSize(800, 650);
this.setLocationRelativeTo(null); //Put the window to the centre of the screen
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Set the background picture*/
URL imgUrl = this.getClass().getResource("/sources/Background.jpg");
ImageIcon background = new ImageIcon(imgUrl);
JLabel bg = new JLabel(background);
bg.setBounds(0, 0, background.getIconWidth(), background.getIconHeight());
/*Set the content*/
URL contentUrl = this.getClass().getResource("/sources/Content.png");
ImageIcon content = new ImageIcon(contentUrl);
ct = new JLabel(content);
ct.setBounds(30,