首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >取消获取文件路径,文件名在java中的函数外部

取消获取文件路径,文件名在java中的函数外部
EN

Stack Overflow用户
提问于 2017-11-21 11:40:00
回答 1查看 36关注 0票数 0

好的,我正在为我的大学做一个java项目,在我们学校的课程表系统上。所以我和我的会员合作伙伴一起制作了整个UI。然而,在尝试将它与其他类集成时,我遇到了错误,我需要调用一些可以传递给其他类的值。在我的例子中,我需要导入5个csv文件并将其传递给另一个类。然而,由于一些奇怪的原因,这并没有发生。我试图将所有内容公开,这样我就可以获得值,但即使这样也没有发生任何事情。为了方便起见,我只是对在任何函数内的函数外部显示它感兴趣。如果有人能在那里帮助我,我相信我可以自己把他们叫到其他班级。下面是导入类的代码。请帮帮我:

代码语言:javascript
运行
复制
/*
 * 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.
 */

/**
 *
 * @author SUSMITA SAHA
 */
import java.awt.*;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Screen1 extends javax.swing.JFrame {
    private final JFileChooser openfile;
    public String filename = "";
    public String filename1 = "";
    public String filename2 = "";
    public String filename3 = "";
    public String filename4 = "";

    /**
     * Creates new form Screen
     */
    public Screen1() {
        initComponents();
        getContentPane().setBackground(Color.GREEN);
        openfile = new JFileChooser();
        openfile.setCurrentDirectory(new File("G:\\Java Project\\AcademicTimeTableSystem"));
        openfile.setFileFilter(new FileNameExtensionFilter("CSV files", "csv"));

    }

    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("INPUT SCREEN");

        jLabel2.setText("COURSES");

        jLabel3.setText("INSTRUCTORS");

        jLabel4.setText("ROOMS");

        jLabel5.setText("SECTIONS");

        jLabel6.setText("TIMESLOTS");

        jLabel7.setText("Enter the csv file");

        jLabel8.setText("Enter the csv file");

        jLabel9.setText("Enter the csv file");

        jLabel10.setText("Enter the csv file");

        jLabel11.setText("Enter the csv file");

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

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

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

        jButton4.setText("BROWSE");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("BROWSE");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton6.setText("IMPORT");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(127, 127, 127)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel7)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 853, Short.MAX_VALUE)
                            .addComponent(jButton1))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel8)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel9)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel10)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel11)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton5)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(322, 322, 322)
                        .addComponent(jButton6)))
                .addGap(44, 44, 44))
            .addGroup(layout.createSequentialGroup()
                .addGap(539, 539, 539)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel7)
                    .addComponent(jButton1))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel8)
                    .addComponent(jButton2))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel9)
                    .addComponent(jButton3))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel10)
                    .addComponent(jButton4))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel11)
                    .addComponent(jButton5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
                .addComponent(jButton6)
                .addGap(24, 24, 24))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
         int returnVal = openfile.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            final JFileChooser fc = new JFileChooser();
          // jLabel9.setText(openfile.getSelectedFile().toString());
            jLabel8.setText(openfile.getSelectedFile().toString());
            filename1 = openfile.getSelectedFile().toString();
            System.out.println(filename1);  //here the output is displayed
        }
        else
        {
            jLabel8.setText("Please Choose the file");
        }
        System.out.println(filename1);  //here the output is displayed
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
           int returnVal = openfile.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            final JFileChooser fc = new JFileChooser();
          // jLabel9.setText(openfile.getSelectedFile().toString());
            jLabel11.setText(openfile.getSelectedFile().toString());
            filename4 = openfile.getSelectedFile().toString();
        }
        else
        {
            jLabel11.setText("Please Choose the file");
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int returnVal = openfile.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            final JFileChooser fc = new JFileChooser();
          // jLabel9.setText(openfile.getSelectedFile().toString());
            jLabel7.setText(openfile.getSelectedFile().toString());
            filename = openfile.getSelectedFile().toString();
        }
        else
        {
            jLabel7.setText("Please Choose the file");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
          int returnVal = openfile.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            final JFileChooser fc = new JFileChooser();
          // jLabel9.setText(openfile.getSelectedFile().toString());
            jLabel9.setText(openfile.getSelectedFile().toString());
            filename2 = openfile.getSelectedFile().toString();
        }
        else
        {
            jLabel9.setText("Please Choose the file");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        int returnVal = openfile.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            final JFileChooser fc = new JFileChooser();
          // jLabel9.setText(openfile.getSelectedFile().toString());
            jLabel10.setText(openfile.getSelectedFile().toString());
            filename3 = openfile.getSelectedFile().toString();
        }
        else
        {
            jLabel10.setText("Please Choose the file");
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    int a = 0;

    protected void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { 

        System.out.println(filename1);  //here the output is NOT displayed AT ANY CIRCUMSTANCES
    }
    /**
     * @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(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    // End of variables declaration//GEN-END:variables
}

我还提供了一个驱动器链接,以防更容易

https://drive.google.com/drive/folders/1EQqJTbptZv-cxXev1idwhD1hT369_XTR?usp=sharing

EN

Stack Overflow用户

发布于 2017-11-21 22:58:17

正如我所说的,jButton6现在不执行任何操作,因为没有附加ActionListener。要解决此问题,必须将jButton6ActionPerformed函数与按钮关联:

代码语言:javascript
运行
复制
...
jButton6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButton6.setText("IMPORT");
jButton6.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton6ActionPerformed(evt);
    }
});
...

在对象之间传输数据的标准方法是注入,可以使用构造函数,也可以使用setter。这个类说明了这两种变体。请记住,使用集合来处理统一数据(如文件路径)是很好的。

代码语言:javascript
运行
复制
public class SecondClass {
    private List<String> list;

    public SecondClass() {
    }

    public SecondClass(List<String> list) {
        this.list = list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
}

您可以使用以下代码提交此类中的数据:

代码语言:javascript
运行
复制
protected void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { 
    java.util.List<String> list = new ArrayList<>();
    list.add(filename);
    list.add(filename1);
    list.add(filename2);
    list.add(filename3);
    list.add(filename4);

    // inject with constructor
    SecondClass secondClassA = new SecondClass(list);

    // inject with setter
    SecondClass secondClassB = new SecondClass();
    secondClassB.setList(list);
}

如果你想使用一个已经构造好的对象来提交文件,你可以使用类似这样的东西:

代码语言:javascript
运行
复制
public class SecondClass  implements Consumer<List<String>> {
    private List<String> list;

    @Override
    public void accept(List<String> list) {
        this.list = list;
    }

}

public class Screen1 extends javax.swing.JFrame {

    private Consumer<java.util.List<String>> consumer;

    public void setConsumer(Consumer<java.util.List<String>> consumer) {
        this.consumer = consumer;
    }

    protected void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { 
        java.util.List<String> list = new ArrayList<>();
        list.add(filename);
        list.add(filename1);
        list.add(filename2);
        list.add(filename3);
        list.add(filename4);

        if(consumer != null) {
            consumer.accept(list);
        }
    }

    ....

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SecondClass secondClass = new SecondClass();

                Screen1 screen1 = new Screen1();
                screen1.setConsumer(secondClass);
                screen1.setVisible(true);
            }
        });
    }
}

如果对象彼此不认识,则已知中介者认识它们两个:

代码语言:javascript
运行
复制
public class Mediator implements Consumer<List<String>> {
    private static Mediator INSTANCE;

    private final List<Consumer<List<String>>> consumers = new ArrayList<>();

    private Mediator() {
    }

    public static Mediator getInstance() {
        if(INSTANCE == null) {
            INSTANCE = new Mediator();
        }

        return INSTANCE;
    }

    public void register(Consumer<List<String>> consumer) {
        consumers.add(consumer);
    }

    public void unregister(Consumer<List<String>> consumer) {
        consumers.remove(consumer);
    }

    @Override
    public void accept(List<String> list) {
        consumers.stream().forEach(c -> c.accept(list));
    }
}

因此,所有想要从中介器接收消息的对象都会被注册。

代码语言:javascript
运行
复制
public class SecondClass  implements Consumer<List<String>> {
    private List<String> list;

    public SecondClass() {
        Mediator.getInstance().register(this);
    }

    @Override
    public void accept(List<String> list) {
        this.list = list;
    }
}

而那些发送消息的人将消息发送给中介者:

代码语言:javascript
运行
复制
public class Screen1 extends javax.swing.JFrame {

    protected void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { 
        java.util.List<String> list = new ArrayList<>();
        list.add(filename);
        list.add(filename1);
        list.add(filename2);
        list.add(filename3);
        list.add(filename4);

        Mediator.getInstance().accept(list);
    }

    ....

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SecondClass secondClass = new SecondClass();

                Screen1 screen1 = new Screen1();
                screen1.setVisible(true);
            }
        });
    }
}
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47404783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档