有 Java 编程相关的问题?

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

java如何处理静态final变量

我是Java初学者,我对static final变量有一些问题。我有一个登录页面,可以从中获取当前登录用户的用户名

Login Page Code

import javax.swing.*;

public class ProfileLogin extends JFrame {

    public ProfileLogin() {
        initComponents();
    }

    private void initComponents() {

        jPanel1 = new JPanel();
        proName = new JTextField();
        jButton2 = new JButton();
        jLabel2 = new JLabel();
        jPanel2 = new JPanel();
        logName = new JTextField();
        jButton1 = new JButton();
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sound Recognition System");
        setResizable(false);

        jPanel1.setBorder(BorderFactory.createTitledBorder("Create Profile"));

        jButton2.setText("Create New");
        jButton2.setToolTipText("Click to create a new profile");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Choose a Profile Name:");

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(proName, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jButton2, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(proName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
                .addGap(16, 16, 16))
        );

        jPanel2.setBorder(BorderFactory.createTitledBorder("Select Profile"));

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

        jLabel1.setText("Enter your Profile Name:");

        GroupLayout jPanel2Layout = new GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(logName, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                    .addComponent(jButton1, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(logName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(23, 23, 23))
        );

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-195)/2, (screenSize.height-294)/2, 195, 294);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String profileName;
        String empty;
        empty = "";
        profileName = proName.getText();

        try {
            if(profileName.equalsIgnoreCase("")) {
              JOptionPane.showMessageDialog(null, "Please Enter a Profile Name!");
              return;
            }

           database.rs = database.st.executeQuery("select pname from login where pname='"+profileName+"'");

           if(database.rs.next()) {
               JOptionPane.showMessageDialog(null, "Username Already Existing!");
               return;
           }


            database.st.executeUpdate("insert into login(pname) values('"+profileName+"')");
            JOptionPane.showMessageDialog(null, "Profile successfully created!");
            proName.setText(empty);;

        }
        catch(Exception e)
        {}





    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String loginName=logName.getText().trim();
            if(loginName.equalsIgnoreCase(""))
            {
              JOptionPane.showMessageDialog(null, "Please Enter Profile Name!");
              return;
            }
            database.rs = database.st.executeQuery("select pname from login where pname='"+loginName+"'");
            if (database.rs.next()) {
                Account a = new Account();
                a.setVisible(true);
                this.dispose();   
            }
            else
            {
                JOptionPane.showMessageDialog(null, "No such username!");
            }

        } catch (Exception e) {

            System.out.println(e);
            e.printStackTrace();

        }



    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new ProfileLogin().setVisible(true);
            }
        });
    }

    private JButton jButton1;
    private JButton jButton2;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JTextField logName;
    private JTextField proName;
    private DatabaseConnection database = new DatabaseConnection();
}

现在我有了一个java页面,我需要将用户名从登录页面嵌入到静态最终变量中。但我不知道如何从登录页面传递变量,并将值嵌入到静态最终变量中

import javax.sound.sampled.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SoundRecording extends JDialog {
        String name="JACOB";
    public static final String SAVE_PATH = "./data/recordings/"+name;

    private JLabel operationLabel;
    private JPanel recordPanel;
    private JButton applyButton;
    private JButton cancelButton;
    private JComboBox operationList;
    private JButton playButton;
    private JButton recordButton;
    private JButton stopButton;
    private JSeparator separator;
    private AudioVisualizer visualizer;

    private AudioInputStream audioStream;
    private SourceDataLine sourceLine;
    private AudioFormat audioFormat;
    private TargetDataLine line;
    private ByteArrayOutputStream output;

    public SoundRecording(JFrame parent) {
        super(parent, "Record", true);

        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        recordPanel = new JPanel();
        recordButton = new JButton();
        stopButton = new JButton();
        playButton = new JButton();
        operationLabel = new JLabel("Select Operation:");
        operationList = new JComboBox();
        applyButton = new JButton();
        cancelButton = new JButton();
        separator = new JSeparator();
        visualizer = new AudioVisualizer();

        recordPanel.setBorder(BorderFactory.createTitledBorder("Options"));

        recordButton.setText("Record");
        recordButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                recordButtonActionPerformed(evt);
            }
        });

        stopButton.setText("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        playButton.setText("Play");
        playButton.setEnabled(false);
        playButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                playButtonActionPerformed(evt);
            }
        });

        operationList.setModel(new DefaultComboBoxModel(new String[] { "Shutdown", "Sleep", "Close", "Minimize" }));

        applyButton.setText("Apply");
        applyButton.setEnabled(false);
        applyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                applyButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        GroupLayout recordPanelLayout = new GroupLayout(recordPanel);
        recordPanel.setLayout(recordPanelLayout);
        recordPanelLayout.setHorizontalGroup(
            recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(recordPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(operationList, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addComponent(separator, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addComponent(visualizer, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
                    .addGroup(recordPanelLayout.createSequentialGroup()
                        .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(operationLabel, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE)
                            .addGroup(recordPanelLayout.createSequentialGroup()
                                .addComponent(recordButton)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(stopButton, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE))
                    .addComponent(playButton, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)))))
        );
        recordPanelLayout.setVerticalGroup(
            recordPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(recordPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(operationLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(operationList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(separator, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(visualizer, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(recordPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(recordButton)
                    .addComponent(stopButton, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(playButton)
                .addContainerGap(10, Short.MAX_VALUE))
        );

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(applyButton)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addGap(0, 8, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(recordPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(recordPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(applyButton)
                    .addComponent(cancelButton))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(215, 299);
        setResizable(false);

        /*
         * This is used to position the frame into
         * the center of the screen.
         */
        setLocationRelativeTo(null);
    }

    private void recordButtonActionPerformed(ActionEvent evt) {
        recordButton.setEnabled(false);
        stopButton.setEnabled(true);
        playButton.setEnabled(false);       
        applyButton.setEnabled(true);

        /*
         * Construct the data line from the microphone using
         * the custom audio format.
         */
        try {
            audioFormat = Microphone.getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
            line = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
        } catch(Exception ex) {
            ex.printStackTrace();
        }

        /*
         * Create a thread to capture the microphone data
         * into an audio file and start the thread running.
         */
        CaptureThread capture = new CaptureThread();
        capture.start();
    }

    private void stopButtonActionPerformed(ActionEvent evt) {
        stopButton.setEnabled(false);
        recordButton.setEnabled(true);
        playButton.setEnabled(true);

        line.stop();
        line.close();
    }

    private void playButtonActionPerformed(ActionEvent evt) {
        playButton.setEnabled(false);

        PlaybackThread playback = new PlaybackThread();
        playback.start();
    }

    private void applyButtonActionPerformed(ActionEvent evt) {
        /*
         * Set the file type and the file extension.
         */
        String operation = operationList.getSelectedItem().toString();
        File audioFile = new File(SAVE_PATH + operation + ".wav");

        /*
         * Display the confirmation dialog.
         */
        if(audioFile.exists()) {
            Toolkit.getDefaultToolkit().beep();

            Object[] options = {"Yes", "No",};
            int returnValue = JOptionPane.showOptionDialog(this,
                "This recording already exists, do you want to overwrite?", "Overwrite",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[1]);

            if(returnValue == JOptionPane.NO_OPTION) {
                return;
            }
        }

        /*
         * Write the stored buffer bytes into the
         * saved audio file.
         */
        byte[] audioData = output.toByteArray();
        ByteArrayInputStream stream = new ByteArrayInputStream(audioData);
        try {
            AudioInputStream audioStream = new AudioInputStream(stream, audioFormat, audioData.length);
            AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, audioFile);
        } catch(IOException ex) {
            ex.printStackTrace();
        }

        this.dispose();
    }

    private void cancelButtonActionPerformed(ActionEvent evt) { 
        this.dispose();
    }

    /*
     * Inner class to capture data from microphone and
     * write it to an output audio file.
     */
    class CaptureThread extends Thread implements Runnable {

        @Override
        public void run() {
            /*
             * Start writing audio data into the data line.
             */
            try {
                /*
                 * Close the current running line while we
                 * listen for input on a new line.
                 */
                Microphone.getLine().stop();
                Microphone.getLine().close();

                /*
                 * Open the new line for recording
                 * sound clips.
                 */
                line.open(audioFormat);
                line.start();

                /*
                 * Start the drawing of the visualizer.
                 */             
                visualizer.start();

                /*
                 * Create a buffer which the data can be stored in
                 * and listen for input data.
                 */
                output = new ByteArrayOutputStream();
                while(true) {
                    if(!line.isOpen()) {                    
                        break;
                    }

                    /*
                     * Get the total about of bytes which
                     * are available on the line.
                     */
                    int available = line.available();

                    /*
                     * Make sure something is pending on
                     * the line before trying to read.
                     */
                    if(available > 0) {
                        byte[] buffer = new byte[available];
                        int read = line.read(buffer, 0, buffer.length);

                        if(read > 0) {
                            output.write(buffer, 0, buffer.length);
                        }

                        /*
                         * Set the chunk of data into the
                         * visualizer.
                         */
                        visualizer.setData(buffer);
                    }
                }

                /*
                 * Close the ouput buffer.
                 */
                output.close();

                /*
                 * Stop the drawing of the visualizer.
                 */
                visualizer.stop();

                /*
                 * Re-open the line and start it running
                 * again.
                 */
                Microphone.getLine().open(audioFormat);
                Microphone.getLine().start();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /*
     * This class is used for playing back audio which is
     * saved into a buffer. This feeds the audio into the
     * output speaker line.
     */
    class PlaybackThread extends Thread implements Runnable {

        @Override
        public void run() {
            byte[] audioData = output.toByteArray();
            ByteArrayInputStream stream = new ByteArrayInputStream(audioData);

            /*
             * Get the data line to the output speakers.
             */
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            try {
                sourceLine = (SourceDataLine) AudioSystem.getLine(info);
                sourceLine.open(audioFormat);
            } catch(Exception ex) {
                ex.printStackTrace();
            }

            /*
             * Start the audio output line.
             */
            sourceLine.start();

            /*
             * Write the data into the audio stream.
             */
            int read = 0;
            byte[] data = new byte[stream.available()];
            while(read != -1) {
                try {
                    read = stream.read(data, 0, data.length);
                } catch(Exception e) {
                    e.printStackTrace();
                }

                if(read > 0) {
                    @SuppressWarnings("unused")
                    int written = sourceLine.write(data, 0, read);
                }
            }

            /*
             * Flush any unused bytes from the stream and
             * close the audio line to the speakers.
             */
            sourceLine.drain();
            sourceLine.close();

            /*
             * Re-enable the play button, allowing the user to
             * play the clip again.
             */
            playButton.setEnabled(true);
        }
    }
}

必须将用户名添加到静态最终变量SAVE_PATH中,使其成为 "./data/recordings/username"

我已经尝试将一个示例用户名直接添加到此中,如下所示

String name="JACOB";
public static final String SAVE_PATH = "./data/recordings/"+name;

But it says Non-static variable name cannot be referenced from a static context.

有人能帮我吗


共 (2) 个答案

  1. # 1 楼答案

    如果需要设置或更改静态变量,可以创建一个简单的静态方法,如

    public static void setGlobalSavePath(String name) {
      SoundRecording.SAVE_PATH = "./data/recordings/" + name;
    }
    

    比如说,当你需要的时候就给它打电话

    SoundRecording.setGlobalSavePath("JACOB");
    

    但要执行此操作,请从SAVE_PATH声明中删除final,否则无法更改其值

  2. # 2 楼答案

    最简单的方法是使name也是静态的:

    static String name = "JACOB";
    

    但通常,您希望在成员方法中创建非静态的路径:

    final String path = SAVE_PATH + name;
    

    因为我看不出您是如何使用name变量的,所以我无法真正告诉您在您的情况下正确的方法是什么