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

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

我的代码如下:

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                   
}

我也尝试将wetLevel设置为新的格式化文本字段无济于事.

主要是这段代码:

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

这一点:

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");
}

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

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

使用“设计”视图,右键单击格式化文本字段,然后选择“属性”选项.然后查找formatterFactory属性:

如果您尝试编辑此属性,将显示以下对话框.在数字类别下选择整数默认选项:

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

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

无关

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

相关文章
相关标签/搜索