JPanel添加背景图片

需要重写JPanel的构造函数

1
2
3
4
5
6
7
8
mypanel = new JPanel(){
protected void paintComponent(Graphics g) {
ImageIcon icon = new ImageIcon("topline.png");
Image img = icon.getImage();
g.drawImage(img, 0, 0, lenth, high/8, icon.getImageObserver());
//从左到右分别是,图片资源,起始x点,起始y点,长,宽,图片视图
}
};

控制图片大小

把图片按等比例缩小或放大

1
2
ImageIcon bIcon = new ImageIcon("./src/resource/z001.jpg");
bIcon.setImage(bIcon.getImage().getScaledInstance(75, 75, Image.SCALE_DEFAULT));

设置左上角和任务栏的Logo

这是在一个继承JFrame类的类的构造函数里的代码。

1
2
3
this.setTitle("游戏商店");
ImageIcon frameImage=new ImageIcon("smoney.png");
this.setIconImage(frameImage.getImage());

设置字体

1
2
3
JLabel tmp=new JLabel("Coins");
tmp.setFont(new Font("幼圆", Font.CENTER_BASELINE, 24));
tmp.setForeground(Color.BLUE);

设置背景音乐

1
2
3
4
5
6
7
8
9
10
URL cb;
File f = new File("./src/1.wav");
try {
cb = f.toURL();
BackMusic = Applet.newAudioClip(cb);
BackMusic.loop();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

UI和后台数据的同步

在重写repaint方法,加入你的数据变化。

JFrame的可见、可调大小、出现位置

1
2
3
4
mJFrame.setResizable(false);
mJFrame.setLocationRelativeTo(null);
//null 是全屏幕中心 this 是父框中心
mJFrame.setVisible(true);

txt数据文档的读写

详见我的另一篇博文,java的输入输出,这里我就只写一种了

写txt

1
2
3
FileOutputStream inputFile= new FileOutputStream("Message.txt");
DataOutputStream out =new DataOutputStream(inputFile);
out.writeInt(10);

读txt

1
2
3
FileInputStream inputFile= new FileInputStream("Message.txt");
DataInputStream in =new DataInputStream(inputFile);
int Point=in.readInt();

注意 写和读数据的顺序不能随意改变

弹射对话框

1
JOptionPane.showMessageDialog(null, "闯关成功");

绝对布局

1
2
3
4
5
JButton RoundBtn = new JButton("开始游戏");
RoundBtn.setBounds(440, 200, 120, 30);
//x轴 y轴 长 宽
RoundBtn.addActionListener(this);
panel.add(RoundBtn);

导出jar包

Resource is out of sync with the file system的解决办法
在eclipse中,启动server时报此错,是因为文件系统不同步造成的,解决方法有两个:
(1)选中工程,右键,选择F5(手动刷新);
(2)Window->Preferences->General->Workspace,选中Refresh automatically(设置eclipse自动刷新)。

暂时就想到这么多。