为什么我的JFileChooser没有存储其余代码的结果?

时间:2015-01-08 16:40:38

标签: java swing

在Java中,我尝试设置JFileChooser来选择文件,然后存储文件名以便在stringbuilder中使用。所以,假设我有这样的代码

    try
    {
        //Basic game launching command.
        StringBuilder sb = new StringBuilder("cmd.exe /C start C:\\mygame\\game.exe");
        }
        for(File f : CustomContent.getSelectedFiles()){
            sb.append(" -file ").append(f.getName());

        }
        Process process = Runtime.getRuntime().exec(sb.toString());
    }

在另一部分我有这个,对于一个名为" CustomContent"

的jButton
  private void CustomContentActionPerformed(java.awt.event.ActionEvent evt) {                                              
    final JFileChooser CustomContent = new JFileChooser();
    CustomContent.setMultiSelectionEnabled(true);
    int returnVal = CustomContent.showOpenDialog(CustomContent);
    String file = CustomContent.getSelectedFile().toString();

为什么它不起作用?我做错了什么?

编辑:这是一个最小的示例程序。我想我已经包括了一切。它来自netbeans,所以我不是100%肯定。 如果我遗漏了任何东西,请告诉我。

/*
 * 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 javaapplication5;

import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;

/**
 *
 * @author Loismustdie555
 */
public class NewJPanel extends javax.swing.JPanel {

    /**
     * Creates new form NewJPanel
     */
    public NewJPanel() {
        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() {

        CustomContentButton = new javax.swing.JButton();
        RunGameButton = new javax.swing.JButton();

        CustomContentButton.setText("Files");
        CustomContentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CustomContentButtonActionPerformed(evt);
            }
        });

        RunGameButton.setText("Run");
        RunGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RunGameButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(CustomContentButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RunGameButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CustomContentButton)
                    .addComponent(RunGameButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void RunGameButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        try
        {
            //Basic game launching command.
            StringBuilder sb = new StringBuilder("cmd.exe /C start C:\\mygame\\game.exe");
            for(File f : CustomContentButton.getSelectedFiles()){
                sb.append(" -file ").append(f.getName());

            }

            //Launch the game
            Process process = Runtime.getRuntime().exec(sb.toString());
        }
        catch(IOException e)
        {
            //Log Error
        }
    }                                             

    private void CustomContentButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        final JFileChooser CustomContentResults = new JFileChooser();
        CustomContentResults.setMultiSelectionEnabled(true);
        int returnVal = CustomContentResults.showOpenDialog(CustomContentResults);
        String file = CustomContentResults.getSelectedFile().toString();
    }                                                   


    // Variables declaration - do not modify                     
    private javax.swing.JButton CustomContentButton;
    private javax.swing.JButton RunGameButton;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

我在目前为止发布的代码中看到的唯一问题(除了你没有遵循Java命名约定)是你要声明你的CustomContent变量(应该命名为“customContent”)在本地,建议您在声明它时使用的任何CustomContent对象与尝试从中提取数据的对象不同。


修改
关于你的新代码,你在CustomContentButton上调用getSelectedFiles(),一个JButton(??)。这当然行不通。


编辑2
你的整个程序设置看起来很像。您应该在用户使用JFileChooser之后立即从JFileChooser获取文件,因此可能在ActionListener中使JFileChooser可见 - 获取该侦听器底部的信息,将信息存储在字段中,然后您可以在你的课堂上使用它。

请学习并使用Java naming conventions。变量名都应以较低的字母开头,而类名以大写字母开头。

遵循这些建议以及遵循良好的代码格式化实践将允许其他人(例如我们!)更好地理解您的代码,更重要的是,将允许您未来的自我更好地理解您在6个月前的想法你写了代码。


编辑3
例如:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.*;

@SuppressWarnings("serial")
public class NewJPanel2 extends JPanel {
   private File[] selectedFiles = null;

   // Actions that are used by my buttons
   private RunAction runAction = new RunAction("Run");
   private FileAction fileAction = new FileAction("Files");

   public NewJPanel2() {
      setLayout(new GridLayout(1, 0, 5, 5));
      setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

      // create my buttons using the actions
      add(new JButton(fileAction));
      add(new JButton(runAction));
   }

   // my run action
   private class RunAction extends AbstractAction {
      public RunAction(String name) {
         super(name);  // give button its name text
         int mnemonic = (int) name.charAt(0);  
         putValue(MNEMONIC_KEY, mnemonic); // alt-key mnemonic
         setEnabled(false); // disable this action at start
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // TODO use selectedFiles to launch new program

         // just to show that the files are accessable
         for (File file : selectedFiles) {
            System.out.println(file);
         }
      }
   }

   private class FileAction extends AbstractAction {

      public FileAction(String name) {
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         final JFileChooser customContentResults = new JFileChooser();
         customContentResults.setMultiSelectionEnabled(true);
         int returnVal = customContentResults.showOpenDialog(customContentResults);
         if (returnVal == JFileChooser.APPROVE_OPTION) {
            selectedFiles = customContentResults.getSelectedFiles();
            if (selectedFiles != null && selectedFiles.length > 0) {

               // only enable runAction if Files have been selected
               runAction.setEnabled(true);
            }
         }
      }
   }

   private static void createAndShowGui() {
      NewJPanel2 mainPanel = new NewJPanel2();

      JFrame frame = new JFrame("NewJPanel2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}