//: Faces.java
// Icon behavior in JButtons
package c13.swing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Faces extends JPanel {
static Icon[] faces = {
new ImageIcon("face0.gif"),
new ImageIcon("face1.gif"),
new ImageIcon("face2.gif"),
new ImageIcon("face3.gif"),
new ImageIcon("face4.gif"),
};
JButton
jb = new JButton("JButton", faces[3]),
jb2 = new JButton("Disable");
boolean mad = false;
public Faces() {
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(mad) {
jb.setIcon(faces[3]);
mad = false;
} else {
jb.setIcon(faces[0]);
mad = true;
}
jb.setVerticalAlignment(JButton.TOP);
jb.setHorizontalAlignment(JButton.LEFT);
}
});
jb.setRolloverEnabled(true);
jb.setRolloverIcon(faces[1]);
jb.setPressedIcon(faces[2]);
jb.setDisabledIcon(faces[4]);
jb.setToolTipText("Yow!");
add(jb);
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(jb.isEnabled()) {
jb.setEnabled(false);
jb2.setText("Enable");
} else {
jb.setEnabled(true);
jb2.setText("Disable");
}
}
});
add(jb2);
}
public static void main(String args[]) {
Show.inFrame(new Faces(), 300, 200);
}
} ///:~
P.473
以上例程中代码:
static Icon[] faces = {
new ImageIcon("face0.gif"),
new ImageIcon("face1.gif"),
new ImageIcon("face2.gif"),
new ImageIcon("face3.gif"),
new ImageIcon("face4.gif"),
};
改成以下形式才能加载图片:
static Icon[] faces;
static {
try {
faces = new Icon[]{
new ImageIcon(ImageIO.read(new File("src/face0.gif"))),
new ImageIcon(ImageIO.read(new File("src/face1.gif"))),
new ImageIcon(ImageIO.read(new File("src/face2.gif"))),
new ImageIcon(ImageIO.read(new File("src/face3.gif"))),
new ImageIcon(ImageIO.read(new File("src/face4.gif"))),
};
} catch (IOException e) {
throw new RuntimeException(e);
}
}
不知道还有没有其他方法。
标签:ImageIcon,Java,--,45,gif,faces,new,JButton,jb From: https://blog.51cto.com/u_16183536/8724431