2013-01-02 35 views
7

我有一個JLabel,當你點擊它時,它被替換爲JTextField,我需要JTextField來自動選擇它的所有文本。強制JTextField在其出現時選擇其所有內容

感謝allot的幫助。

+0

是你在找什麼? http://stackoverflow.com/questions/1178312/how-to-select-all-text-in-a-jformattedtextfield-when-it-gets-focus/1178596#1178596 – SomeJavaGuy

+0

我試過這兩個問題之前,我問這個問題,這個答案的問題是它沒有工作。此答案的另一個問題是文本字段只有在您單擊文本後纔會獲得焦點,而不是在出現時才獲得焦點 –

+0

請參閱http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html關於如何注重Swing組件 –

回答

8

解決方法一:通過焦點事件做吧。不是最好的解決方案。

public static void main(final String[] args) { 
    // simple window preparation 
    final JFrame f = new JFrame(); 
    f.setBounds(200, 200, 400, 400); 
    f.setVisible(true); 

    { // this sleep part shall simulate a user doing some stuff 
     try { 
      Thread.sleep(2345); 
     } catch (final InterruptedException ignore) {} 
    } 

    { // here's the interesting part for you, this is what you put inside your button listener or whatever 
     final JTextField t = new JTextField("Hello World!"); 
     t.addFocusListener(new FocusListener() { 
      @Override public void focusLost(final FocusEvent pE) {} 
      @Override public void focusGained(final FocusEvent pE) { 
       t.selectAll(); 
      } 
     }); 
     f.add(t); 
     f.validate(); 

     t.requestFocus(); 
    } 
} 
+0

謝謝你的迴應,它真的幫助我 –

+0

使用Thread.sleep的目的是什麼?這在Swing應用程序中通常被認爲是不好的做法 – MadProgrammer

+0

這只是爲了讓該領域在延遲後彈出,而不是做所有這些點擊按鈕 - 隱藏 - 元素 - 新元素 - 彈出 - 獲取 - 聚焦 - 全部被選中他在原始問題中正在談論。但是我會編輯我的帖子,使其更清晰。 – JayC667

6

JTextField.selectAll()是你所需要的。

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class SelectAll 
{ 
    private int count = 0; 

    private void displayGUI() 
    { 
     JFrame frame = new JFrame("Select All"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     final JPanel contentPane = new JPanel(); 
     JButton addButton = new JButton("Add"); 
     addButton.addActionListener(new ActionListener() 
     { 
      @Override 
      public void actionPerformed(ActionEvent ae) 
      { 
       JTextField tfield = new JTextField(10); 
       tfield.setText("" + (++count));    
       contentPane.add(tfield); 
       tfield.requestFocusInWindow(); 
       tfield.selectAll(); 

       contentPane.revalidate(); 
       contentPane.repaint(); 
      } 
     }); 

     contentPane.add(addButton); 

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 
    public static void main(String... args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       new SelectAll().displayGUI(); 
      } 
     }); 
    } 
} 
+0

似乎您必須將selectAll()與[requestFocusInWindow()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocusInWindow())一起使用,以獲得所需的效果。如我的編輯所示。 –

相關問題