简体   繁体   English

JLabel 更改时 GridBagLayout 更改

[英]GridBagLayout changes when JLabel is changed

I want to make an input form and do a validation for the input field when focus is lost.我想制作一个输入表单并在失去焦点时对输入字段进行验证。 If the validation fails, I want to display an error message next to the InputField.如果验证失败,我想在 InputField 旁边显示一条错误消息。

My problem: The input field and it's underline will resize when I change the text of the error JLabel next to it.我的问题:当我更改其旁边的错误 JLabel 的文本时,输入字段及其下划线将调整大小。

Steps to reproduce:重现步骤:

  1. Run main method运行主方法
  2. Enter more than 10 characters in the input field在输入字段中输入超过 10 个字符

--> Current result: Textfield and Seperator resize, Error-JLabel is displayed far right -->当前结果: Textfield 和 Seperator 调整大小,Error-JLabel 显示在最右边

--> Wanted result: Textfield and Seperator remain unchanged, Error JLabel is displayed same place like the test message -->想要的结果: Textfield 和 Seperator 保持不变,Error JLabel 显示在与测试消息相同的位置

I've been struggling with a small issue for days.几天来,我一直在为一个小问题而苦苦挣扎。 Please help!请帮忙!

package View;

import javafx.scene.input.KeyCode;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;

public class PersonDataInput extends JPanel {

    private JLabel emailLabel;
    private JLabel mobileLabel;
    private JLabel nameLabel;
    private JLabel phoneLabel;
    private JLabel surnameLabel;

    private JLabel emailErrorLabel;
    private JLabel mobileErrorLabel;
    private JLabel nameErrorLabel;
    private JLabel phoneErrorLabel;
    private JLabel surnameErrorLabel;

    private JTextField mobileInputField;
    private JTextField nameInputField;
    private JTextField phoneInputField;
    private JTextField surnameInputField;
    private JTextField emailInputField;

    public static void main(String[] args) {

        JFrame frame = new JFrame("Test");
        frame.setContentPane(new PersonDataInput());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public PersonDataInput() {
        Border redline = BorderFactory.createLineBorder(Color.red);
        setBorder(redline);
        //setMaximumSize(new Dimension(200,300));
        initComponents();
    }

    private void initComponents() {


        // <editor-fold defaultstate="collapsed" desc="Components">
        emailLabel = new JLabel("Email");
        mobileLabel = new JLabel("Mobile");
        nameLabel = new JLabel("Name");
        phoneLabel = new JLabel("Phone");
        surnameLabel = new JLabel("Surname");

        emailErrorLabel = new JLabel();
        mobileErrorLabel = new JLabel();
        nameErrorLabel = new JLabel();
        phoneErrorLabel = new JLabel();
        surnameErrorLabel = new JLabel();

        mobileInputField = new JTextField();
        nameInputField = new JTextField();
        phoneInputField = new JTextField();
        surnameInputField = new JTextField();
        emailInputField = new JTextField();

        mobileInputField.setDocument(new JTextFieldLimit(10));
        nameInputField.setDocument(new JTextFieldLimit(10));
        phoneInputField.setDocument(new JTextFieldLimit(10));
        surnameInputField.setDocument(new JTextFieldLimit(10));
        emailInputField.setDocument(new JTextFieldLimit(10));

        mobileInputField.setName("mobileInputField");
        nameInputField.setName("nameInputField");
        phoneInputField.setName("phoneInputField");
        surnameInputField.setName("surnameInputField");
        emailInputField.setName("emailInputField");

        JSeparator seperator1 = new JSeparator();
        JSeparator seperator2 = new JSeparator();
        JSeparator seperator3 = new JSeparator();
        JSeparator seperator4 = new JSeparator();
        JSeparator seperator5 = new JSeparator();
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="EventListeners">

        //...
        //...
        KeyListener keyListener = new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent keyEvent) {
                //...
            }

            @Override
            public void keyPressed(KeyEvent keyEvent) {
                keyPressedMethod(keyEvent);
            }

            @Override
            public void keyReleased(KeyEvent keyEvent) {
                //...
            }
        };

        //...
        FocusListener focusListener = new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent focusEvent) {
                focusGainedMethod(focusEvent);
            }

            @Override
            public void focusLost(FocusEvent focusEvent) {
                focusLostMethod(focusEvent);
            }
        };

        mobileInputField.addFocusListener(focusListener);
        mobileInputField.addKeyListener(keyListener);

        nameInputField.addFocusListener(focusListener);
        nameInputField.addKeyListener(keyListener);

        phoneInputField.addFocusListener(focusListener);
        phoneInputField.addKeyListener(keyListener);

        surnameInputField.addFocusListener(focusListener);
        surnameInputField.addKeyListener(keyListener);

        emailInputField.addFocusListener(focusListener);
        emailInputField.addKeyListener(keyListener);
        // </editor-fold>s

        // <editor-fold defaultstate="collapsed" desc="Styles">
        mobileInputField.setBorder(null);
        nameInputField.setBorder(null);
        phoneInputField.setBorder(null);
        surnameInputField.setBorder(null);
        emailInputField.setBorder(null);
        setBackground(new java.awt.Color(255, 255, 255));
        //</editor-fold>

        // <editor-fold defaultstate="collapsed" desc="Layout">
        GridBagLayout gridBagLayout = new GridBagLayout();
        setLayout(gridBagLayout);


        // this component is needed to anchor all components within the JPanel to the upper right corner
        GridBagConstraints horizontalFill = new GridBagConstraints();
        horizontalFill.anchor = GridBagConstraints.NORTHWEST;
        horizontalFill.fill = GridBagConstraints.HORIZONTAL;
        horizontalFill.gridwidth=4;
        horizontalFill.weightx = 1;
        add(Box.createHorizontalGlue(), horizontalFill);

        add(nameLabel,
                new GBC(0, 0)
                        .setSpan(1,1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(nameInputField,
                new GBC(0, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        nameErrorLabel.setText("Test: The error message shall be displayed here.");
        add(nameErrorLabel,
                new GBC(1, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(200,0)
                        .setAnchor(GBC.NORTHWEST)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(seperator1,
                new GBC(0, 2)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0.0, 1.0));
/*
        add(surnameLabel,
                new GBC(0, 3)
                        .setSpan(1,1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(surnameInputField,
                new GBC(0, 4)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(seperator2,
                new GBC(0, 5)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(emailLabel,
                new GBC(0, 6)
                        .setSpan(1,1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(emailInputField,
                new GBC(0, 7)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(seperator3,
                new GBC(0, 8)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(phoneLabel,
                new GBC(0, 9)
                        .setSpan(1,1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(phoneInputField,
                new GBC(0, 10)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(seperator4,
                new GBC(0, 11)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(mobileLabel,
                new GBC(0, 12)
                        .setSpan(1,1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(mobileInputField,
                new GBC(0, 13)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setIpad(100,0)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

        add(seperator5,
                new GBC(0, 14)
                        .setSpan(2, 1)
                        .setFill(GBC.HORIZONTAL)
                        .setInsets(5,10,0,0)
                        .setWeight(0, 1.0));

 */




    }// </editor-fold>
        //</editor-fold>



    private void keyPressedMethod(KeyEvent keyEvent) {
        String component = keyEvent.getComponent().getName();

        if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
            switch (component) {
                case "nameInputField":
                    surnameInputField.requestFocus();
                    break;
                case "surnameInputField":
                    emailInputField.requestFocus();
                    break;
                case "emailInputField":
                    phoneInputField.requestFocus();
                    break;
                case "phoneInputField":
                    mobileInputField.requestFocus();
                    break;
                case "mobileInputField":
                    this.requestFocus();
                default:
                    break;
            }

        }

        // todo: field validation anpassen, Email Validation,
        else {
            switch (component) {
                case "nameInputField":
                    if (nameInputField.getText().length() == 10) {
                        nameErrorLabel.setText("Max. 10 characters.");
                    }
                    break;
                case "surnameInputField":
                    if (surnameInputField.getText().length() == 10) {
                        surnameErrorLabel.setText("Max. 10 characters.");
                    }
                    break;
                case "emailInputField":
                    if (emailInputField.getText().length() == 10) {
                        emailErrorLabel.setText("Max. 10 characters.");
                    }
                    break;
                case "phoneInputField":
                    if (phoneInputField.getText().length() == 10) {
                        phoneErrorLabel.setText("Max. 10 characters.");
                    }
                    break;
                case "mobileInputField":
                    if (mobileInputField.getText().length() == 10) {
                        mobileErrorLabel.setText("Max. 10 characters.");
                    }
                default:
                    break;
            }

        }
    }

    private void focusLostMethod(FocusEvent focusEvent) {
        String component = focusEvent.getComponent().getName();
        switch (component) {
            case "nameInputField":
                nameLabel.setForeground(Color.black);
                nameErrorLabel.setText("");
                break;
            case "surnameInputField":
                surnameLabel.setForeground(Color.black);
                break;
            case "emailInputField":
                emailLabel.setForeground(Color.black);
                break;
            case "phoneInputField":
                phoneLabel.setForeground(Color.black);
                break;
            case "mobileInputField":
                mobileLabel.setForeground(Color.black);
            default:
                break;
        }
    }

    private void focusGainedMethod(FocusEvent focusEvent) {
        String component = focusEvent.getComponent().getName();
        switch (component) {
            case "nameInputField":
                nameLabel.setForeground(new Color(51, 102, 255));
                break;
            case "surnameInputField":
                surnameLabel.setForeground(new Color(51, 102, 255));
                break;
            case "emailInputField":
                emailLabel.setForeground(new Color(51, 102, 255));
                break;
            case "phoneInputField":
                phoneLabel.setForeground(new Color(51, 102, 255));
                break;
            case "mobileInputField":
                mobileLabel.setForeground(new Color(51, 102, 255));
            default:
                break;
        }
    }


    //Class to set limits for JTextFields
    class JTextFieldLimit extends PlainDocument {
        private int limit;

        JTextFieldLimit(int limit) {
            super();
            this.limit = limit;
        }

        JTextFieldLimit(int limit, boolean upper) {
            super();
            this.limit = limit;
        }

        public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
            if (str == null)
                return;

            if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);
            }
        }
    }

}


GridBagLayout will only take into consideration visible components. GridBagLayout 只会考虑可见组件。 If the JLabel has no text, then it's size will be 0x0 and the GridBagLayout will respond accordingly.如果 JLabel 没有文本,那么它的大小将为 0x0,并且 GridBagLayout 将做出相应的响应。 "IF" the error message is static, you could simply set it's text color to be the same as the background color of the container and just "fake" it. “如果”错误消息是 static,您可以简单地将其文本颜色设置为与容器的背景颜色相同,然后“伪造”它。 Also - KeyListeners are probably not what you want to use – MadProgrammer 9 hours ago另外 - KeyListeners 可能不是你想要使用的 - MadProgrammer 9 小时前

Thanks this helped!谢谢这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM