Java Swing How to - Set Value to JFormattedTextField








Question

We would like to know how to set Value to JFormattedTextField.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
//from w  w w  .j a va 2 s  . c  o m
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
   JFormattedTextField loanAmountField = new JFormattedTextField(
         NumberFormat.getCurrencyInstance());

   public Main() {
      loanAmountField.setColumns(8);
      loanAmountField.setEditable(false);
      loanAmountField.setFocusable(false);
      add(loanAmountField);
      add(new JButton(new CalculateListener(loanAmountField)));
   }
   public static void main(String[] args) {
     Main mainPanel = new Main();
     JFrame f = new JFrame();
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     f.getContentPane().add(mainPanel);
     f.pack();
     f.setVisible(true);
   }
}
class CalculateListener extends AbstractAction {
  JFormattedTextField loanAmountField;
  public CalculateListener(JFormattedTextField loanAmountField) {
     super("Calculate");
     putValue(MNEMONIC_KEY, KeyEvent.VK_C);
     this.loanAmountField = loanAmountField;
  }
  public void actionPerformed(ActionEvent event) {
     loanAmountField.setValue(new Double(12.22));
  }
}