有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的JFileChooser在剩下的代码中不存储它的结果?

在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) 个答案

  1. # 1 楼答案

    到目前为止,我在您发布的代码中看到的唯一问题(除了您没有遵循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();
             }
          });
       }
    }