2014-02-08 71 views
0

這是我創建登錄對話框的代碼,但我想在輸入按鍵時自動登錄,但沒有完成此代碼。我試過getRootPane().setDefaultButton(..);但我沒有JButton對象。JOptionPane將默認按鈕設置爲輸入鍵

 String _options = {"ok", "Exit"}; 

     JOptionPane pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, _options, null); 
     JDialog dialog = pane.createDialog("Login"); 
     dialog.setAlwaysOnTop(true); 
     dialog.setVisible(true); 
     dialog.requestFocus(); 
     dialog.toFront(); 

我想設置默認按鈕,但有沒有辦法從JOptionpane獲取JButton對象?

其次,我們可以設置

 JOptionPane pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, _options, _options[0]); //set to _options[0] 

但這裏的問題是將焦點轉移到「確定」按鈕,名字是不是可聚焦?這怎麼解決?

回答

0

您可以創建自己的JDialog並在JPassword字段中添加ActionListener

這是一個簡單的例子。

import java.awt.*; 
import java.awt.event.*; 
import java.util.Arrays; 
import javax.swing.*; 
import javax.swing.border.EmptyBorder; 

public class Password { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       new PasswordDialog(); 
      } 
     }); 
    } 

    static class PasswordDialog extends JDialog { 
     public PasswordDialog() { 
      final JLabel label = new JLabel("Type: stackoverflow"); 
      final JPasswordField field = new JPasswordField(20); 
      final JLabel status = new JLabel(" "); 

      status.setForeground(Color.RED); 

      JPanel panel = new JPanel(new BorderLayout()); 
      panel.setBorder(new EmptyBorder(10, 10, 10, 10)); 
      panel.add(label, BorderLayout.NORTH); 
      panel.add(field, BorderLayout.CENTER); 
      panel.add(status, BorderLayout.SOUTH); 

      field.addActionListener(new ActionListener(){ 
       public void actionPerformed(ActionEvent e) { 
        if (Arrays.equals(field.getPassword(), "stackoverflow".toCharArray())) { 
         JOptionPane.showMessageDialog(PasswordDialog.this, "Correct Password"); 
        } else { 
         status.setText("Invalid Password"); 
        } 
       } 
      }); 

      add(panel); 
      pack(); 
      setLocationRelativeTo(null); 
      setVisible(true); 

      addWindowListener(new WindowAdapter(){ 
       public void windowClosing(WindowEvent e) { 
        System.exit(0); 
       } 
      }); 
     } 
    } 
}