2012-06-01 109 views
3

我已經創建了一些我想使用用戶輸入的文本域。我已經閱讀過我應該使用documentlistener,但是我認爲在實現它的時候遇到了一些困難。如何實現documentlistener

在代碼中,我試圖實現它到textfield tf1。 im應該得到的輸入是被解析爲一個double,所以我可以對它進行一些數學計算。

這裏是我的代碼,我嘗試實現它。

import java.awt.ComponentOrientation; 
import java.awt.Container; 
import java.awt.Dimension; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JCheckBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.event.DocumentEvent; 
import javax.swing.event.DocumentListener; 


public class Display { 
final static boolean shouldFill = true; 
final static boolean shouldWeightX = true; 
final static boolean RIGHT_TO_LEFT = false; 

public static void addComponentsToPane(Container pane) { 

    if (RIGHT_TO_LEFT) { 
     pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 
    } 
    JButton button; 
    JLabel label; 

    pane.setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    if (shouldFill) { 
    //natural height, maximum width 
    c.fill = GridBagConstraints.HORIZONTAL; 
    } 
    if (shouldWeightX) { 
    c.weightx = 0.5; 
    } 

    ... 

    button = new JButton("Value Bet"); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.ipady = 0; 
    c.gridx = 0; 
    c.gridy = 1; 
    pane.add(button, c); 
    button.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) 
     { 
      //Execute when button is pressed 
      JFrame frame = new JFrame("Value Bet"); 
      frame.setVisible(true); 
      frame.setSize(500,300); 
      GridBagLayout layout = new GridBagLayout(); 
      frame.setLayout(layout); 
      GridBagConstraints c = new GridBagConstraints(); 

      JLabel label; 
      JTextField tf; 

      if (shouldFill) { 
      //natural height, maximum width 
      c.fill = GridBagConstraints.HORIZONTAL; 
      } 
      if (shouldWeightX) { 
      c.weightx = 0.5; 
      } 

      ... 

      final JTextField tf1 = new JTextField(); 
      c.fill = GridBagConstraints.HORIZONTAL; 
      c.gridx = 1; 
      c.gridy = 2; 
      frame.add(tf1, c); 

      tf1.getDocument().addDocumentListener(new DocHandler(){ 
       public class DocHandler implements DocumentListener{ 

        @Override 
        public void changedUpdate(DocumentEvent arg0) { 
         tfHasChanged(); 

        } 

        @Override 
        public void insertUpdate(DocumentEvent arg0) { 
         tfHasChanged(); 

        } 

        @Override 
        public void removeUpdate(DocumentEvent arg0) { 
         tfHasChanged(); 

        } 

       } 

       public void tfHasChanged(){ 
        double chance1 = Double.parseDouble(tf1.getText()); 
       } 
      });  

      ... div components 


} 

private static void createAndShowGUI() { 
     //Create and set up the window. 
     JFrame frame = new JFrame("Betting Application"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //Set up the content pane. 
     addComponentsToPane(frame.getContentPane()); 

     //Display the window. 
     frame.pack(); 
     frame.setVisible(true); 
    } 

public static void main(String[] args) { 
     //Schedule a job for the event-dispatching thread: 
     //creating and showing this application's GUI. 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 
+0

我建議你放棄這整個方法,並使用一個模態對話框,我建議在[我的回答](http://stackoverflow.com/a/10846008/418556)到你最後一個問題。或者爲了得到最好的幫助,至少要解釋爲什麼你不想採取這種方法。 –

+0

爲了儘快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

4

對於你的數字來實現的DocumentFilter或直接與數字格式化使用的JFormattedTextField

那麼可能的方式(塊執行)代碼行

formatter.setMinimum(0.0); 
formatter.setMaximum(1000.00); 

,並添加一些公式爲textField1,例如textField1等於textField2的值例如

import java.awt.*; 
import java.awt.font.TextAttribute; 
import java.math.*; 
import java.text.*; 
import java.util.Map; 
import javax.swing.*; 
import javax.swing.JFormattedTextField.*; 
import javax.swing.event.*; 
import javax.swing.text.InternationalFormatter; 

public class DocumentListenerAdapter { 

    public static void main(String args[]) { 
     JFrame frame = new JFrame("AbstractTextField Test"); 
     final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01)); 
     textField1.setFormatterFactory(new AbstractFormatterFactory() { 

      @Override 
      public AbstractFormatter getFormatter(JFormattedTextField tf) { 
       NumberFormat format = DecimalFormat.getInstance(); 
       format.setMinimumFractionDigits(2); 
       format.setMaximumFractionDigits(2); 
       format.setRoundingMode(RoundingMode.HALF_UP); 
       InternationalFormatter formatter = new InternationalFormatter(format); 
       formatter.setAllowsInvalid(false); 
       formatter.setMinimum(0.0); 
       formatter.setMaximum(1000.00); 
       return formatter; 
      } 
     }); 
     final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes(); 
     attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); 
     final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01)); 
     textField2.setFormatterFactory(new AbstractFormatterFactory() { 

      @Override 
      public AbstractFormatter getFormatter(JFormattedTextField tf) { 
       NumberFormat format = DecimalFormat.getInstance(); 
       format.setMinimumFractionDigits(2); 
       format.setMaximumFractionDigits(2); 
       format.setRoundingMode(RoundingMode.HALF_UP); 
       InternationalFormatter formatter = new InternationalFormatter(format); 
       formatter.setAllowsInvalid(false); 
       //formatter.setMinimum(0.0); 
       //formatter.setMaximum(1000.00); 
       return formatter; 
      } 
     }); 
     textField2.getDocument().addDocumentListener(new DocumentListener() { 

      @Override 
      public void changedUpdate(DocumentEvent documentEvent) { 
       printIt(documentEvent); 
      } 

      @Override 
      public void insertUpdate(DocumentEvent documentEvent) { 
       printIt(documentEvent); 
      } 

      @Override 
      public void removeUpdate(DocumentEvent documentEvent) { 
       printIt(documentEvent); 
      } 

      private void printIt(DocumentEvent documentEvent) { 
       DocumentEvent.EventType type = documentEvent.getType(); 
       double t1a1 = (((Number) textField2.getValue()).doubleValue()); 
       if (t1a1 > 1000) { 
        Runnable doRun = new Runnable() { 

         @Override 
         public void run() { 
          textField2.setFont(new Font(attributes)); 
          textField2.setForeground(Color.red); 
         } 
        }; 
        SwingUtilities.invokeLater(doRun); 
       } else { 
        Runnable doRun = new Runnable() { 

         @Override 
         public void run() { 
          textField2.setFont(new Font("Serif", Font.BOLD, 16)); 
          textField2.setForeground(Color.black); 
         } 
        }; 
        SwingUtilities.invokeLater(doRun); 
       } 
      } 
     }); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(textField1, BorderLayout.NORTH); 
     frame.add(textField2, BorderLayout.SOUTH); 
     frame.setVisible(true); 
     frame.pack(); 
    } 

    private DocumentListenerAdapter() { 
    } 
} 
+0

鑑於'「價值賭注」'我一直認爲最好的組件是'NumberModel'的'JSpinner' - 但是然後OP似乎忽略了我。 :) –

+1

@Andrew Thompson肯定BNI,我的壞在默認情況下,我從來沒有檢查asker userprofiles,這是爲了保護我的精神健康:-) – mKorbel

+0

我通常不檢查配置文件,只是當我有一個壓倒性的Déjàvu感(哦,並且不要激動,那些有趣的小急性病可能是正確的,因爲我複製/粘貼[維基百科的Déjàvu](http://en.wikipedia.org/wiki/D%C3%A9j%C3%A0_vu); )。 –

1

如果TF1是一個文本字段那麼做,文檔偵聽實現3種方法一樣的changedUpdate,中的insertUpdate,中的removeUpdate

tf1.getDocument().addDocumentListener(new DocumentListener() { 

    @Override 
     public void changedUpdate(DocumentEvent e){ 

           //do some math 
           tf1.getText(); 
            } 

     @Override 
     public void insertUpdate(DocumentEvent e) { 

            /do some math 
           tf1.getText(); 
     } 

     @Override 
     public void removeUpdate(DocumentEvent e) { 
      // TODO Auto-generated method stub 

     } 
});