日期:2014-05-20 浏览次数:20725 次
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.io.*; public class AppPanel extends JPanel { //variables and components========================== private JPanel imageBox; private JPanel toolPane; private JLabel counterLabel; private int counter; private boolean showWholeImage; private JButton selectButton; private JButton breakButton; private JButton viewImageButton; private Image[] images; private Image wholeImage; private JFileChooser chooser; //constructor============================= public AppPanel(){ //initial variables chooser = new JFileChooser(); images=new BufferedImage[24]; wholeImage=null; showWholeImage = true; counter=0; setLayout(new BorderLayout()); //initial components imageBox = new JPanel(); imageBox.setBackground(Color.WHITE); toolPane = new JPanel(); counterLabel = new JLabel("操作次数:"+counter); viewImageButton = new JButton("显示原图"); selectButton = new JButton("选择图片"); selectButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ if(JFileChooser.APPROVE_OPTION==chooser.showOpenDialog(null)){ try{ wholeImage = ImageIO.read(chooser.getSelectedFile()); showWholeImage=true; repaint(); } catch(Exception e){ JOptionPane.showMessageDialog(null, "打开文件失败"); } } } }); breakButton = new JButton("打乱图片"); toolPane.add(counterLabel); toolPane.add(selectButton); toolPane.add(breakButton); toolPane.add(viewImageButton); add(toolPane,BorderLayout.SOUTH); add(imageBox); } //paintComponents public void paintComponent(Graphics g){ super.paintComponent(g); Graphics g2d = imageBox.getGraphics(); if(showWholeImage && wholeImage!=null){ g2d.drawImage(wholeImage,0,0,imageBox); } else{ int x =0,y=0; for(int i=0;i<24;i++){ g2d.drawImage(images[i],x, y, null); } } } }