【问题标题】:Adding constraint on JTextField在 JTextField 上添加约束
【发布时间】:2013-10-15 10:28:33
【问题描述】:

我正在制作一个 GUI,其中我使用了许多 JTextfield 实例来输入用户的输入。我想指定这个特定的(例如:用户名)文本字段是必须填写的。我该怎么做?

 JLabel label_2 = new JLabel("User Name");
            label_2.setBounds(23, 167, 126, 21);
            panel_1.add(label_2);

    textField_2 = new JTextField();
            textField_2.setColumns(10);
            textField_2.setBounds(178, 129, 210, 20);
        panel_1.add(textField_2);

【问题讨论】:

  • 我猜你需要检查提交操作上的必填字段并检查它们是否包含值
  • 您如何处理在所有文本字段中输入的值?
  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) Java GUI 可能必须在多个平台、不同的屏幕分辨率和使用不同的 PLAF 上工作。因此,它们不利于组件的精确放置。要为强大的 GUI 组织组件,请改用布局管理器或 combinations of them,以及 white space 的布局填充和边框。 3)问题中空白图片的目的是什么?

标签: java swing constraints jtextfield


【解决方案1】:

【讨论】:

    【解决方案2】:

    当用户完成文本字段时,例如当他提交数据时,您可以验证文本字段以查看它是否为空。

    例如,如果您使用的是提交按钮。

    submitButton.addActionLister(new ActionListner(){
        public void actionPerformed(ActionEvent ae){
           if(textField.getText().length() == 0){
                //notify user that mandatory field is empty.
           }
    
           //other validation checks.
        }  
    }
    

    您可以向文本字段添加焦点侦听器。根据约束,每个字段都可以有不同的焦点丢失实现。

     textfield.addFocusListener(new FocusListener(){
               @Override
              public void focusGained(FocusEvent fe) {
                 // do whatever want like highlighting the field
              }
    
              @Override
              public void focusLost(FocusEvent fe) {
                  //check for constraint as the user is done with this field.
              }
     });
    

    【讨论】:

      【解决方案3】:
      JLabel label_2 = new JLabel("User Name");
      label_2.setBounds(23, 167, 126, 21);
      panel_1.add(label_2);
      
      textField_2 = new JTextField();
      textField_2.setColumns(10);
      textField_2.setBounds(178, 129, 210, 20);
      panel_1.add(textField_2);
      
      submit.addActionListener(this);
      
      }
      
        public void actionPerformed(ActionEvent e)
         {
            //check the text field
             if(textField_2.getText().length()==0)
                    {
                         //user_name not set
                    }
             else
                    {
                     //user_name is set
                    }
      
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2014-09-06
        • 2015-05-19
        • 2015-11-16
        • 2014-04-09
        • 2021-06-14
        • 1970-01-01
        相关资源
        最近更新 更多