使用Swing GUI在一个类中执行程序

时间:2015-12-16 16:58:03

标签: java swing

我有一个比较的程序然后合并两个文件并创建一个新文件。我现在尝试使用可以与此程序交互的Swing编程GUI。到目前为止,一切似乎都已到位但是当我尝试运行该程序时,我得到了大量的Swing和awt错误。以下是我试图运行的程序。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package HelloCKL;

import java.util.ArrayList;
import java.io.*;


public class HelloCKL {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        String sourceFile1Path = helloSwingCKL.fileSource;
        String sourceFile2Path = helloSwingCKL.fileToAppend;

        String mergedFilePath = "merged_test2.ckl";

        File[] files = new File[2];
        files[0] = new File(sourceFile1Path);
        files[1] = new File(sourceFile2Path);

        File mergedFile = new File(mergedFilePath);

        mergeFiles(files, mergedFile);
    }


    public static void mergeFiles(File[] files, File mergedFile) {
        // NEW
        ArrayList<String> list = new ArrayList<String>();

        FileWriter fstream = null;
        BufferedWriter out = null;
        try {
            fstream = new FileWriter(mergedFile, false);
            out = new BufferedWriter(fstream);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
        // with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file 
        // we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
        // and set it to false if we already have that in our list. 
        // We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
        Boolean copy = true;
        Boolean tmpCopy = true;
        for (File f : files) {
            System.out.println("merging: " + f.getName());
            FileInputStream fis;
            try {
                fis = new FileInputStream(f);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));

                String aLine;
                while ((aLine = in.readLine()) != null) {
                    // Skip the close checklist and we can write it in at the end
                    if (aLine.trim().equals("</CHECKLIST>")){
                        continue;
                    }
                    if (aLine.trim().equals("<VULN>")){
                        // Store our current value of copy
                        tmpCopy = copy;
                        copy = true;

                        String aLine2 = in.readLine();  
                        String aLine3 = in.readLine();
                        String nameLine = in.readLine();

                        if(list.contains(nameLine.trim())){
                            System.out.println("Skipping: " + nameLine);
                            copy = false;
//                            while (!(aLine.trim().equals("</VULN>"))){
//                                aLine = in.readLine();
//                            }
//                            continue; // this would skip the writing out to file part
                        }
                        else{
                            list.add(nameLine.trim());
                            System.out.println("::: List is now :::" );
                            System.out.println(list.toString());
                        }
                        if(copy){
                            out.write(aLine);
                            out.newLine();
                            out.write(aLine2);
                            out.newLine();
                            out.write(aLine3);
                            out.newLine();
                            out.write(nameLine);
                            out.newLine();
                        }
                    }
                    else{
                        if(copy){
                          out.write(aLine);
                          out.newLine();
                        }
                    }
                    // after we have written to file, if the line was a close vuln, switch copy back to original value
                    if (aLine.trim().equals("</VULN>")){
                        copy = tmpCopy;
                    }
                }

                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            copy = false;
        }

        // Now lets add the close checklist tag we omitted before
        try{
          out.write("</CHECKLIST>");
        } catch (IOException e){
            e.printStackTrace();
        }

        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

这是我正在使用的Swing编码。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hellockl;

import static HelloCKL.HelloCKL.mergeFiles;
import java.io.File;
import javax.swing.JFileChooser;
import java.util.ArrayList;
import java.io.*;


public class helloSwingCKL extends javax.swing.JFrame {

    /**
     * Creates new form helloSwingCKL
     */
    public helloSwingCKL() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(java.awt.Color.lightGray);

        jButton1.setText("Source");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("New .ckl");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTextField3.setText("Save merged file as...");

        jButton3.setText("Merge");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jTextField3)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(5, 5, 5)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jTextField1)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(104, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File source = chooser.getSelectedFile();
        String fileSource = source.getAbsolutePath();
        jTextField1.setText(fileSource);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File toAppend = chooser.getSelectedFile();
        String fileToAppend = toAppend.getAbsolutePath();
        jTextField2.setText(fileToAppend);
    }                                        

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        HelloCKL.mergeFiles();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new helloSwingCKL().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration                   
}

以下是&#34;大量错误&#34; ...

*run:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: hellockl.HelloCKL.main
    at hellockl.helloSwingCKL.jButton3ActionPerformed(helloSwingCKL.java:145)
    at hellockl.helloSwingCKL.access$300(helloSwingCKL.java:18)
    at hellockl.helloSwingCKL$4.actionPerformed(helloSwingCKL.java:73)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6535)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 15 seconds)*

以下是编译器错误。

 Compiling 1 source file to C:\Users\blakey\Documents\NetBeansProjects\helloCKL\build\classes
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:3: error: package HelloCKL does not exist
import static HelloCKL.HelloCKL.mergeFiles;
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:3: error: static import only from classes and interfaces
import static HelloCKL.HelloCKL.mergeFiles;
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:129: error: cannot access HelloCKL
        HelloCKL.main();
  bad source file: C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\HelloCKL.java
    file does not contain class hellockl.HelloCKL
    Please remove or make sure it appears in the correct subdirectory of the sourcepath.
3 errors
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\nbproject\build-impl.xml:952: The following error occurred while executing this line:
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\nbproject\build-impl.xml:269: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)

1 个答案:

答案 0 :(得分:2)

  

当我尝试运行该程序时,我得到了大量的Swing和awt错误

您希望尝试运行不会编译的代码从不这样做 - 在尝试运行程序之前首先修复任何和所有编译错误,如果可以&#39 ;弄清楚如何做到这一点并需要帮助,然后至少在这里用你的问题发布汇编错误,因为&#34;大量错误&#34;并没有告诉我们我们可以合作的事情。

快速查看代码的主要问题是您错误地调用mergeFiles(...)方法。您在不传递任何参数的情况下调用它:

HelloCKL.mergeFiles();

并且它已被编写为需要两个参数:

public static void mergeFiles(File[] files, File mergedFile) {

解决方案:调用方法就像尝试在原始main方法中调用它一样,方法是传入要合并的文件数组和要包含合并的最终结果文件。看起来你有其他代码试图获取这些文件,但似乎没有对它得到的结果做任何事情,而且你应该使用它。