em có code sau:
public class NewClass2 extends JFrame implements ActionListener {
JButton button1;
JButton button2;
JLabel label;
public NewClass2() {
this.setSize(500, 400);
setLocation(500, 250);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
add(label);
label.setSize(400, 300);
//HinhAnh("abc.gif");
setVisible(true);
button1 = new JButton("Next");
button2 = new JButton("Previous");
add(button1, "East", 0);
add(button2, "North", 0);
button1.addActionListener(this);
button2.addActionListener(this);
}
public static void main(String[] args) {
NewClass2 t = new NewClass2();
}
public void HinhAnh(String str) {
BufferedImage image = null;
try {
image = ImageIO.read(new File(str));
} catch (IOException ex) {
Logger.getLogger(NewClass2.class.getName()).log(Level.SEVERE, null, ex);
}
int x = label.getSize().width;
int y = label.getSize().height;
int ix = image.getWidth();
int iy = image.getHeight();
int dx = 0;
int dy = 0;
if(x / y > ix / iy) {
dy = y;
dx = dy * ix / iy;
} else {
dx = x;
dy = dx * iy / ix;
}
ImageIcon icon = new ImageIcon(image.getScaledInstance(dx, dy, Image.SCALE_SMOOTH));
label.setIcon(icon);
}
@Override
public void actionPerformed(ActionEvent e) {
String s[] = {"a25.jpg", "abc.gif", "agh.jpg", "down.jpg", "hacker.jpg", "picture.jpg"};
int i = -1;
JButton b = (JButton) e.getSource();
if(b == button1) {
if(i < s.length) {
i++;
this.HinhAnh(s[i]);
} else {
JOptionPane.showConfirmDialog(null, "Da het hinh anh", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
if(b == button2) {
if(i > 0) {
i--;
this.HinhAnh(s[i]);
}
}
}
}
em muốn khi click vào button thì nó chuyển sang ảnh khác… nhưng khi click thì nó lại ném ra ngoại lệ trong phương thức `HinhAnh… Em không hiểu tại sao ? Mong mọi người giúp…