2012-05-27 12 views
12

netbeans kullanılarak yapılır başvurum yükler, ilk JTextField otomatik odaklandığında, ve bu JTextField içinde, ben kullanıcı bu tıkladığında, bu gidecek "adınızı girin" yazdım uygulama yüklendiğinde alan ancak, bu alan, odaklanmıştır ben, nasıl başlangıçta bunu unfocus "adınızı girin" göremiyorum demektir?bir JTextField odaklamayın nasıl

+0

Orada 2 JTextFields, ilk kullanıcı adı için, şifre ikinci ve bir JMenuItem denilen Günlüğü (sadece bir odaklanabilir bileşeni :) ile bir GUI test değil)

, ben uygulamayı çalıştırmak an, ilk JTextField odaklanmıştır, ben istemiyorum –

+0

BTW - her bir uygulama için kullanıcı adı eğer. Kurulum * Beklenecek * Beklenecek *, sadece kullanıcı adı alanını varsayılan olarak doldurun ve eğer doğruysa kullanıcı sekmesini bir sonraki alana bırakın. Sabit * garantili * ise, alanı doldurun ve devre dışı bırakın. ** ** odaklanabilir olmayacak ve odak varsayılan olarak 2. alana gidecektir. –

cevap

14

bir log-in en iyi kalıcı bir iletişim kutusunda yapılan, ancak o sorunları tanıtır olacağını bileşen görünür sonra çağrılmalıdır, ama bu engellendi requestFocusInWindow() yöntem aslında iletişim kiplidir!

Bu örnekte, iletişim kutusunun görünürlüğünden sonra odağı yönetmek için Rob Camick'in RequestFocusListener (Dialog Focus'da sunulduğu gibi) kullanılır.

Login with focused password field

Not: kullanıcı herhangi bir şey yapmadan önce nasıl göründüğünü olduğunu. Şifre alanı varsayılan olarak odaklanmıştır.

package test.t100.t001; 

import java.awt.BorderLayout; 
import java.awt.GridLayout; 

import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 
import javax.swing.SwingConstants; 
import javax.swing.SwingUtilities; 
import javax.swing.event.AncestorEvent; 
import javax.swing.event.AncestorListener; 

public class LoginRequired { 

    LoginRequired() { 
     JFrame f = new JFrame("Login Required"); 
     f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     f.setSize(400, 300); 
     f.setResizable(false); 
     f.setLocationByPlatform(true); 
     f.setVisible(true); 

     showLogin(f); 
    } 

    private void showLogin(JFrame frame) { 
     JPanel p = new JPanel(new BorderLayout(5,5)); 

     JPanel labels = new JPanel(new GridLayout(0,1,2,2)); 
     labels.add(new JLabel("User Name", SwingConstants.RIGHT)); 
     labels.add(new JLabel("Password", SwingConstants.RIGHT)); 
     p.add(labels, BorderLayout.WEST); 

     JPanel controls = new JPanel(new GridLayout(0,1,2,2)); 
     JTextField username = new JTextField("Joe Blogs"); 
     controls.add(username); 
     JPasswordField password = new JPasswordField(); 
     password.addAncestorListener(new RequestFocusListener(false)); 
     controls.add(password); 
     p.add(controls, BorderLayout.CENTER); 

     //LayoutManager l = new GroupLayout(p); 
     //p.setLayout(l); 
     JOptionPane.showMessageDialog(
      frame, p, "Log In", JOptionPane.QUESTION_MESSAGE); 
    } 

    /** 
    * @param args none 
    */ 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       new LoginRequired(); 
      } 
     }); 
    } 

} 

/** 
* Convenience class to request focus on a component. 
* 
* When the component is added to a realized Window then component will 
* request focus immediately, since the ancestorAdded event is fired 
* immediately. 
* 
* When the component is added to a non realized Window, then the focus 
* request will be made once the window is realized, since the 
* ancestorAdded event will not be fired until then. 
* 
* Using the default constructor will cause the listener to be removed 
* from the component once the AncestorEvent is generated. A second constructor 
* allows you to specify a boolean value of false to prevent the 
* AncestorListener from being removed when the event is generated. This will 
* allow you to reuse the listener each time the event is generated. 
*/ 
class RequestFocusListener implements AncestorListener 
{ 
    private boolean removeListener; 

    /* 
    * Convenience constructor. The listener is only used once and then it is 
    * removed from the component. 
    */ 
    public RequestFocusListener() 
    { 
     this(true); 
    } 

    /* 
    * Constructor that controls whether this listen can be used once or 
    * multiple times. 
    * 
    * @param removeListener when true this listener is only invoked once 
    *      otherwise it can be invoked multiple times. 
    */ 
    public RequestFocusListener(boolean removeListener) 
    { 
     this.removeListener = removeListener; 
    } 

    @Override 
    public void ancestorAdded(AncestorEvent e) 
    { 
     JComponent component = e.getComponent(); 
     component.requestFocusInWindow(); 

     if (removeListener) 
      component.removeAncestorListener(this); 
    } 

    @Override 
    public void ancestorMoved(AncestorEvent e) {} 

    @Override 
    public void ancestorRemoved(AncestorEvent e) {} 
} 
+0

hmmm benim kelimelerim de +1 – mKorbel

+0

@AloneInTheDark Bu, ayrı bir soru sorulması gereken ayrı bir sorudur. soru. –

4

Kullanım requestFocusInWindow() ziyade başka bir bileşen üzerinde JTextfield ilk odaklamayı ayarlamak için.

Ama yerli odak sistemi, daha doğrusu setText(String s)JTextFieldconstructor yılında initComponents() çağrısından sonra (netbeans içinde olduğu varsayılır) üzerinde değiştirmek için değil öneririm.

Başka isteğe bağlı okuma: How to Use the Focus Subsystem

+0

Ne login için bir JMenuItem tıkla olsaydı?RequestFocusInWindow() 'ı başka bir öğede kullandım, fakat o JMenuItem'i tıklattığım anda, JTextField odaklanır, ikinci jeneratörü tıkladığımda, JTextField odaklanmaz, daha sonra çalışır, ancak ilk kez –

+0

deniyor musunuz? 'JMenuItem' için NetBeans özellik editörü' nextFocusableComponent' özelliği? – Asif

+0

Sabitledim, açılışta iki kez ur kodu kullandım ve Jmenuitem'e tıkladığımda teşekkürler –

3

Kullanıcı adı alanına klavye odağı vermenin, kullanıcının önce yapması gereken şey olduğunu varsayarak, doğru davranış olduğunu düşünüyorum. Bunun yerine odaklama, neden olmasın net sadece

import java.awt.*; 
import javax.swing.*; 
import javax.swing.text.Document; 

public class PlaceholderTextField extends JTextField { 

    public static void main(final String[] args) { 
     final PlaceholderTextField tf = new PlaceholderTextField(""); 
     tf.setColumns(20); 
     tf.setPlaceholder("All your base are belong to us!"); 
     final Font f = tf.getFont(); 
     tf.setFont(new Font(f.getName(), f.getStyle(), 30)); 
     JOptionPane.showMessageDialog(null, tf); 
    } 

    private String placeholder; 

    public PlaceholderTextField() { 
    } 

    public PlaceholderTextField(
     final Document pDoc, 
     final String pText, 
     final int pColumns) 
    { 
     super(pDoc, pText, pColumns); 
    } 

    public PlaceholderTextField(final int pColumns) { 
     super(pColumns); 
    } 

    public PlaceholderTextField(final String pText) { 
     super(pText); 
    } 

    public PlaceholderTextField(final String pText, final int pColumns) { 
     super(pText, pColumns); 
    } 

    public String getPlaceholder() { 
     return placeholder; 
    } 

    @Override 
    protected void paintComponent(final Graphics pG) { 
     super.paintComponent(pG); 

     if (placeholder.length() == 0 || getText().length() > 0) { 
      return; 
     } 

     final Graphics2D g = (Graphics2D) pG; 
     g.setRenderingHint(
      RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 
     g.setColor(getDisabledTextColor()); 
     g.drawString(placeholder, getInsets().left, pG.getFontMetrics() 
      .getMaxAscent() + getInsets().top); 
    } 

    public void setPlaceholder(final String s) { 
     placeholder = s; 
    } 

} 

Eğer gerçekten sadece odağı kaldırmak isterseniz ?: kullanıcı türleri şeyin peşine üzerine temizleyerek nedeniyle, bazı seçenekleri:

  • component.setFocusable(false);
  • KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
  • KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
3
textField.setFocusable(false); 
textField.setFocusable(true); 

ise textField odağı vardı ve sadece, eğer TAB dereceden sırayla sonraki bileşeni otomatik odak alacak. Efekt, bir TAB presiyle aynıdır.

İlgili konular