要将按钮图形化,只需创建一个ImageIcon对象,将图形路径赋予ImageIcon对象,然后将该对象传递给按钮即可。
此处涉及eclipse中图形的路径设置,包括(项目路径下、非项目路径下、相对路径、绝对路径),相对路径前不加/,此处相对路径是相对于eclipse中项目文件夹而言的,绝对路径为图形所在未知的具体路径。以picture1.jpg(在H:/java/workspace/study/src/picture路径下)为例:
1.若将picture文件夹置于study/src路径(非项目路径)下:
1.1 绝对路径: H:/java/workspace/study/src/picture/picture1.jpg
1.2 相对路径: src/picture/picture1.jpg
2.若将picture文件夹置于study路径(项目路径)下:
2.1 绝对路径不变: H:/java/workspace/study/picture/picture1.jpg
2.2 相对路径: picture/picture1.jpgpackage test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class PictureLabel extends JFrame{
private static Icon[] pictures;
private JButton jb,jb1 = new JButton("Disable");
private boolean mad = false;
public PictureLabel()
{
pictures = new Icon[]{
new ImageIcon("src/picture/picture1.jpg"), //相对路径
new ImageIcon("H:/java/workspace/study/src/picture/picture2.jpg"), //绝对路径
new ImageIcon("src/picture/picture3.jpg"),
new ImageIcon("src/picture/picture4.jpg"),
new ImageIcon("src/picture/picture5.jpg")
};
//路径前不加/为相对路径
jb = new JButton("JButton",pictures[3]);
setLayout(new FlowLayout());
jb.addActionListener(new ActionListener(){
@Override//保证被标注的方法确实覆盖了基类的方法,否则编译会出错
public void actionPerformed(ActionEvent e)
{
if(mad)
{
jb.setIcon(pictures[3]);
mad = false;
}else
{
jb.setIcon(pictures[0]);
mad = true;
}
jb.setVerticalAlignment(JButton.TOP);
jb.setHorizontalAlignment(JButton.LEFT);
}
});
jb.setRolloverEnabled(true); //允许翻转图标
jb.setRolloverIcon(pictures[1]);
jb.setPressedIcon(pictures[2]);
jb.setDisabledIcon(pictures[4]);
jb.setToolTipText("Yow");
add(jb);
//如果 setRolloverEnabled 为 true,则当鼠标移动到按钮上时,setRolloverIcon的内容就被用到该按钮的图形上,即picture[1];
//当按下按钮时,setPressedIcon的内容被用到该按钮的图形上,即picture[2];当按钮被禁止时,setDisabledIcon的内容被应用到按钮,
//即picture[4]。
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(jb.isEnabled())
{
jb.setEnabled(false);
jb1.setText("Enable");
}else
{
jb.setEnabled(true);
jb1.setText("Disable");
}
}
});
add(jb1);
}
public static void main(String[] args)
{
run(new PictureLabel(),500,200);
}
}
编译可得按钮具有动画效果。
注意:1、相对路径前不加/;
2、在eclipse中,程序中引入的文件的路径是相对于项目文件夹而言的;
发布php中文网,转载请注明出处,感谢您的尊重!