2017-02-27 216 views
-1

我正在嘗試爲GUI創建示例,它取自用戶在JTextFiled中的名稱,併爲用戶輸入其在JtextField中輸入的名稱的消息,現在我想使用方法檢查用戶是否輸入按鈕沒有輸入任何東西,我試圖在ActionListener中使用此方法,但我看到編輯器中的錯誤,而當我在ActionListener外部使用它時,我發現它是行得通的!請參閱附件圖片檢查JTextField是否爲空

public class Example01 extends JFrame { 

public JTextField text; 
public Example01() { 
    setTitle("Example 01"); 
    JPanel panel = new JPanel(); 
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); 
    panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50)); 
    JLabel label = new JLabel("Enter Your Name : "); 
    text = new JTextField(); 
    text.setSize(30, 10); 
    JButton btn1 = new JButton("Enter"); 

    btn1.addActionListener(new ActionListener() { 

    if (text.getText().equals("")) { 
     JOptionPane.showMessageDialog(rootPane, "Please enter anything"); 
    } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText()); 
     } 
    }); 
    panel.add(label); 
    panel.add(Box.createRigidArea(new Dimension(0, 20))); 
    panel.add(text); 
    panel.add(Box.createRigidArea(new Dimension(0, 20))); 
    panel.add(btn1); 

    add(panel); 
    setVisible(true); 
    pack(); 
    setLocationRelativeTo(null); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
} 

} error message

+0

此鏈接可能幫助http://stackoverflow.com/questions/17132452/java-check-if-jtext field-is-empty-or-not – SomeStudent

+0

您試圖在可執行上下文之外執行代碼,即,方法 – MadProgrammer

+0

我看到這個,但我不明白addDocumentListener究竟做了什麼,我試圖添加一些編輯代碼爲我的Jtextfield我看到多個錯誤 – MML

回答

4

以...

if (text.getText().equals("")) { 
    JOptionPane.showMessageDialog(rootPane, "Please enter anything"); 
} 

,並把它放在你actionPerformed方法裏面......

btn1.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (text.getText().equals("")) { 
      JOptionPane.showMessageDialog(rootPane, "Please enter anything"); 
     } 
     JOptionPane.showMessageDialog(rootPane, "Hello : " + text.getText()); 
    } 
}); 
+0

感謝MadProgrammer其工作正常! – MML