JFormattedTextField in Forte Swing palette

Recently I upgraded Forte to release 4. I want to start using the new features of JDK 1.4, but I'm surprised to see that eg. JFormattedTextField is not in my Forte Swing palette. I cannot drop a JFormattedTextField in a JPanel now.
Can anyone please tell me why it's not in the palette or how to get it there. I know how to use 'add to component palette' for my own made Swing classes, but not for new JDK 1.4 classes.

take the nb3.4 it is there.
www.netbeans.org

Similar Messages

  • New Swing Component for Swing Palette in NetBeans

    Hi guys,
    I want to write a new Swing component (Bean) for drawing vertical and horizontal lines to use with netBeans GUI designer.
    Could anyone direct me to a tutorial
    thanks in advance

    JTextcomponent.

  • Forte/swing help

    I'm making a text editor for practice with java... How do i make a text area with a scrollbar? Horizontil and vertical..
    Thanks

    JTextArea area = new JTextArea( nRows, nCols );
    JScrollPane pane = new JScrollPane( area );
    To control how large the client under the scroll pane's viewport is use "setPreferredSize()"
    To set which scroll bars get displayed when, use "[set/get][Horizontal/Vertical]ScrollbarPolicy()" on the pane object
    add the pane to your panel/frame etc

  • JFormattedTextField creating spaces in field

    Hi, I am working with a JFormattedTextField, I am using the tutorial from Sun, but once the text field is created it already has spaces put in the field. I tried using setText and it still has them either way.
    import java.awt.Container;
    import java.awt.FlowLayout;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.text.MaskFormatter;
    public class test extends JFrame {
         private JTextField InputLoc;
         // I have also set InputLoc to be a JFormattedTextField
         Container mainWindow;
         public test() {
              makeInput();
              mainWindow = getContentPane();
              mainWindow.setLayout(new FlowLayout());
              mainWindow.add(InputLoc);
         private void makeInput() {
              InputLoc = new JFormattedTextField(createFormatter("###########"));
              InputLoc.setText("");
         protected MaskFormatter createFormatter(String s) {
              MaskFormatter formatter = null;
              try {
                   formatter = new MaskFormatter(s);
              } catch (java.text.ParseException exc) {
                   System.err.println("formatter is bad: " + exc.getMessage());
                   System.exit(-1);
              return formatter;
         public static void main(String[] args) {
              test gui = new test();
              gui.setSize(80, 80);
              gui.setVisible(true);
    }The code should compile and will show you what is going on. Please let me know what the problem is.
    thanks
    Joe

    Please let me know what the problem is. I don't know what the problem is, because I can't tell from your description how you expect that code to behave. The code is doing what you tell it to do, so if you want it to do something different, we'll need to understand what that something is...
    ~

  • JFormattedTextField

    Hey!
    I'm having problem with entering numbers after decimal point. I 've set
    two digits after decimal point. when I add first time it's working.
    When try to override it takes third number & rounding it off and adding
    it.
    eg: 38 then overrude 8 with 7 it take 387 and puts 39
    If I enable override mode enable when I entering number reaches cmmma (,) without problem but afterwards it takes next two digits after
    decimal point addes with entered number.
    45.00 inserting 25 then it becomes 452,500.00
    I tried my best to solve it. please someone help me to sort out this
    problem..
    I've added my code here you can test and give me some idea..
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.text.NumberFormatter;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.JTextField;
    import javax.swing.JFormattedTextField;
    import javax.swing.text.DefaultFormatter;
    import java.math.BigDecimal;
    import java.util.Locale;
    import java.text.*;
    import javax.swing.text.MaskFormatter;
    public class NumberCellEditor{
    DecimalFormat numberFormat;
    JFrame frame;
    JFormattedTextField text,text1;
    JPanel panel;
    public void create(){
    text=new JFormattedTextField();
    text1=new JFormattedTextField();
    numberFormat = (DecimalFormat) NumberFormat.getNumberInstance();
    numberFormat.setDecimalSeparatorAlwaysShown(true);
    numberFormat.setMinimumFractionDigits(2);
    NumberFormatter numFormatter = new
    NumberFormatter(numberFormat);
    numFormatter.setAllowsInvalid(false);
    numFormatter.setFormat(numberFormat);
    //numFormatter.setOverwriteMode(true);
    text.setValue(new Float(0.0F));
    text.setFormatterFactory(new
    DefaultFormatterFactory(numFormatter));
    text.setHorizontalAlignment(JTextField.TRAILING);
    public void createComp(){
    frame=new JFrame(" TEST 2");
    panel=new JPanel();
    panel.setLayout(null);
    create();
    text.setBounds(100,100,100,30);
    text1.setBounds(100,200,100,30);
    panel.add(text);
    panel.add(text1);
    frame.getContentPane().add(panel);
    frame.setSize(300,300);
    frame.setVisible(true);
    public static void main (String [] args){
    NumberCellEditor n=new NumberCellEditor();
    n.createComp();
    }

    Hey guys !!!
    Thanks for your advice...
    Do you know why did I post it twice? I want to know the problem is with my code or with some problem in JDK. That's why I've given the full code to run & check...
    Since you guys are well experienced in programming I thought this will a simple problem to solve. well... I'm just started this programming...
    Well.. I think it's not useful to post my problems in to the prestigious JAVA FORUM. Since i'm so young in programming I'll certainly waste your valuable TIME.
    Any way.. Thanks for teaching a lession to me.
    Bye

  • JFormattedTextField Currency Symbol($) handling

    I've been searching for a good currency field that is more generic than the examples in the java tutorials. Wasn't able to find any, so I created one. This may not be the place to put this, but here it is anyway. If you have something better, or some suggestions to improve this, or if something is missing, please post it.
    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class CurrencyField
      extends JFormattedTextField
      public CurrencyField()
        super();
        setFormatterFactory(new DefaultFormatterFactory(new CurrencyFormatter()));
      public class CurrencyFormatter
        extends JFormattedTextField.AbstractFormatter
         public String valueToString(Object object)
           if (object == null)
             return "";
           NumberFormat curFormat = NumberFormat.getCurrencyInstance();
           return curFormat.format(object);
         public Object stringToValue(String string) throws ParseException
           Number number = null;
           NumberFormat curFormat = NumberFormat.getCurrencyInstance();
           NumberFormat numFormat = NumberFormat.getNumberInstance();
           try
             number = curFormat.parse(string);
           catch(ParseException ex)
             try
               number = numFormat.parse(string);
             catch(ParseException ex2)
               throw ex2;
           return number;
       * Test
       * @param args String[]
      public static void main(String[] args)
        JFrame frame = new JFrame("Testing CurrencyField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        CurrencyField cField01 = new CurrencyField();
        cField01.setColumns(10);
        CurrencyField cField02 = new CurrencyField();
        cField02.setColumns(10);
        panel.add(cField01);
        panel.add(cField02);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }Hopefully somebody will find this useful.

    Hello Wardle,
    I find your code very usefully, thx. I have made some changes so that the user can clear the field with a blank string and to show the value precision before overriding the value.
    import java.text.NumberFormat;
    import java.text.ParseException;
    import javax.swing.JFormattedTextField;
    import javax.swing.text.DefaultFormatterFactory;
    public class CurrencyField extends JFormattedTextField {
         public CurrencyField() {
              super();
              setFormatterFactory(new DefaultFormatterFactory(new CurrencyFormatter(),
                        new CurrencyFormatter(),
                        new EditCurrencyFormatter())); //changed to use seperate editFormatter
         private class EditCurrencyFormatter extends CurrencyFormatter { //add editFormatter....
              public String valueToString(Object object) {
                   if (object == null) {
                        return "";
                   NumberFormat curFormat = NumberFormat.getCurrencyInstance();
                   curFormat.setMaximumFractionDigits(14); //....with shown precision
                   return curFormat.format(object);
         private class CurrencyFormatter extends
                   JFormattedTextField.AbstractFormatter {
              public String valueToString(Object object) {
                   if (object == null) {
                        return "";
                   NumberFormat curFormat = NumberFormat.getCurrencyInstance();
                   return curFormat.format(object);
              public Object stringToValue(String string) throws ParseException {
                   if (string == null || string.trim().length() == 0) { //add handling for empty string
                        return null;
                   Number number = null;
                   NumberFormat curFormat = NumberFormat.getCurrencyInstance();
                   NumberFormat numFormat = NumberFormat.getNumberInstance();
                   try {
                        number = curFormat.parse(string);
                   } catch (ParseException ex) {
                        try {
                             number = numFormat.parse(string);
                        } catch (ParseException ex2) {
                             throw ex2;
                   return number;
    }

  • JFormattedTextField.isEditValid() not returning false

    I have the following code, and in the text field you can type all kinds of letters or numbers and it always shows up as having valid input. Why is this? Also, why is the ".01" truncated off when the application starts up? Basically, I want the user to be forced to enter in a floating point number.
    Thank you for your time,
    Brandon Murphy
    import java.awt.Color;
    import java.text.ParseException;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.MaskFormatter;
    public class DocumentListenerAdapter implements DocumentListener
         public DocumentListenerAdapter(JFormattedTextField textField)
              _textField = textField;
         public void changedUpdate(DocumentEvent e) {this.verify();}
         public void insertUpdate(DocumentEvent e) {this.verify();}
         public void removeUpdate(DocumentEvent e) {this.verify();}
         protected void verify()
              if(_textField.isEditValid() == true)
                   _textField.setBorder(null);
              else //(_textField.isEditValid() == false)
                   _textField.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
              System.out.println(_textField.isValid() + ", " +  _textField.getText());
         private JFormattedTextField      _textField      = null;
      public static void main(String argv[])
              JFrame frame = new JFrame("AbstractTextField Test");
             JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
             textField1.getDocument().addDocumentListener(new DocumentListenerAdapter(textField1));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(textField1);
              frame.setVisible(true);
              frame.pack();
    }Edited by: officialhopsof on Jun 16, 2010 2:07 AM

    You never actually set a format on the text field.
    If you turn on setAllowsInvalid the user can actual type "10.blabla" and it'll just accept that as 10, not sure how to fix that.
    import java.awt.Color;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JFormattedTextField.AbstractFormatter;
    import javax.swing.JFormattedTextField.AbstractFormatterFactory;
    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);
                    InternationalFormatter formatter = new InternationalFormatter(format);
                    formatter.setAllowsInvalid(false);
                    return formatter;
            textField1.addPropertyChangeListener("editValid", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    boolean valid = (Boolean) evt.getNewValue();
                    System.out.println(valid + ", " + textField1.getValue() + ", "
                            + textField1.getText());
                    if (valid) {
                        textField1.setBorder(null);
                    else {
                        textField1.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(textField1);
            frame.setVisible(true);
            frame.pack();
    }

  • Tricky behaviour on JFormattedTextField

    Dear friends,
    after few trials using JFormattedTextField, I finaly figured out how it beaves...
    if you have te value 1,00 and type DEL with the cursor just before the comma character, the text field value becomes 100,00 - this weird behaviour has a simple explanation: when you click DEL before the comma symbol, the text component remove the comma, and the value 1,00 becomes 100. After that, the view formatter add the comma again and the value becomes 100,00. Strange ? yes, very strange behaviour... at least from the point of view of the user. My user is asking me: "Why 1 dolar becomes a hundred dollars in a unique touch?"
    my question now is: How can I avoid that behaviour ? <b>how can I avoid the value 1,00 to be transformed into 100,00 by clicking DEL before the comma?</b> is it possible ?
    below is my test code:
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.math.BigDecimal;
    import java.text.DecimalFormat;
    import java.text.DecimalFormatSymbols;
    import java.util.Locale;
    import javax.swing.JButton;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.NumberFormatter;
    public class testeFormat {
         public static JLabel getText = new JLabel("getText  = ");
         public static JLabel getValue = new JLabel("getValue = ");
         public static void main(String args[]) {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().setLayout(new GridLayout(4, 1));
              final JFormattedTextField tf = new JFormattedTextField();
              DecimalFormat df = new DecimalFormat("#,###.00");
              df.setDecimalFormatSymbols(new DecimalFormatSymbols(new Locale("pt", "BR")));
              NumberFormatter nf = new NumberFormatter(df);
              nf.setValueClass(BigDecimal.class);
              nf.setOverwriteMode(false);
              DefaultFormatterFactory factory = new DefaultFormatterFactory(
                        //new NumberFormatter(df), // Default
                        nf, // Display
                        nf); // Edit
              tf.setFormatterFactory(factory);
              tf.setHorizontalAlignment(SwingConstants.RIGHT);
              nf.setAllowsInvalid(false);
              tf.setValue(new Double(0.0d));
              tf.setColumns(20);
              frame.getContentPane().add(tf);
              JButton button = new JButton("Test");
              frame.getContentPane().add(button);
              frame.getContentPane().add(getText);
              frame.getContentPane().add(getValue);
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        getText.setText("getText() = " + tf.getText());
                        getValue.setText("getValue() = " + tf.getValue());
              frame.setSize(new Dimension(300, 200));
              frame.setVisible(true);
    }

    you could add a keyListener
        tf.addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            if(ke.getKeyCode() == KeyEvent.VK_DELETE)
              if(tf.getText().charAt(tf.getCaretPosition()) == ',')
                ke.consume();
                java.awt.Toolkit.getDefaultToolkit().beep();
            }}});

  • Get focus to the start of JFormattedTextField

    I create my JFormattedTextField like this:
           try{
                 MaskFormatter formatter = new MaskFormatter( "######-####" );
                 JFormattedTextField idNr = new JFormattedTextField(formatter);
            catch(ParseException idNr){System.out.println(idNr);}Its working fine but the only problem is that when a user selects the JFormattedTextField to fil it out the focus is gained in the midle instead of the start where it should be.... Like normally a TextField would do.Can anyone help me with this?

    This is a small subclass that only works with the DefaultFormatter constructor. Basically, you need to add a FocusListener and MouseListener. When the TextField gains focus, set a flag. When the user clicks in the TextField with the mouse the first time, the flag will be set (focus event comes first). The mouseClicked method will be called. If the flag is set, set the caret position to the beginning.
    If the user clicks in the text field after the field already has focus, move the caret to the mouse position as normal.
    Chad
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JFormattedTextField;
    import javax.swing.text.DefaultFormatter;
    public class JMaskField extends JFormattedTextField
    implements FocusListener, MouseListener
         private boolean justGotFocus;
         public JMaskField(DefaultFormatter mask)
              super(mask);
              addFocusListener(this);
              addMouseListener(this);
              justGotFocus = false;
         public void focusLost(FocusEvent event)
              setBackground(Color.white);
         public void focusGained(FocusEvent event)
              setBackground(Color.green);
              justGotFocus = true;
         public void mouseClicked(MouseEvent event)
              if (justGotFocus == true)
                   justGotFocus = false;
                   setCaretPosition(0);
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
         public void mouseReleased(MouseEvent e) {}

  • Listener for JFormattedTextField

    Hi. I'm trying to do a simple thing. I have a JFormattedTextField and when You enter some value in that field and press Enter I'd like the testLabel to display that value. My code doesn't work, what am I doing wrong?
    package trial;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.event.ChangeEvent;
    public class TrialMain implements PropertyChangeListener {
        JLabel testLabel = new JLabel();
        JLabel command = new JLabel("Enter some text below:");
        JFormattedTextField enterText = new JFormattedTextField();
        public TrialMain() {
            JFrame frm = new JFrame();
            frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel( new GridLayout(5, 1) );
            p.setOpaque(true);
            p.setPreferredSize( new Dimension(200, 200) );
            p.setBackground( Color.GREEN );
            frm.setContentPane(p);
            p.add(testLabel);
            p.add(command);
            p.add(enterText);
            enterText.addPropertyChangeListener(this);
            frm.pack();
            frm.setVisible(true);
        public static void main(String[] args) {
            new TrialMain();
        public void propertyChange(PropertyChangeEvent evt) {
            Object source = evt.getSource();
            if(source == enterText) {
                testLabel.setText(enterText.getText());
    }

    I haven't looked all that closely but according to http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html it should beenterText.addPropertyChangeListener("value", this);

  • Problem with PropertyChangeListener and JTextField

    I'm having a problem with PropertyChangeListener and JTextField.
    I can not seem to get the propertychange event to fire.
    Anyone have any idea why the code below doesn't work?
    * NewJFrame.java
    * Created on May 15, 2005, 4:21 PM
    import java.beans.*;
    import javax.swing.*;
    * @author wolfgray
    public class NewJFrame extends javax.swing.JFrame
    implements PropertyChangeListener {
    /** Creates new form NewJFrame */
    public NewJFrame() {
    initComponents();
    jTextField1.addPropertyChangeListener( this );
    public void propertyChange(PropertyChangeEvent e) {
    System.out.println(e);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
    jFormattedTextField1.setText("jFormattedTextField1");
    jScrollPane1.setViewportView(jFormattedTextField1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    }

    If you want to listen to changes in the textfield's contents you should use a DocumentListener and not a PropertyChangeListener:
    http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
    And please use [co[/i]de]  tags when you are posting code (press the code button above the message window).

  • HOW TO: Create a JSP Edit Record Form Using BC4J Data Tags

    This is a JDeveloper Tech Note found on the OTN Documentation page. This note describes the use of the BC4J data tags to create row edit/submit JSP pages. Here is the link:
    http://technet.oracle.com/docs/products/jdev/technotes/datatag_input/Edit_Form.html

    Are you using Java 1.4.* ?
    Use JFormattedTextField.
    import javax.swing.*;
    import java.text.*;
    import java.awt.*;
    import java.util.*;
    public class DateExample
        public static void main( String [] args )
          // Here's what you're interested in...
          DateFormat dateFormat = new SimpleDateFormat( "MM/dd/yyyy" );
          JFormattedTextField field = new JFormattedTextField( dateFormat );
          field.setColumns( 11 );
          field.setText( dateFormat.format(new Date()) );
          JPanel panel = new JPanel();
          panel.add( field );
          panel.add( new JButton( "Hey" ) );
          JFrame f = new JFrame();
          f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          f.getContentPane().add( panel );
          f.pack();
          f.setVisible( true );
    }It also works with other types of Format objects (ex. Currency, Decimal, etc.)

  • How do I limit number of characters in a JTextField?(different from others)

    Hi,
    I know this question has been posted several times on this forum, but my question is actually a different one. So please read.
    I have the following code that puts two JTextFields in a JFrame. I want to limit the number of characters in the first JTextField to three characters. What's different about my question from other solutions provided, is that I don't want to be able to type more than three characters in the JTextField, and then not be able to get out of JTextField unless I have three or less characters. What I do want, is to have maximum of three characters, not be able to type the fourth, and have access to the other JTextField at all times.
    I have tried the following solution of setting an InputVerifier to my JTextField, but it hasn't worked, since I can still type the fourth character.
    Looking forward to your help!
    Thanks.
    import java.awt.Dimension;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.InputVerifier;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class TextFieldVerifier {
         public TextFieldVerifier()
              JFrame frame = new JFrame("My TextVerifier");
              JPanel panel = new JPanel();
              JLabel firstTextFieldLabel = new JLabel("First: ");
              JLabel secondTextFieldLabel = new JLabel("Second: ");
              final JTextField myTextField = new JTextField();
              myTextField.setPreferredSize(new Dimension(100,20));
              myTextField.setInputVerifier(new InputVerifier()
                   public boolean verify(JComponent input) {
                        if(myTextField.getText().length()<=3)
                             return true;
                        else
                            return false;     
              myTextField.addKeyListener(new KeyAdapter()
                   public void keyTyped(KeyEvent e)
                        if(!myTextField.getInputVerifier().verify(myTextField))
                             myTextField.setText(myTextField.getText().substring(0, myTextField.getText().length()-1));
              JTextField secondTextField = new JTextField();
              secondTextField.setPreferredSize(new Dimension(100,20));
              panel.add(firstTextFieldLabel);
              panel.add(myTextField);
              panel.add(secondTextFieldLabel);
              panel.add(secondTextField);
              frame.getContentPane().add(panel);
              frame.setSize(new Dimension(200,100));
              frame.setVisible(true);
         public static void main (String [] args)
              TextFieldVerifier v = new TextFieldVerifier();
    }

    Thanks, JayDS! Your suggestion worked. And I've come up with the following code with help of your suggestion. However, I'm not happy with the fact that I see empty spaces in my JFormattedTextField when I don't have anything entered in it, or when my textfield has focus and I click it again. Also, I'd like the text alignment to always stay on the right, even if I have less than 3 digits.
    Could you please help me out with that?
    Thanks!
    import java.awt.Dimension;
    import java.text.ParseException;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.MaskFormatter;
    public class TextFieldVerifier {
         public TextFieldVerifier()
              JFrame frame = new JFrame("My TextVerifier");
              JPanel panel = new JPanel();
              JLabel firstTextFieldLabel = new JLabel("First: ");
              JLabel secondTextFieldLabel = new JLabel("Second: ");
              try{
                   VariableLengthMaskFormatter formatter = new VariableLengthMaskFormatter("###");
                   final JFormattedTextField myTextField = new JFormattedTextField(formatter);
                   myTextField.setHorizontalAlignment(JTextField.RIGHT);
                   myTextField.setPreferredSize(new Dimension(100,20));
                   panel.add(firstTextFieldLabel);
                   panel.add(myTextField);
              } catch (ParseException ex) {
                   ex.printStackTrace();
              JTextField secondTextField = new JTextField();
              secondTextField.setPreferredSize(new Dimension(100,20));
              panel.add(secondTextFieldLabel);
              panel.add(secondTextField);
              frame.getContentPane().add(panel);
              frame.setSize(new Dimension(200,100));
              frame.setVisible(true);
         protected MaskFormatter createFormatter(String s) {
             MaskFormatter formatter = null;
             try {
                  formatter = new MaskFormatter(s);
             } catch (java.text.ParseException exc) {
                 System.err.println("formatter is bad: " + exc.getMessage());
                 System.exit(-1);
             return formatter;
         public static void main (String [] args)
              TextFieldVerifier v = new TextFieldVerifier();
    }Edited by: programmer_girl on Mar 10, 2008 11:10 PM

  • Using variables in 5 instances of one Class in a seperate Class

    I have 5 instances of the one Class all returning different values. These values are parameteres for a final calculation. I am using Sliders as my data validation and I want my final calculation to react to the individual sliders being moved. I need to know the name of the slider and its value or do I?
    I would like to Calculate Tractive effort in Extra Panel, I know that all this has something to do with Event Handling but what?
    Any and help vastly appreciated otherwise I am goint to eat this computer cables and all.
    By the way I Hate Computers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Code as follows:
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TractiveEffortCalculator extends JFrame
         private static final long serialVersionUID = 1L;
         public ConstructParametersPanel Instance = new ConstructParametersPanel();
         public ExtraPanel Sample = new ExtraPanel();
         public JPanel thisPanel;
         public TractiveEffortCalculator()
              thisPanel = new JPanel();
              //super ("N Generation Steam"+"           "+"Tractive Effort Calculator");
              BackGroundColour myColor = new BackGroundColour();
              //ConstructParametersPanel Instance = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(2);
              grid.setHgap(10);
              grid.setRows(1);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              thisPanel.add(Instance.ConstructParametersPanelMethod());
              thisPanel.add(Sample.ExtraPanelMethod());
              setBackground(myColor.NewBackGroundColour());
              getContentPane().add(thisPanel);
              pack();
              setVisible(true);
              setLocation(40,50);
              setSize(800,600);
              //setResizable(false);
         public static void main(final String[]args)
              final TractiveEffortCalculator app = new TractiveEffortCalculator();
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    public class ConstructParametersPanel extends JPanel
         private static final long serialVersionUID = 1L;
         private JPanel sidePanel;
         TheSliderClass Instance1 = new TheSliderClass();
         TheSliderClass Instance2 = new TheSliderClass();
         TheSliderClass Instance3 = new TheSliderClass();
         TheSliderClass Instance4 = new TheSliderClass();
         TheSliderClass Instance5 = new TheSliderClass();
         public JPanel ConstructParametersPanelMethod()
              sidePanel = new JPanel();
              BackGroundColour myColor = new BackGroundColour();
              GreenColour myColor2 = new GreenColour();
              BlackShadowColour myColor3 = new BlackShadowColour();
              sidePanel.setBorder(BorderFactory.createBevelBorder(1
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()
                                                                          ,myColor2.NewGreenColour()
                                                                          ,myColor3.NewBlackShadowColour()));
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              sidePanel.setLayout(grid);
              sidePanel.setBackground(myColor.NewBackGroundColour());
              sidePanel.add(Instance1.TheSliderClassMethod("Boiler Pressure",200,320));
              sidePanel.add(Instance2.TheSliderClassMethod("Wheel Diameter",60,80));
              sidePanel.add(Instance3.TheSliderClassMethod("Stroke",10,20));
              sidePanel.add(Instance4.TheSliderClassMethod("Piston Rod",2,4));
              sidePanel.add(Instance5.TheSliderClassMethod("Tail Rod",1,3));
              return sidePanel;          
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFormattedTextField;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.NumberFormatter;
    public class TheSliderClass extends JPanel implements ChangeListener
         private static final long serialVersionUID = 1L;
         //Add a formatted text field to supplement the slider.
         public JFormattedTextField textField,textField2;
         public String publicSliderName = "";
         public int fps;
         //And here's the slider.
         public JSlider sliderParameterValue;
         JPanel labelAndTextField,allTogether;
         int TractiveEffort = 0;
         public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
              JPanel allTogether = new JPanel();
              Font font = new Font("palatino linotype regular", Font.BOLD, 12);
              int initialValue = ((minimumValue+maximumValue)/2);
              int tickMarkValue = (maximumValue-minimumValue);
              publicSliderName = sliderName;
              //Create the label.
              JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
              sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
              sliderLabel.setFont(font);
              sliderLabel.setForeground(Color.BLUE);
              //Create the formatted text field and its formatter.
              java.text.NumberFormat numberFormat =
                   java.text.NumberFormat.getIntegerInstance();
              NumberFormatter formatter = new NumberFormatter(numberFormat);
              formatter.setMinimum(new Integer(minimumValue));
              formatter.setMaximum(new Integer(maximumValue));
              textField = new JFormattedTextField(formatter);
              textField.setValue(new Integer(initialValue));
              textField.setColumns(3); //get some space
              textField.setEditable(false);
              textField.setForeground(Color.red);
              textField2 = new JFormattedTextField(formatter);
              textField2.setValue(new Integer(initialValue));
              textField2.setColumns(3); //get some space
              textField2.setEditable(false);
              textField2.setForeground(Color.red);
              //Create the slider.
              sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
              minimumValue, maximumValue, initialValue);
              sliderParameterValue.addChangeListener(this);
              //Turn on labels at major tick marks.
              sliderParameterValue.setMajorTickSpacing(tickMarkValue);
              sliderParameterValue.setMinorTickSpacing(10);
              sliderParameterValue.setPaintTicks(true);
              sliderParameterValue.setPaintLabels(true);
              sliderParameterValue.setBorder(
              BorderFactory.createEmptyBorder(0,0,0,0));
                                                      sliderParameterValue.setBackground(Color.cyan);
              //Create a subpanel for the label and text field.
              JPanel labelAndTextField = new JPanel(); //use FlowLayout
              labelAndTextField.setBackground(Color.cyan);      
              labelAndTextField.add(sliderLabel);
              labelAndTextField.add(textField);
              //Put everything together.
              GridLayout gridThis = new GridLayout();
              gridThis.setColumns(1);
              gridThis.setRows(2);
              allTogether.setLayout(gridThis);
              allTogether.add(labelAndTextField);
              allTogether.add(sliderParameterValue);
              allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
                                                                                    Color.red));
              return allTogether;
         /** Listen to the slider. */
         public void stateChanged(ChangeEvent e)
              JSlider source = (JSlider)e.getSource();
              fps = (int)source.getValue();
              textField.setText(String.valueOf(fps));
              textField2.setText(String.valueOf(fps));
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    public class ExtraPanel extends JPanel
         private static final long serialVersionUID = 1L;
         public JPanel thisPanel;
         public ConstructParametersPanel aPointer;
         public JPanel ExtraPanelMethod()
              thisPanel = new JPanel();
              aPointer = new ConstructParametersPanel();
              GridLayout grid = new GridLayout();
              grid.setColumns(1);
              grid.setHgap(10);
              grid.setRows(6);
              grid.setVgap(5);
              thisPanel.setLayout(grid);
              return thisPanel;

    I don't know if anyone's going to go through all that code...but here's a hint.
    if you have 5 sliders and each one represents a separate variable you're going to use in your calculation...you will need to be able to read the change in THAT PARTICULAR slider to update that particular variable and recalculate.
    So you have a change state listener: The ChangeEvent passed to the
    public void stateChanged(ChangeEvent e) method will have a method called getSource() which you use. However, you aren't figuring out which slider it came from, you're just updating the text areas with info that comes from ANY slider.
    You can use e.getSource() to identify which slider it came from.
    Say you had the following JSlider sl1, sl2, sl3, sl4.
    And each one represents int int1, int2, int3, int4;
    what you do in your stateChanged code say
    if (e.getSource()==sl1){
    int1 = sl1.getValue();
    } else if (e.getSource()==sl2){
      int2 = sl2.getValue();
    } now you have identified which slider was activated. Hope this helps!

  • How to enter values in JList box and JTable ???

    Hi friends...
    i am new to Swing
    SInce i am using Netbeans IDE 5.5
    and there is easy to do swing programming using this IDE
    now i am confused using JTable and JList box
    since i used method Insert in AWT
    but how to add values in LIST BOX ( JList )
    ex.
    JList list = new JList( );
    list.add(mystringvalue, ? );
    here it ask for component so what should i write here..
    when i write here this, gives error.
    what to do to insert string or vector or object in JList
    and to enter value in JTable
    THanks

    hi Ghanshyam,
    i am also new to swing i was just wondering are you using the swing palette to create your interface
    by the look of the code
    JList list = new JList( );
    list.add(mystringvalue, ? );you may not be because every JList is put in a JScrollPane
    but if you do want to do it through the palette there is an option in properties - model which you can uses to add in values.
    and if your looking to get info. from a database look up
    AbstractListModel &
    AbstractTableModel
    the is a lot of info on the internet (example net beans CarTableModel) is a
    good start off
    happy hunting.
    JJ

Maybe you are looking for

  • MacBook Pro (15", Late 2011) Start-up troubles

    I'm having start-up issues with my MacBook Pro. Yesterday night it was working fine and I had no problems at all. I left it to go to sleep as usual, and this morning when I tried to start it up the screen started showing jittering grey pixels and see

  • Rockmelt flash pop out

    using windows XPsp3 goog chrome Rockmelt Flash on hulu works full screen but crashes with popout player setting. any suggestions??

  • I am getting an ITunes.exe system error MSVCR80.dll how can I fix this?

    I am trying to sync my phone to my laptop. ITunes was installed and has been working. All of a sudden I am gettingan ITUNES.EXE system error MSVCR80.dll is missing. I have removed the ITunes from my computer and reinstalled it ... It did not install

  • Issue Opening Photos

    When I go to open photos - they are opening in blue-green-purple colors as if a filter is being applied.  The color pallette is also appearing with the same blue-purple colors.  In the layers pallette - the icon of the image appears in the normal col

  • Can't turn on

    can't turn on! because the connector no good or something else?