2012-11-30 30 views
5

我是Swing Java開發新手。有人能幫我解決這個問題嗎?Swing - MaskFormatter - 在文本框右側輸入數字

我有一個帶有maskformatter的jformattedtextfield。它工作得很好。但只有我想知道的是,如果我們能夠從右側輸入數字。下面的代碼工作得很好,從左到右輸入數字。

謝謝你的時間。

這裏是Java代碼,我有:

public class MaskFormattedTextExample extends JFrame { 

    private static final long serialVersionUID = -1212313123; 

    JFormattedTextField timeField; 

    public MaskFormattedTextExample() { 
     initComponents(); 
    } 

    private void initComponents() { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setSize(new Dimension(200, 200)); 
     getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); 

     MaskFormatter mask = null; 
     try { 
      mask = new MaskFormatter("##:##:##"); 
      mask.setPlaceholderCharacter('_'); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 

     timeField = new JFormattedTextField(mask); 
     timeField.setHorizontalAlignment(JTextField.RIGHT); 
     timeField.setCaretPosition(JTextField.RIGHT); 

     getContentPane().add(timeField); 
    } 

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

      public void run() { 
       new MaskFormattedTextExample().setVisible(true); 
      } 
     }); 
    } 
} 
+0

您是否嘗試過['setComponentOrientation(的ComponentOrientation O)'](http://docs.oracle .com/javase/1.4.2/docs/api/javax/swing/JSpinner.html)方法? – fireshadow52

+0

['Component.setComponentOrientation(ComponentOrientation)'](http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#setComponentOrientation%28java.awt.ComponentOrientation%29)FTFY @ fireshadow52 :) – Brian

+0

謝謝Brian和fireshadow52。它運作良好。但我看到一個小問題。插入位置有點混亂。我希望始終能夠看到最後的插入位置。相反,它在開始時顯示。我還觀察到,輸入3位數字後的數字格式爲149(我希望看到1:49,但顯示爲14:9) – Steve

回答

4

你可以使用:

timeField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 
+0

謝謝Reimeus。它運作良好。但我看到一個小問題。插入位置有點混亂。我希望始終能夠看到最後的插入位置。相反,它在開始時顯示。我還觀察到輸入3位數字後的數字格式爲149(我希望看到1:49,但它顯示爲14:9) – Steve

+0

這是'JFormattedTextField'的默認行爲。你可以看看從一個新的[setCaretPosition](http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition%28int%29) DocumentListener](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html)。 – Reimeus