/****************************** 會考題第四題:圖形旋轉 ********************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; public class b4 extends JFrame //畫圖物件是JFrame的擴充 { Container c; Color bgcolor=Color.white; Color textcolor=Color.red; JButton rot0,rot1,rot2,rot3,rot4; JLabel lab1=new JLabel("來源檔名:"); JLabel lab2=new JLabel("目標檔名:"); imgZ1 act=new imgZ1(); JTextField text_s,text_d; public b4() //建構元 { super("旋轉圖形"); c=getContentPane(); //設定UI元件 rot1=new JButton("不轉"); rot2=new JButton("90度"); rot3=new JButton("180度"); rot4=new JButton("270度"); rot0=new JButton("結束"); text_s=new JTextField("source file",10); text_d=new JTextField("Dest file",10); setSize(400,300); c.setLayout(new FlowLayout(FlowLayout.CENTER)); c.add(lab1); c.add(text_s); c.add(lab2); c.add(text_d); c.add(rot1); c.add(rot2); c.add(rot3); c.add(rot4); c.add(rot0); //安置Listener rot0.addActionListener(act); rot1.addActionListener(act); rot2.addActionListener(act); rot3.addActionListener(act); rot4.addActionListener(act); show(); } public void paint(Graphics g) //真正的畫圖設定 { super.paint(g); } class imgZ1 implements ActionListener { byte data[][][]=new byte[300][300][3];//300*300*3 byte byte ndata[][][]=new byte[300][300][3];//300*300*3 byte byte header[]=new byte[54];//54位元表頭 public void file_read() throws IOException //讀取來源檔案 { int i,j; FileInputStream fr=new FileInputStream(text_s.getText()); fr.read(header,0,54); for (i=0;i<300;i=i+1) for (j=0;j<300;j=j+1) fr.read(data[i][j],0,3); fr.close(); } public void file_write() throws IOException//寫入目標檔案 { int i,j; FileOutputStream fw=new FileOutputStream(text_d.getText()); fw.write(header,0,54); for (i=0;i<300;i=i+1) for (j=0;j<300;j=j+1) fw.write(ndata[i][j],0,3); fw.close(); } public void actionPerformed(ActionEvent e) //按鈕事件處理 { int x,y,k; byte tmp; if (e.getSource()==rot0)//結束 { System.exit(0); } /***如果不是結束,就一定要讀來源檔**/ try {file_read();} catch(IOException e1) { System.out.println(text_s.getText()+"Reading Error!"); } /***透過檢查那個按鈕呼叫的,就可以判定該做的動作 ***/ if (e.getSource()==rot1)//不動 { for (x=0;x<300;x=x+1) for (y=0;y<300;y=y+1) for (k=0;k<3;k=k+1) { ndata[y][x][k]=data[y][x][k]; } } else if (e.getSource()==rot2)//轉90度 { for (x=0;x<300;x=x+1) for (y=0;y<300;y=y+1) for (k=0;k<3;k=k+1) { ndata[299-x][y][k]=data[y][x][k]; } } else if (e.getSource()==rot3)//轉180度 { for (x=0;x<300;x=x+1) for (y=0;y<300;y=y+1) for (k=0;k<3;k=k+1) { ndata[y][x][k]=data[299-y][299-x][k]; } } else if (e.getSource()==rot4)//轉270度 { for (x=0;x<300;x=x+1) for (y=0;y<300;y=y+1) for (k=0;k<3;k=k+1) { ndata[x][299-y][k]=data[y][x][k]; } } //一定要寫檔到目的檔案 try {file_write();} catch(IOException e1) { System.out.println(text_d.getText()+"Open Error!"); } repaint(); //重新顯示一次 } } public static void main(String args[]) //程式起點 { b4 app=new b4(); //畫圖 app.addWindowListener(new WindowAdapter(){ //匿名內部類別 public void windowClosing(WindowEvent e) { System.exit(0); } }); //處理視窗關閉要求 } }