Swing: JFormattedTextField set to numbers only using Netbeans
Asked Answered
U

1

5

I've got a little problem with JFormattedTextField: I want to set the formatted text fields to numbers only. I've created one with Swing interface on NetBeans.

My code is as follows:

package SerasApp;

import static java.lang.System.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;

/**
 * @author adam
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }
    //set position of label to be the center of the frame
    public void PositionHiSera()
    {
        //find position of jpanel
        int FrameHeight = this.Intro.getHeight();
        int FrameWidth = this.Intro.getWidth();
        int LabelSize[] = new int[2];
        LabelSize[0] = HiSera.getWidth();
        LabelSize[1] = HiSera.getHeight();
        out.println(LabelSize[0]);
        out.println(LabelSize[1]);
        int Origin[] = new int[2];
        Origin[1] = (FrameHeight/2)-(LabelSize[0]/2);
        Origin[0] = (FrameWidth/2)-(LabelSize[1]/2);
        //set label origin
        HiSera.setLocation(Origin[1], Origin[0]);
    }


    public void HumidityLevel()
    {
        NumberFormat a = NumberFormat.getNumberInstance();
        NumberFormatter b = new NumberFormatter(a);
        DefaultFormatterFactory c = new DefaultFormatterFactory(b);
        humidityLevel.setFormatterFactory(c);
    }
    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        MainDisplayFrame = new javax.swing.JPanel();
        Intro = new javax.swing.JPanel();
        HiSera = new javax.swing.JLabel();
        MainMenu = new javax.swing.JPanel();
        WeatherOptions = new javax.swing.JPanel();
        sunny = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        humidityLevel = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        MainDisplayFrame.setLayout(new java.awt.CardLayout());

        Intro.setMaximumSize(new java.awt.Dimension(30000, 30000));

        HiSera.setText("Hi Sera");

        javax.swing.GroupLayout IntroLayout = new javax.swing.GroupLayout(Intro);
        Intro.setLayout(IntroLayout);
        IntroLayout.setHorizontalGroup(
            IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(IntroLayout.createSequentialGroup()
                .addGap(209, 209, 209)
                .addComponent(HiSera)
                .addContainerGap(243, Short.MAX_VALUE))
        );
        IntroLayout.setVerticalGroup(
            IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(IntroLayout.createSequentialGroup()
                .addGap(225, 225, 225)
                .addComponent(HiSera)
                .addContainerGap(258, Short.MAX_VALUE))
        );

        MainDisplayFrame.add(Intro, "card2");

        javax.swing.GroupLayout MainMenuLayout = new javax.swing.GroupLayout(MainMenu);
        MainMenu.setLayout(MainMenuLayout);
        MainMenuLayout.setHorizontalGroup(
            MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, Short.MAX_VALUE, Short.MAX_VALUE)
        );
        MainMenuLayout.setVerticalGroup(
            MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
        );

        MainDisplayFrame.add(MainMenu, "card2");

        WeatherOptions.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                WeatherOptionsFocusGained(evt);
            }
        });

        sunny.setText("Sunny");
        sunny.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sunnyActionPerformed(evt);
            }
        });

        jButton2.setText("Overcast");

        jButton3.setText("Rainy");

        jLabel1.setText("Humidity Level");

        javax.swing.GroupLayout WeatherOptionsLayout = new javax.swing.GroupLayout(WeatherOptions);
        WeatherOptions.setLayout(WeatherOptionsLayout);
        WeatherOptionsLayout.setHorizontalGroup(
            WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(WeatherOptionsLayout.createSequentialGroup()
                .addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(WeatherOptionsLayout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addComponent(sunny)
                        .addGap(75, 75, 75))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, WeatherOptionsLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(36, 36, 36)))
                .addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(WeatherOptionsLayout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(69, 69, 69)
                        .addComponent(jButton3)))
                .addContainerGap(99, Short.MAX_VALUE))
        );
        WeatherOptionsLayout.setVerticalGroup(
            WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(WeatherOptionsLayout.createSequentialGroup()
                .addGap(225, 225, 225)
                .addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sunny)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(87, 87, 87)
                .addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(132, Short.MAX_VALUE))
        );

        MainDisplayFrame.add(WeatherOptions, "card2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {                                       
        // TODO add your handling code here:
        PositionHiSera();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        //make Intro Disappear and make Weather Options Appear
        WeatherOptions.setVisible(true);
        Intro.setVisible(false);
        HumidityLevel();
        out.println("tests");
    }                                      

    private void sunnyActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void WeatherOptionsFocusGained(java.awt.event.FocusEvent evt) {                                           
        // TODO add your handling code here:

    }                                          
        /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel HiSera;
    private javax.swing.JPanel Intro;
    private javax.swing.JPanel MainDisplayFrame;
    private javax.swing.JPanel MainMenu;
    private javax.swing.JPanel WeatherOptions;
    private javax.swing.JFormattedTextField humidityLevel;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton sunny;
    // End of variables declaration                   
}

I've tried also to set a humidityLevel to new formatted text field to no avail.

Mainly it's this bit of code:

public void HumidityLevel()
{
    NumberFormat a = NumberFormat.getNumberInstance();
    NumberFormatter b = new NumberFormatter(a);
    DefaultFormatterFactory c = new DefaultFormatterFactory(b);
    humidityLevel.setFormatterFactory(c);
}

and this bit:

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {                                       
    // TODO add your handling code here:
    PositionHiSera();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    //make Intro Disappear and make Weather Options Appear
    WeatherOptions.setVisible(true);
    Intro.setVisible(false);
    HumidityLevel();
    out.println("tests");
}                                      

I also don't want to use a JTextField because I want to learn how to use JFormattedTextField.

Unclassified answered 10/12, 2014 at 17:33 Comment(2)
all good ideas are killed by using Thread.sleep(1000); in Focus, never to use Thread.sleep(int); in Java, nor in SwingProfitable
Thanks mkorbel, I'm looking into it nowUnclassified
D
10

I want to set the formatted text fields to numbers only.

Using the Design view, right click over the formatted text field and choose Properties option. Then look for formatterFactory property:

JFormattedTextField properties

If you try to edit this property, the following dialog will show up. Choose integer default option under number category:

FormatterFactory property

That's it, your text field will be initialized using NumberFormat.getIntegerInstance(). If you inspect the generated source code you'll see something like this:

    jFormattedTextField1 = new javax.swing.JFormattedTextField();
    jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));

Off-topic

As @mKorbel pointed out, using Thread.sleep() is a bad idea and will block the Event Dispatch Thread (EDT) which is a single and special thread where Swing components creation / update should be performed and event handling is processed. If this thread is blocked then your GUI won't be able to repaint itself and will "freeze". In this case you should consider use a Swing Timer instead. See Concurrency in Swing for further details.

Diestock answered 11/12, 2014 at 12:7 Comment(1)
You are welcome :) Please don't forget to mark this answer as accepted in order to help future visitors: What should I do when someone answers my question?Diestock

© 2022 - 2024 — McMap. All rights reserved.