import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import javax.swing.*;
import java.io.*;

public class PDF417 extends JPanel implements ActionListener{

    /**
     * @param args
     */	
    private JPanel forms;
    private JPanel actions;
    private boolean freezed;
    private JTextField columns;
    private JTextField verifyLevel;
    private JTextField lengthWidthRate;	
    //private JTextField 
    private JTextField color;
    //private JTextField hieeight;
    private JTextArea info;
    private JLabel imgLabel;
    private JButton fromEditor;
    private JButton fromFile;
    private JButton baoCun;
    private JTextField tfontSize;
    private JTextField lLineCount;
    private JTextField lMargin;
    private JTextField lVMargin;
    private JTextArea tstrTxt;
    private JTextField wordHeight;
    private MakeJNI makejni;
		

    public PDF417() {
	init();
    }
    public native static int JNIMake(String s, long nErrLevel,long nMask,long nBarEdition,long nScale);
    public native static long JNIMixText(String szText,long lFontSize,long lTxtHeight,long lHmargin,long lVmargin,long lTxtCntOneLine);
 
		
    private void init() {		
	if(!freezed) {
	    forms = new JPanel();
	    forms.setBorder(BorderFactory.createTitledBorder(BorderFactory
							     .createEtchedBorder(EtchedBorder.LOWERED), "参数设置"));
	    forms.setLayout(new BorderLayout());
				
	    makejni = new MakeJNI();

	    JPanel params = new JPanel();
	    params.setLayout(new FlowLayout());
				
	    params.add(new JLabel("掩模"));
	    columns = new JTextField("3", 5);
	    params.add(columns);
				
	    params.add(new JLabel("校验等级"));
	    verifyLevel = new JTextField("3", 5);
	    params.add(verifyLevel);
				
	    params.add(new JLabel("缩放"));
	    lengthWidthRate = new JTextField("3", 5);
	    params.add(lengthWidthRate);
				
	    JPanel params2=new JPanel(new FlowLayout(FlowLayout.LEFT));
	    color=new JTextField("24",5);
	    //height=new JTextField("38",5);
	    params2.add(new JLabel("版本"));
	    params2.add(color);
	    //params2.add(new JLabel("高度"));
	    //params2.add(height);
	    JPanel panel=new JPanel(new GridLayout(2,1));
	    panel.add(params);
	    panel.add(params2);
	    forms.add(panel, BorderLayout.NORTH);

	    JPanel codePanel = new JPanel();
	    codePanel.setLayout(new BorderLayout());
	    codePanel.add(new JLabel("条码信息"), BorderLayout.NORTH);
	    JPanel code = new JPanel();
	    code.setLayout(new FlowLayout(FlowLayout.CENTER));
	    info = new JTextArea("2004062100000014ST0005机电式", 7, 13);
	    info.setWrapStyleWord(true);
	    info.setLineWrap(true);
	    code.add(new JScrollPane(info));
				
	    imgLabel = new JLabel();
	    imgLabel.setPreferredSize(new Dimension(160, 129));
	    imgLabel.setMinimumSize(new Dimension(160, 129));
	    imgLabel.setMaximumSize(new Dimension(160, 129));
	    imgLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
	    loadImage();
	    code.add(imgLabel);
	    codePanel.add(code, BorderLayout.SOUTH);
	    forms.add(codePanel, BorderLayout.SOUTH);
				
				
	    JPanel word=new JPanel(new GridLayout(5,1));
	    word.setBorder(BorderFactory.createTitledBorder(BorderFactory
							    .createEtchedBorder(EtchedBorder.LOWERED), "文字信息"));
	    JPanel panel3=new JPanel(new FlowLayout(FlowLayout.LEFT));
	    lLineCount=new JTextField("9",5);
	    panel3.add(new JLabel("每行字数"));
	    panel3.add(lLineCount);
	    word.add(panel3);
	    JPanel panel4=new JPanel(new FlowLayout(FlowLayout.LEFT));
	    tstrTxt=new JTextArea("abcdefg",1, 20);
	    panel4.add(new JLabel("文字信息"));
	    panel4.add(tstrTxt);
	    word.add(panel4);
	    //word.add(lLineCount);
	    //word.add(tstrTxt);
	    JPanel panel1=new JPanel(new FlowLayout(FlowLayout.LEFT));
	    tfontSize=new JTextField("0",5);
	    wordHeight=new JTextField("40",5);
	    panel1.add(new JLabel("字体大小"));
	    panel1.add(tfontSize);
	    panel1.add(new JLabel("文字高度"));
	    panel1.add(wordHeight);
	    word.add(panel1);
	    JPanel panel2=new JPanel(new FlowLayout(FlowLayout.LEFT));
				
				
	    lMargin=new JTextField("10",5);
        		
	    lVMargin=new JTextField("5",5);
	    panel2.add(new JLabel("水平留白"));
	    panel2.add(lMargin);
	    panel2.add(new JLabel("垂直留白"));
	    panel2.add(lVMargin);
	    word.add(panel2);				
				

	    actions = new JPanel();
	    actions.setLayout(new FlowLayout());
	    fromEditor = new JButton("从编辑生成");                       
	    actions.add(fromEditor);
	    fromFile = new JButton("从文件生成");
	    actions.add(fromFile);
	    baoCun=new JButton("保存");
	    actions.add(baoCun);
				
	    word.add(actions);
				

	    setLayout(new BorderLayout());
	    add(forms, BorderLayout.NORTH);
	    add(word, BorderLayout.SOUTH);
	    freezed = true;
	    fromEditor.addActionListener(this);
	    fromFile.addActionListener(this);
	    baoCun.addActionListener(this);					
	}
    }
		
    /*
      public void addEditListener(ActionListener listener) {
      fromEditor.addActionListener(listener);
      }

      public void addFileListener(ActionListener listener) {
      fromFile.addActionListener(listener);
      }
		
      public void addSaveListener(ActionListener listener) {
      save.addActionListener(listener);
      }
    */	
    public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub		
	//事件处理			
	//判断事件源?
			
	//从编辑框生成条码
	if(e.getSource()==this.fromEditor){
	    //int n=makejni.JNISetColorDepth(24);
                       
	    //int m=makejni.JNIGetColorDepth();
	    	    int makeresult = makejni.JNIMake(info.getText(), Long.parseLong(columns.getText()), Long.parseLong(verifyLevel.getText()),Long.parseLong(lengthWidthRate.getText()),Long.parseLong(color.getText()));
	    //makejni.JNIMixText("12345678",0,20,10,5,9);
	    makejni.JNIMixText(tstrTxt.getText(),Long.parseLong(tfontSize.getText()),Long.parseLong(wordHeight.getText()), Long.parseLong(lMargin.getText()),Long.parseLong(lVMargin.getText()),Long.parseLong(lLineCount.getText()));
	    if( makeresult == 0 )
	    JOptionPane.showMessageDialog( this, "QR BarCode generate successfully!");
	    else JOptionPane.showMessageDialog( this, "QR BarCode cannot be generated!");
	}
			
	//从文件中生成条码
	if(e.getSource()==this.fromFile){
	    JFileChooser filechooser = new JFileChooser();
	    filechooser.setFileSelectionMode( JFileChooser.FILES_ONLY);
	    int result = filechooser.showOpenDialog(this);
				
	    //user clicked Cancel button on dialog
	    if( result == JFileChooser.CANCEL_OPTION)
		return;
				
	    File filename = filechooser.getSelectedFile();
	    if( filename == null || filename.getName().equals( "" ))
		JOptionPane.showMessageDialog( this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE);
	    //JOptionPane.showMessageDialog( null, filename);
				
	    FileReader fr = null;
	    try {
		fr = new FileReader( filename );
	    } catch (FileNotFoundException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	    }
	    BufferedReader br = new BufferedReader(fr);
				
	    String text = "";
	    String line = null;
	    try {
		line = br.readLine();
	    } catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	    } 
	    while(line != null) 
		{ 
		    text += line; 
		    try {
			line = br.readLine();
		    } catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		    } 
		}
	    int makeresult = makejni.JNIMake(text, Long.parseLong(verifyLevel.getText()), Long.parseLong(columns.getText()),Long.parseLong(color.getText()),Long.parseLong(lengthWidthRate.getText()));
	    makejni.JNIMixText(tstrTxt.getText(),Long.parseLong(tfontSize.getText()),Long.parseLong(wordHeight.getText()),
			       Long.parseLong(lMargin.getText()),Long.parseLong(lVMargin.getText()),Long.parseLong(lLineCount.getText()));
				
	    if( makeresult == 0 )
		JOptionPane.showMessageDialog( null, "QRBarCode generate successfully!");
	    else JOptionPane.showMessageDialog( null, "QRBarCode cannot be generated!");
	}
			
	if(e.getSource()==this.baoCun){
	    JFileChooser fileSelection=new JFileChooser();
	    int res = fileSelection.showSaveDialog(this);
	    if (res == JFileChooser.CANCEL_OPTION) {
		return;
	    } else {
		try {
		    File fSaveAs = fileSelection.getSelectedFile();
                		
		    FileInputStream fis=new FileInputStream("temp.bmp");
		    FileOutputStream fos=new FileOutputStream(fSaveAs);
		    byte[] b=new byte[1024];
		    int n=0;
		    while((n=fis.read(b))!=-1){
			fos.write(b,0,n);
		    }
		    fis.close();
		    fos.close();
		} catch (Exception event2) {
		    event2.printStackTrace();
		}
	    }
	}
			
						
    }
		
		
		
    private void loadImage() {			
	loadImage("temp.bmp");
    }
		
    private void loadImage(String path) {
	imgLabel.setIcon(createImageIcon(path, ""));
    }
		
    protected static ImageIcon createImageIcon(String path, String description) {
	java.net.URL imgURL = PDF417.class.getResource(path);
	if (imgURL != null) {
	    return new ImageIcon(imgURL, description);
	} else {
	    System.err.println("Couldn't find file: " + path);
	    return null;
	}
    }
		
    private static void createAndShowGUI() {
	JFrame.setDefaultLookAndFeelDecorated(true);
	JFrame frame = new JFrame("二维条码测试");
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setContentPane(new PDF417());
	frame.pack();
	frame.setLocation(300,60);
	frame.setVisible(true);
    }
		
    public static void main(String[] args) {		
	javax.swing.SwingUtilities.invokeLater(new Runnable() {
		public void run() {
		    createAndShowGUI();
		}
	    });
    }

}
