‘壹’ Java Swing 怎么自定义界面背景图片
在java swing中需要为容器添加自定义图片或者背景图片。提供两种简单的解决方案,一种利用JPanel,另一种利用JLabel,代码如下:
1、JPanel(源代码)
packageoo;
importjava.awt.Graphics;
importjava.awt.Image;
importjava.io.File;
importjavax.swing.ImageIcon;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
publicclassDrawing{
JFramejframe=newJFrame();
publicstaticJPanelGImage=null;
publicDrawing(){
initFrame();
}
//初始化窗口
publicvoidinitFrame(){
//利用JPanel添加背景图片
GImage=newJPanel(){
protectedvoidpaintComponent(Graphicsg){
ImageIconicon=newImageIcon("image\benbenla.jpg");
Imageimg=icon.getImage();
g.drawImage(img,0,0,icon.getIconWidth(),
icon.getIconHeight(),icon.getImageObserver());
jframe.setSize(icon.getIconWidth(),icon.getIconHeight());
}
};
jframe.setTitle("测试背景图片");
jframe.add(GImage);
jframe.pack();
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicstaticvoidmain(String[]args){
newDrawing();
}
}
2、JLabel源代码
packageswing.draw;
importjava.awt.Image;
importjavax.swing.ImageIcon;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
/**利用JLabel来构建图片*/
publicclassDrawing2{
JLabeljlpic=newJLabel();
JFramejframe=newJFrame();
publicDrawing2(){
init1Frame();
}
publicvoidinit1Frame(){
ImageIconicon=newImageIcon("image\benbenla.jpg");
icon.setImage(icon.getImage().getScaledInstance(icon.getIconWidth(),
icon.getIconHeight(),Image.SCALE_DEFAULT));
System.out.println(icon.getIconHeight()+""+icon.getIconWidth());
jlpic.setBounds(0,0,1366,768);
jlpic.setHorizontalAlignment(0);
jlpic.setIcon(icon);
jframe.setSize(1366,768);
jframe.add(jlpic);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
publicstaticvoidmain(Stringargs[]){
newDrawing2();
}
}
添加控件:
jlpic.setIcon(icon);
Containerc=newContainer();
JLabeluser=newJLabel("用户:");
JLabelpassword=newJLabel("密码:");
JTextFieldtxf_userName=newJTextField();
JPasswordFieldpwd_password=newJPasswordField()
{
publicvoidpaste(){
UIManager.getLookAndFeel().provideErrorFeedback(this);
}
};
user.setBounds(200,25,50,25);
password.setBounds(200,52,50,25);
txf_userName.setBounds(300,25,150,25);
pwd_password.setBounds(300,52,150,25);
c.add(user);
c.add(txf_userName);
c.add(password);
c.add(pwd_password);
c.add(jlpic);
jframe.setSize(1366,768);
//jframe.add();
jframe.add(c);
‘贰’ 安卓在java代码中怎么添加imageView图片
1、创建imageview对象
2、设置imageview的图片
3、添加到布局中
示例代码
ViewGroupgroup=(ViewGroup)findViewById(R.id.viewGroup);//获取原来的布局容器
ImageViewimageView=newImageView(this);//创建imageview
imageView.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));//image的布局方式
imageView.setImageResource(R.drawable.ic_launcher);//设置imageview呈现的图片
group.addView(imageView);//添加到布局容器中,显示图片。