2015-11-16 4 views
0

Я написал ниже код Java. После обращения к нескольким сообщениям, наконец, был создан GUI ;-) в swing.Создать exe или аналогичный файл

GUI:

import java.awt.EventQueue; 

public class DummyFrame extends JFrame { 

    private JPanel contentPane; 
    private JTextField srcTextField; 
    private JTextField destTextField; 
    private JButton btnNewButton; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     } catch (Throwable e) { 
      e.printStackTrace(); 
     } 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        DummyFrame frame = new DummyFrame(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    */ 
    public DummyFrame() { 
     setTitle("DummyFrame"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 635, 452); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 

     JButton srcBtn = new JButton("Source Excel"); 
     srcBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       JFileChooser fChoose = new JFileChooser(); 
       fChoose.showOpenDialog(null); 
       File f = fChoose.getSelectedFile(); 
       srcTextField.setText(f.getAbsolutePath()); 
      } 
     }); 

     srcTextField = new JTextField(); 
     srcTextField.setColumns(10); 

     destTextField = new JTextField(); 
     destTextField.setColumns(10); 

     JButton destBtn = new JButton("Output Excel"); 
     destBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       JFileChooser fChoose = new JFileChooser(); 
       fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
       fChoose.setAcceptAllFileFilterUsed(false); 
       if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
        destTextField.setText(fChoose.getSelectedFile().getAbsolutePath() + "\\"); 
        System.out.println(fChoose.getCurrentDirectory()); 
       } else { 
        System.out.println("No Selection"); 
       } 

      } 
     }); 
     final JTextArea outputTextArea = new JTextArea(); 
     btnNewButton = new JButton("Convert"); 
     btnNewButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       CreateNxi_Main createNxi_Main = new CreateNxi_Main(); 
       try { 
        createNxi_Main.getInputAndOutputPaths(srcTextField.getText(), destTextField.getText() + "\\", 
          outputTextArea); 
       } catch (Exception e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 

      } 
     }); 

     GroupLayout gl_contentPane = new GroupLayout(contentPane); 
     gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) 
       .addGroup(gl_contentPane.createSequentialGroup().addGap(10) 
         .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) 
           .addGroup(gl_contentPane.createSequentialGroup() 
             .addComponent(destTextField, GroupLayout.PREFERRED_SIZE, 421, 
               GroupLayout.PREFERRED_SIZE) 
             .addGap(18) 
             .addComponent(destBtn, GroupLayout.PREFERRED_SIZE, 97, 
               GroupLayout.PREFERRED_SIZE) 
             .addContainerGap()) 
           .addGroup(
             gl_contentPane.createSequentialGroup() 
               .addComponent(srcTextField, GroupLayout.DEFAULT_SIZE, 421, 
                 Short.MAX_VALUE) 
               .addGap(18) 
               .addComponent(srcBtn, GroupLayout.PREFERRED_SIZE, 97, 
                 GroupLayout.PREFERRED_SIZE) 
               .addGap(63)))) 
       .addGroup(gl_contentPane.createSequentialGroup().addContainerGap(261, Short.MAX_VALUE) 
         .addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 107, GroupLayout.PREFERRED_SIZE) 
         .addGap(241)) 
       .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup().addContainerGap() 
         .addComponent(outputTextArea, GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE))); 
     gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane 
       .createSequentialGroup().addContainerGap() 
       .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addComponent(srcBtn).addComponent(
         srcTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) 
       .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false) 
         .addGroup(gl_contentPane.createSequentialGroup().addGap(20).addComponent(destTextField, 
           GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) 
         .addGroup(gl_contentPane.createSequentialGroup().addGap(18).addComponent(destBtn, 0, 0, 
           Short.MAX_VALUE))) 
       .addGap(18).addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE) 
       .addGap(18).addComponent(outputTextArea, GroupLayout.PREFERRED_SIZE, 226, GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(26, Short.MAX_VALUE))); 
     contentPane.setLayout(gl_contentPane); 
    } 
} 

CreteNxi_Main

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import javax.swing.JTextArea; 

import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class CreateNxi_Main { 

    public static void main(String[] args) throws Exception { 
     Date date = new Date(); 
     SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
     String startFormattedDate = sdf.format(date); 
     System.out.println(startFormattedDate); 
     String endFormattedDate = sdf.format(new Date()); 
     System.out.println(endFormattedDate); 
     Date d1 = sdf.parse(startFormattedDate); 
     Date d2 = sdf.parse(endFormattedDate); 
     long diff = d2.getTime() - d1.getTime(); 
     long diffSeconds = diff/1000 % 60; 
     long diffMinutes = diff/(60 * 1000) % 60; 
     System.out.print(diffMinutes + " minutes, "); 
     System.out.print(diffSeconds + " seconds."); 
    } 

    public void getInputAndOutputPaths(String inPath, String outPath, JTextArea outputTextArea) throws Exception { 
     String filePath = inPath; 
     String output = outPath; 

     System.out.println("Src is " + filePath.toString()); 
     System.out.println("Dest Path is " + outPath.toString()); 
     // String destDirectory = "D:\\News\\nxis\\output"; 
     FileInputStream fin = new FileInputStream(new File(filePath)); 
     XSSFWorkbook wb = new XSSFWorkbook(fin); 
     XSSFSheet sheet = wb.getSheetAt(0); 
     int rows = sheet.getPhysicalNumberOfRows(); 
     System.out.println(rows); 
     CreateNxi createNxi = new CreateNxi(); 
     for (int i = 1; i < rows - 1; i++) { 
      String guid = sheet.getRow(i).getCell(2).toString(); 
      String collection = sheet.getRow(i).getCell(1).toString(); 
      outputTextArea.append(guid + "\n"); 
      // System.out.println(collection + "\t" + guid); 
      createNxi.createFiles(guid, collection, output); 
     } 
     wb.close(); 
    } 

} 

CreteNxi:

import java.io.File; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

import org.w3c.dom.Document; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class CreateNxi { 

    void createFiles(String guid, String collection, String output) throws Exception { 
     String input = "D:\\News\\nxis\\Template - change GUID.nxi"; 
     String replaceGuid = guid; 
     String replaceCollection = collection; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     Document document = db.parse(new File(input)); 
     NodeList nodeList = document.getElementsByTagName("n-extract-guid"); 

     NodeList nodeList1 = document.getElementsByTagName("n-extract-request"); 
     for (int x = 0, size = nodeList.getLength(); x < size; x++) 

     { 

      Node docIDValue = (Node) nodeList.item(x).getAttributes().getNamedItem("guid"); 
      String docIDval = docIDValue.getNodeValue(); 
      docIDValue.setNodeValue(docIDval.replaceAll(docIDval, replaceGuid)); 

     } // Collection 
     for (int x1 = 0, size1 = nodeList1.getLength(); x1 < size1; x1++) 

     { 

      Node collectionIDValue = (Node) nodeList1.item(x1).getAttributes().getNamedItem("verifycollection"); 
      String collectionIDval = collectionIDValue.getNodeValue(); 
      collectionIDValue.setNodeValue(collectionIDval.replaceAll(collectionIDval, replaceCollection)); 

     } 
     new File(output).mkdir(); 
     output += replaceGuid + ".nxi"; 
     Transformer xformer = TransformerFactory.newInstance().newTransformer(); 
     xformer.transform(new DOMSource(document), new StreamResult(new File(output))); 
     // System.out.println("Done"); 
    } 

} 

Рабочий как б elow, мы выбираем исходный файл (.xlsx) и пункт назначения (папка) и один раз нажимаем на convert, процесс выполняется. Здесь у меня есть запрос ниже.

  1. Я не хочу устанавливать eclipse во все системы и запускать его, есть способ, которым я могу сделать .exe или какой-либо формат файла, который я могу отправить ему.

Благодаря

+3

Пожалуйста, задайте 1 вопрос вместо 5. Также отправьте только соответствующий код, а не весь проект. – Manu

+0

Я думал, что размещение одного вопроса для 5 одинаковых тем было бы легко для тех, кто просматривает, а размещает 5 разных – user3872094

+0

. Вы работаете с Java, поэтому вы не сделали бы .exe, но вы бы сделали n исполняемый банку. http://www.skylit.com/javamethods/faqs/createjar.html Но вы действительно должны разделить это на несколько вопросов. –

ответ

2

Поскольку вы превратили это в отдельный вопрос, я отвечу здесь. Чтобы создать файл jar, взгляните на это:

Вы работаете с Java, поэтому вы не сделали бы .exe, но вы бы сделали исполняемый банку. (Не привязан к Windows и работает на любом компьютере, на котором установлена ​​виртуальная виртуальная машина Java) http://skylit.com/javamethods/faqs/createjar.html

+1

Создал отдельный вопрос для других, спасибо – user3872094

+0

Добро пожаловать =) –

Смежные вопросы