import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
public class ImgDemo extends JFrame {
private JPanel contentPane;
private int idImg = 1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImgDemo frame = new ImgDemo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ImgDemo() {
setTitle("\u56FE\u7247\u663E\u793A");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 404);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBackground(Color.YELLOW);
lblNewLabel.setForeground(Color.PINK);
lblNewLabel.setBounds(48, 86, 467, 248);
contentPane.add(lblNewLabel);
JButton btnNewButton = new JButton("\u663E\u793A\u4E0B\u4E00\u5F20\u56FE\u7247");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// 获取图片的路径
String strImgFile = "D:/demoPhoto/";
// 得到图片的完整路径
strImgFile = strImgFile + String.valueOf(idImg) + ".jpg";
// 读取图片
ImageIcon icon = new ImageIcon(ImageIO.read(new File(strImgFile)));
// 从图表中获取到图片
Image image = icon.getImage();
// 缩放图像
Image smallImage = image.getScaledInstance(200,200,Image.SCALE_FAST);
//把Image文件转化为ImageIcon
icon = new ImageIcon(smallImage);
lblNewLabel.setIcon(icon);
// 为下一张图片做准备,一共9张图片,显示完第9张后,重新显示第1张
idImg = idImg+1;
if(idImg==10)
idImg = 1;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(194, 37, 153, 28);
contentPane.add(btnNewButton);
JButton btnNewButton0 = new JButton("显示上一个图片");
btnNewButton0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// 获取图片的路径
String strImgFile = "D:/demoPhoto/";
// 得到图片的完整路径
strImgFile = strImgFile + String.valueOf(idImg) + ".jpg";
// 读取图片
ImageIcon icon = new ImageIcon(ImageIO.read(new File(strImgFile)));
// 从图表中获取到图片
Image image = icon.getImage();
// 缩放图像
Image smallImage = image.getScaledInstance(200,200,Image.SCALE_FAST);
//把Image文件转化为ImageIcon
icon = new ImageIcon(smallImage);
lblNewLabel.setIcon(icon);
// 为下一张图片做准备,一共9张图片,显示完第1张后,重新显示第9张
idImg = idImg-1;
if(idImg==0)
idImg = 9;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton0.setBounds(40, 37, 153, 28);
contentPane.add(btnNewButton0);
}
}
《Java程序设计》第14周实验作业:GUI编程初步
最新推荐文章于 2020-02-20 15:36:51 发布