Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The default behavior of <a href="http://download.oracle.com/javase/6/docs/api/javax/swing/JFormattedTextField.html" rel="nofollow"><code>JFormattedTextField</code></a> on <code>focusLost</code> is <code>COMMIT_OR_REVERT</code>, so one approach is to do the update <em>after</em> the focus listener has concluded. A <a href="http://en.wikipedia.org/wiki/Continuation-passing_style#Continuations_as_objects" rel="nofollow">continuation</a> works nicely, as shown below.</p> <pre><code>import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.text.NumberFormat; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JPanel; /** @see http://stackoverflow.com/questions/6803976 */ public class Adder extends JPanel { private final NumberFormat format = NumberFormat.getNumberInstance(); private final JFormattedTextField a = new JFormattedTextField(format); private final JFormattedTextField b = new JFormattedTextField(format); private final JFormattedTextField sum = new JFormattedTextField(format); public Adder() { this.setLayout(new GridLayout(0, 1)); this.add(init(a)); this.add(init(b)); sum.setEditable(false); sum.setFocusable(false); this.add(sum); } private JFormattedTextField init(JFormattedTextField jtf) { jtf.setValue(0); jtf.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { Number v1 = (Number) a.getValue(); Number v2 = (Number) b.getValue(); sum.setValue(v1.longValue() + v2.longValue()); } }); } }); return jtf; } private void display() { JFrame f = new JFrame("Adder"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(this); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Adder().display(); } }); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload