Я хочу создать форму ввода и выполнить проверку поля ввода при потере фокуса. Если проверка не пройдена, я хочу отобразить сообщение об ошибке рядом с InputField.
Моя проблема: Поле ввода и его подчеркивание изменится, когда я изменю текст ошибки JLabel далее
Шаги для воспроизведения:
- Запуск основного метода
- Введите более 10 символов в поле ввода
-> Текущий результат: Изменение размера текстового поля и разделителя, ошибка-JLabel отображается в крайнем правом углу
-> Требуемый результат: Текстовое поле и разделитель остаются без изменений, ошибка JLabel отображается в том же месте, что и тестовое сообщение
Я боролся с небольшой проблемой в течение нескольких дней. Пожалуйста, помогите!
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);
}
}
}
}