2012-08-13 47 views
2

對於如何編程,我有點困惑。我有一個類擴展JFrame與兩個文本框。我希望能夠從JFrame獲得輸入。不知何故,只是等待我的mainMaybe類的輸入...任何想法?從JFrame獲取輸入

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JTextField; 


public class mainMaybe extends JFrame{ 
    JTextField login; 
    JTextField pass; 

    public mainMaybe() throws InterruptedException{ 
     login = new JTextField(); 
     pass = new JTextField(); 
     pass.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent arg0) { 
       System.out.println("DO SOMETHING"); 
      }  
     }); 
     add(login,BorderLayout.NORTH); 
     add(pass,BorderLayout.SOUTH); 
     pack(); 
     setVisible(true); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public void returnEmail(){ 
     //SOME HOW WAIT FOR THE ACTION LISTENER? 
    } 

    public static void main(String[] args) throws InterruptedException { 
     new mainMaybe().returnEmail(); 
     //CONTROL SHOULD STAY WITH mainMaybe until an email is returned   
    } 

} 

回答

8

Java Swing基於event-driven architecture的概念。因此,事件觸發行爲並基於這些事件執行某種操作。

Using Swing Component將是一個很好的點開始理解,並因此實現你想實現你的UI和它的相應行爲。所以我建議你稍微閱讀一下,然後嘗試解決你想要達到的目標。

我不太確定你想要達到的目標,但如果我是你,我會有兩個文本字段,也許有一些標籤附加到它和一個「提交」按鈕。我會添加一個ActionListener到這個按鈕來執行某種操作。

也許SSCCE可能會幫助您開始。所以,看看下面的代碼:

package com.test; 

import javax.swing.JOptionPane; 

public class SimpleUI extends javax.swing.JFrame { 

    /** 
    * Creates new form SimpleUI 
    */ 
    public SimpleUI() { 
     initComponents(); 
    } 

    private void initComponents() { 

     mainPanel = new javax.swing.JPanel(); 
     labelName = new javax.swing.JLabel(); 
     textName = new javax.swing.JTextField(); 
     jLabel1 = new javax.swing.JLabel(); 
     textPassword = new javax.swing.JPasswordField(); 
     jButton1 = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     mainPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2)); 

     labelName.setText("Name: "); 

     jLabel1.setText("Password: "); 

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

     javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); 
     mainPanel.setLayout(mainPanelLayout); 
     mainPanelLayout.setHorizontalGroup(
      mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(mainPanelLayout.createSequentialGroup() 
       .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(labelName) 
        .addComponent(jLabel1)) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) 
        .addComponent(textName) 
        .addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)) 
       .addGap(18, 18, 18) 
       .addComponent(jButton1) 
       .addGap(0, 65, Short.MAX_VALUE)) 
     ); 
     mainPanelLayout.setVerticalGroup(
      mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(mainPanelLayout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(labelName) 
        .addComponent(textName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(jLabel1) 
        .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addComponent(jButton1)) 
       .addContainerGap(15, Short.MAX_VALUE)) 
     ); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
     ); 

     pack(); 
    } 


    /** 
    * This is the method that is called when an action is performed. 
    * Over here I just simply show an error message if any of the text fields are empty or just show their names. 
    */ 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
     String name   = textName.getText(); 
     String password  = String.valueOf(textPassword.getPassword()); 

     if("".equals(password) || "".equals(name)){ 
      JOptionPane.showMessageDialog(this, "Name or password is empty!", "Incorrect Input", JOptionPane.ERROR_MESSAGE); 
     }else{ 
      JOptionPane.showMessageDialog(this, "Hello "+name+" with password "+password, "Incorrect Input", JOptionPane.PLAIN_MESSAGE); 
     } 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) { 

     try { 
      javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(SimpleUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 


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

    private javax.swing.JButton jButton1; 
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JLabel labelName; 
    private javax.swing.JPanel mainPanel; 
    private javax.swing.JTextField textName; 
    private javax.swing.JPasswordField textPassword; 

} 

注意:我生成使用NetBeans IDE的代碼,所以我沒有處理很多關於佈局或任何東西。如果您想了解佈局,這裏是一個有趣的教程:"A Visual Guide to Layout Managers"

主要的想法對我來說是向您展示事件是如何引發的。所以我做的是我在我的「提交」按鈕中添加了一個actionlistener,當有人點擊按鈕時,我執行某種操作。希望你得到的照片。

+1

+1理解的問題(和一個不錯的答案) – MadProgrammer 2012-08-13 04:00:56

+0

@MadProgrammer - 謝謝! :) – Sujay 2012-08-13 04:04:46

+0

好的,在事件被觸發之後......我如何告訴我的「主」,以及如何告訴這個主要等待事件被觸發? – user1000232 2012-08-13 04:09:24

4

我認爲你的設計方法錯了。在Java GUI(以及大多數類似的技術)中,您不會說「等待電子郵件地址」,而是說「當您收到電子郵件地址時告訴我」。

您在將文本框添加偵聽程序的過程中會遇到一些問題 - 基本上,您希望偵聽程序在texbox中的值發生更改時「觸發」。聽衆的實現會做一些事情 - 例如,將電子郵件地址寫入CONSOL然後退出。

+0

+1理解的問題(和一個不錯的答案) – MadProgrammer 2012-08-13 04:01:36

3

替代方法,使用模態對話框(或更確切地說,其中兩個)。

import javax.swing.*; 

public class LoginPrompt { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       String username = JOptionPane.showInputDialog(null, "User Name"); 
       System.out.println("Username: " + username); 

       JPasswordField passwordField = new JPasswordField(8); 
       // a bit quirky, we need to tab to the field 
       JOptionPane.showMessageDialog(null, passwordField, "Password", 
         JOptionPane.QUESTION_MESSAGE); 
       char[] password = null; 
       password = passwordField.getPassword(); 
       System.out.println("Password: " + String.valueOf(password)); 
      } 
     }); 
    } 
} 
+1

我喜歡這個解決方案。它非常不同而且很短。但出於某種原因,我不喜歡用多個對話框來錯誤地使用我的用戶。我知道這是個人喜好的問題,但我不知何故會讓我的用戶通過一個簡單的用戶界面,而不是將多個對話框扔在他身上。你怎麼看待這件事? – Sujay 2012-08-13 04:29:53

+0

@Sujay *「不喜歡使用多個對話框來bug我的用戶」*完全同意。只是想顯示兩種不同類型的輸入對話框。我喜歡第一個的簡單性,但第二個更加開放地顯示這兩個領域(它可以採用一個面板)。順便說一下,你的答案是最好的。完全應得的'剔'。 :) – 2012-08-13 04:41:39

+0

@AndrewThomson - 謝謝!我只是想知道別人的想法有關使用對話框:) – Sujay 2012-08-13 04:48:31