2012-04-09 194 views
0

我是一名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.

有人能帮助我吗?

+1

代码太多。切断噪音。 – nikhil 2012-04-09 03:30:12

+1

只是一个小建议,在这里你说的是将用户名和密码传递给另一个类,而不是这样做,因为这些东西都属于一个实体,比如Student,Visitor,Employee等。你可以用这个名字创建一个新类并将这些证书保存在该类中,然后在需要时调用此类,而不是将这些内容混合在Swing中。 – 2012-04-09 03:46:03

回答

1

最简单的方法就是让name静态以及:

static String name = "JACOB"; 

但是通常情况下,你想在你的会员的方法来创建的路径是不是静态的:

final String path = SAVE_PATH + name; 

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

+0

只需使用完整代码编辑问题即可。你现在可以检查它吗? – user1012181 2012-04-09 03:26:54

+0

另外,变量'name'只是一个例子。其实用户名必须从登录页面,我不知道如何通过! – user1012181 2012-04-09 03:28:29

0

如果您需要设置或更改您的静态变量,你可以创建一个像

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

一个简单的静态方法,并调用它,当你需要,例如

SoundRecording.setGlobalSavePath("JACOB"); 

但要做到这一点,从SAVE_PATH声明中删除final,或者您无法更改其值。