java Swing:仅使用 Netbeans 将 JFormattedTextField 设置为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27407319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:46:28  来源:igfitidea点击:

Swing: JFormattedTextField set to numbers only using Netbeans

javaswingnetbeansjformattedtextfieldmatisse

提问by Adam Dong

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.

我有一个小问题JFormattedTextField:我想将格式化的文本字段设置为仅数字。我在 NetBeans 上创建了一个带有 Swing 接口的程序。

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 humidityLevelto new formatted text field to no avail.

我也试过设置一个humidityLevel新的格式化文本字段无济于事。

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 JTextFieldbecause I want to learn how to use JFormattedTextField.

我也不想使用 aJTextField因为我想学习如何使用JFormattedTextField.

回答by dic19

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

我只想将格式化文本字段设置为数字。

Using the Design view, right click over the formatted text field and choose Propertiesoption. Then look for formatterFactoryproperty:

使用设计视图,右键单击格式化文本字段并选择Properties选项。然后寻找formatterFactory属性:

JFormattedTextField properties

JFormattedTextField 属性

If you try to edit this property, the following dialog will show up. Choose integer defaultoption under numbercategory:

如果您尝试编辑此属性,将显示以下对话框。选择类别integer default下的选项number

FormatterFactory property

FormatterFactory 属性

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:

就是这样,您的文本字段将使用NumberFormat.getIntegerInstance()进行初始化。如果您检查生成的源代码,您将看到如下内容:

    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 Timerinstead. See Concurrency in Swingfor further details.

正如@mKorbel 指出的那样,使用Thread.sleep()是一个坏主意,它会阻塞事件调度线程 (EDT),它是一个单一的特殊线程,应该在其中执行 Swing 组件的创建/更新并处理事件处理。如果此线程被阻塞,那么您的 GUI 将无法重新绘制自身并将“冻结”。在这种情况下,您应该考虑改用Swing Timer。有关更多详细信息,请参阅Swing 中的并发