小马镇全家福(GUI初步:图片显示)
在MLP每一集的片头曲末尾,一张小马镇的全家福都会被龙火传信所寄出。MLP到目前为止一共播出了6季,其中除了第三季13集以外其他都是26集,即总共寄出了26*5+13=143张照片。但几乎一季当中每一集的照片都是一样的,这无疑造成了资源浪费...
有了FIM++,你可以使用信息化的方式寄送照片,不必担心把预算花费在没用的纸质照片上!(电费另当别论:)
本章涉及Java GUI,有些地方没办法讲的很细请见谅^_^
本章重点:附录1:使用Java类库
我打算用URL的方式让程序从网上(新浪图床)获取图片,加载到标签(JLabel)里,然后添加到JFrame中显示出来,并且使用BorderLayout布局。
阅读附录1的文档后,看以下代码:
Dear Princess Celestia: A Photo of Ponies in Ponyville.
Today I learned:
I enchanted Twilight Sparkle with javax swing j frame.
I enchanted Rarity with java awt border layout.
I enchanted Pinkie Pie with java net u r l.
I enchanted Rainbow Dash with javax swing image icon.
I enchanted Applejack with javax swing j label.
I woke up Rarity with Rarity.
I woke up Pinkie Pie with Pinkie Pie and "https://ww2.sinaimg.cn/large/006tKfTcgy1fhqcjzilojj30go0b47d7.jpg".
I woke up Rainbow Dash with Rainbow Dash and Pinkie Pie.
I woke up Applejack with Applejack and Rainbow Dash.
I woke up Sweetie Belle with Twilight Sparkle and "A Photo of Ponies in Ponyville".
I asked about Sweetie Belle with 600 and 400 of size.
I asked about Sweetie Belle with Rarity of layout.
I stole "exit on close" of Twilight Sparkle and gave it to Fluttershy.
I asked about Sweetie Belle with Fluttershy of default close operation.
I asked about Sweetie Belle and Applejack when they add.
I asked about Sweetie Belle made visible.
Your faithful student, Photo Finishenchanted命令用来声明所调用的java类库,在java中只要import进来就行了,但是FIM++需要以变量名接收它。
我说过,变量是可以重复指定的。所以后面woke up把声明的类库转为对象实例的操作我就直接用原本enchanted使用的变量名接收了,这样不会浪费多余的内存空间(或者说看起来更舒服,或者不用费心机想那么多名字?)。
https://ww2.sinaimg.cn/large/006tKfTcgy1fhqcjzilojj30go0b47d7.jpg处的图片是一张2015年的MLP官方宣传图。
一种写法,asked about和woke up的with前面为调用此对象的方法,后面你可能看到了类似<a>{ and <b>}的写法。这里<a>指的是传入的第一个变量,如有<b>则传入第二个变量。of后面为调用的方法,省略了set,即你写...of size被翻译成java代码之后就是setSize。
另一种写法,and前面为调用此对象的方法,后面为传入的参数,而调用的方法名则在when they后面,不自动省略。
...made <方法名>意为调用此方法(省略set)并传入一个true参数。
懂java的朋友可以看下面的代码:
import java.awt.BorderLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;//enchanted
public class APhotoOfPoniesInPonyville {
public static void main(String[] args) throws Exception{
//对象woke up
BorderLayout Rarity=new BorderLayout();
URL PinkiePie=new URL("https://ww2.sinaimg.cn/large/006tKfTcgy1fhqcjzilojj30go0b47d7.jpg");
ImageIcon RainbowDash=new ImageIcon(PinkiePie);
JLabel Applejack=new JLabel(RainbowDash);
//Java中更简单的写法:JLabel Applejack=new JLabel(new ImageIcon(new URL("https://ww4.sinaimg.cn/large/006tKfTcgy1fhlktrs0wbj30ai0aljsn.jpg")));
JFrame SweetieBelle=new JFrame("A Photo of Ponies in Ponyville");
SweetieBelle.setSize(600, 400);//...of size
SweetieBelle.setLayout(Rarity);//...of layout
int Fluttershy = JFrame.EXIT_ON_CLOSE;//stole
SweetieBelle.setDefaultCloseOperation(Fluttershy);
SweetieBelle.add(Applejack);
SweetieBelle.setVisible(true);//made visible
}
}运行效果:
(图片大小刚好对吧,因为我裁过了...)