Попытка использовать Tab для перехода между JTextFields по вертикали (используя Custom FocusTraversalPolicy) - PullRequest
0 голосов
/ 02 апреля 2020

Это мой первый симулятор базы данных GUI, мне трудно перемещаться с помощью TAB по текстовым полям пользовательского ввода. Я хочу перемещаться в следующем порядке: от имени до первой фамилии, до второй фамилии, возраста, номера телефона, адреса и, наконец, электронной почты. Честно говоря, я просто скопировал код для пользовательской политики обхода фокуса и надеялся, что это сработает, но это не так. Я не знаю, должен ли я вообще вызывать это в классе Listener или это избыточно?

Вот код, извините, он так долго = S (пропущены библиотеки для соответствия максимальной длине и длине записи):

publi c class UserFormNew {

private JTextField idtf;
private JTextField nametf;
private JTextField ln1tf;
private JTextField ln2tf;
private JTextField agetf;
private JTextField pntf;
private JTextField addresstf;
private JTextField emtf;
private JTable t;
private DefaultTableModel dtm;
private JTableHeader header;
private int idCount = 0;
private int rowSelected;
private boolean ed = false;
private String[] selRowInfoGotten;
private List<Component> compList = new ArrayList<Component>();
private JPanel dataIn;

public UserFormNew() {

    // Containers
    JFrame mainF = new JFrame();
    JPanel mainP = new JPanel(new BorderLayout(10, 5));
    dataIn = new JPanel(new GridBagLayout());
    JPanel table = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
    JPanel buttons = new JPanel(new BorderLayout(20, 10));

    // Fonts
    Font plain = new Font("Tahoma", Font.PLAIN, 12);
    Font plaint = new Font("Tahoma", Font.PLAIN, 11);
    Font bold12 = new Font("Tahoma", Font.BOLD, 12);

    // Data-In
    GridBagConstraints gbc = new GridBagConstraints();
    Insets topLeftLabel = new Insets(20, 20, 2, 2);
    Insets midLeftLabel = new Insets(2, 20, 2, 2);
    Insets botLeftLabel = new Insets(2, 20, 20, 2);
    Insets topMidTF = new Insets(20, 2, 2, 20);
    Insets midMidTF = new Insets(2, 2, 2, 20);
    Insets botMidTF = new Insets(2, 2, 20, 20);
    Insets topMidLabel = new Insets(20, 30, 2, 2);
    Insets midMidLabel = new Insets(2, 30, 2, 2);
    Insets botMidLabel = new Insets(2, 30, 20, 2);
    Insets topRightInsets = new Insets(20, 2, 2, 20);
    Insets midRightInsets = new Insets(2, 2, 2, 20);
    Insets botRightInsets = new Insets(2, 2, 10, 20);

    JLabel id = new JLabel("Id");
    id.setFont(bold12);
    gbc.insets = topLeftLabel;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(id, gbc);

    JLabel name = new JLabel("Name");
    name.setFont(bold12);
    gbc.insets = midLeftLabel;
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(name, gbc);

    JLabel ln1 = new JLabel("1\u00B0 Lastname");
    ln1.setFont(bold12);
    gbc.insets = midLeftLabel;
    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(ln1, gbc);

    JLabel ln2 = new JLabel("2\u00B0 Lastname");
    ln2.setFont(bold12);
    gbc.insets = botLeftLabel;
    gbc.gridx = 0;
    gbc.gridy = 3;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(ln2, gbc);

    JLabel age = new JLabel("Age");
    age.setFont(bold12);
    gbc.insets = topMidLabel;
    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(age, gbc);

    JLabel pn = new JLabel("Phone Number");
    pn.setFont(bold12);
    gbc.insets = midMidLabel;
    gbc.gridx = 2;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(pn, gbc);

    JLabel address = new JLabel("Address");
    address.setFont(bold12);
    gbc.insets = midMidLabel;
    gbc.gridx = 2;
    gbc.gridy = 2;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(address, gbc);

    JLabel em = new JLabel("E-Mail");
    em.setFont(bold12);
    gbc.insets = botMidLabel;
    gbc.gridx = 2;
    gbc.gridy = 3;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(em, gbc);

    JLabel emptyTop = new JLabel("         ");
    gbc.insets = topRightInsets;
    gbc.gridx = 5;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(emptyTop, gbc);

    JLabel emptyMid1 = new JLabel("         ");
    gbc.insets = midRightInsets;
    gbc.gridx = 5;
    gbc.gridy = 1;
    gbc.gridwidth = 2;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(emptyMid1, gbc);

    JLabel emptyMid2 = new JLabel("         ");
    gbc.insets = midRightInsets;
    gbc.gridx = 5;
    gbc.gridy = 2;
    gbc.gridwidth = 2;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(emptyMid2, gbc);

    JLabel emptyBot = new JLabel("         ");
    gbc.insets = botRightInsets;
    gbc.gridx = 5;
    gbc.gridy = 3;
    gbc.gridwidth = 2;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(emptyBot, gbc);

    idtf = new JTextField("");
    idtf.setFont(plain);
    idtf.setEditable(false);
    idtf.setHorizontalAlignment(JTextField.RIGHT);
    idtf.addKeyListener(new NumericList());
    gbc.insets = topMidTF;
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.weightx = 0.4;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(idtf, gbc);

    nametf = new JTextField("");
    nametf.setFont(plain);
    nametf.setEditable(true);
    nametf.addKeyListener(new AlphabeticList());
    gbc.insets = midMidTF;
    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 0.4;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(nametf, gbc);

    ln1tf = new JTextField("");
    ln1tf.setFont(plain);
    ln1tf.setEditable(true);
    ln1tf.addKeyListener(new AlphabeticList());
    gbc.insets = midMidTF;
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 1;
    gbc.weightx = 0.4;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(ln1tf, gbc);

    ln2tf = new JTextField("");
    ln2tf.setFont(plain);
    ln2tf.setEditable(true);
    ln2tf.addKeyListener(new AlphabeticList());
    gbc.insets = botMidTF;
    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.gridwidth = 1;
    gbc.weightx = 0.4;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(ln2tf, gbc);

    agetf = new JTextField("");
    agetf.setFont(plain);
    agetf.setEditable(true);
    agetf.addKeyListener(new NumericList());
    gbc.insets = topMidTF;
    gbc.gridx = 3;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(agetf, gbc);

    pntf = new JTextField("");
    pntf.setFont(plain);
    pntf.setEditable(true);
    pntf.addKeyListener(new PhoneList());
    gbc.insets = midMidTF;
    gbc.gridx = 3;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.weightx = 0.1;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(pntf, gbc);

    addresstf = new JTextField("");
    addresstf.setFont(plain);
    addresstf.setEditable(true);
    addresstf.addKeyListener(new AddressList());
    gbc.insets = midMidTF;
    gbc.gridx = 3;
    gbc.gridy = 2;
    gbc.gridwidth = 3;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(addresstf, gbc);

    emtf = new JTextField("");
    emtf.setFont(plain);
    emtf.setEditable(true);
    emtf.addKeyListener(new EmailList());
    gbc.insets = botMidTF;
    gbc.gridx = 3;
    gbc.gridy = 3;
    gbc.gridwidth = 3;
    gbc.weightx = 0.7;
    gbc.weighty = 0.2;
    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    dataIn.add(emtf, gbc);

    // My Traversal Policy
    compList.add(nametf);
    compList.add(ln1tf);
    compList.add(ln2tf);
    compList.add(agetf);
    compList.add(pntf);
    compList.add(addresstf);
    compList.add(emtf);
    dataIn.setFocusTraversalPolicy(new MyFocusTraversalPolicy());

    // Table
    String[][] data = {};
    String[] headers = { "Id", "Name", "First Lastname", "Second Lastname", "Age", "Phone Number", "Address",
            "E-Mail" };

    dtm = new DefaultTableModel(data, headers);
    t = new JTable(dtm);
    t.setFont(plaint);
    header = t.getTableHeader();
    header.setFont(bold12);

    // Table Design
    int[] columnsWidth = { 65, 120, 120, 120, 40, 100, 300, 220 };
    int i = 0;
    for (int width : columnsWidth) {
        TableColumn column = t.getColumnModel().getColumn(i++);
        column.setMinWidth(width);
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
    }

    // Columns Text Alignment
    DefaultTableCellRenderer rendererLeft = new DefaultTableCellRenderer();
    DefaultTableCellRenderer rendererCenter = new DefaultTableCellRenderer();
    TableColumnModel colModel = t.getColumnModel();
    TableColumn[] col = new TableColumn[t.getColumnCount()];

    for (int j = 0; j < t.getColumnCount(); j++) {
        col[j] = colModel.getColumn(j);
        switch (j) {
            case 0: {
                rendererCenter.setHorizontalAlignment(JLabel.CENTER);
                col[j].setCellRenderer(rendererCenter);
            }
                break;
            case 1: {
                rendererLeft.setHorizontalAlignment(JLabel.LEFT);
                col[j].setCellRenderer(rendererLeft);
            }
                break;
            case 2: {
                rendererLeft.setHorizontalAlignment(JLabel.LEFT);
                col[j].setCellRenderer(rendererLeft);
            }
                break;
            case 3: {
                rendererLeft.setHorizontalAlignment(JLabel.LEFT);
                col[j].setCellRenderer(rendererLeft);
            }
                break;
            case 4: {
                rendererCenter.setHorizontalAlignment(JLabel.CENTER);
                col[j].setCellRenderer(rendererCenter);
            }
                break;
            case 5: {
                rendererCenter.setHorizontalAlignment(JLabel.CENTER);
                col[j].setCellRenderer(rendererCenter);
            }
                break;
            case 6: {
                rendererLeft.setHorizontalAlignment(JLabel.LEFT);
                col[j].setCellRenderer(rendererLeft);
            }
                break;
            case 7: {
                rendererLeft.setHorizontalAlignment(JLabel.LEFT);
                col[j].setCellRenderer(rendererLeft);
            }
                break;
        }
    }

    // Insert table into ScrollPane
    JScrollPane sp = new JScrollPane(t);
    table.add(sp);
    t.setPreferredScrollableViewportSize(new Dimension(1085, 230));

    // Buttons
    JPanel eastP = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

    JButton save = new JButton("Save");
    JButton del = new JButton("Delete");
    JButton edit = new JButton("Edit");
    JButton clr = new JButton("Clear");

    save.setFont(bold12);
    del.setFont(bold12);
    edit.setFont(bold12);
    clr.setFont(bold12);

    save.addActionListener(new Save());
    del.addActionListener(new Delete());
    edit.addActionListener(new Edit());
    clr.addActionListener(new Clear());
    t.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            rowSelected = t.getSelectedRow();
        }
    });

    eastP.add(save);
    eastP.add(del);
    eastP.add(edit);
    eastP.add(clr);
    buttons.add(eastP, BorderLayout.EAST);

    // Add to main
    mainP.add(dataIn, BorderLayout.NORTH);
    mainP.add(table, BorderLayout.CENTER);
    mainP.add(buttons, BorderLayout.SOUTH);
    mainF.setContentPane(mainP);
    mainF.pack();
    mainF.setVisible(true);
    mainF.setResizable(false);
    mainF.setLocationRelativeTo(null);
    mainF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new UserFormNew();
        }
    });

}

//Focus Traversal Policy Custom Class
private class MyFocusTraversalPolicy extends FocusTraversalPolicy {

    public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
        int currentPosition = compList.indexOf(aComponent);
        currentPosition = (currentPosition + 1) % compList.size();
        return (Component) compList.get(currentPosition);
    }

    public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
        int currentPosition = compList.indexOf(aComponent);
        currentPosition = (compList.size() + currentPosition - 1) % compList.size();
        return (Component) compList.get(currentPosition);
    }

    public Component getFirstComponent(Container cntnr) {
        return (Component) compList.get(0);
    }

    public Component getLastComponent(Container cntnr) {
        return (Component) compList.get(compList.size() - 1);
    }

    public Component getDefaultComponent(Container cntnr) {
        return (Component) compList.get(0);
    }

}

// Listener Classes
public class Save implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        String name = nametf.getText();
        String ln1 = ln1tf.getText();
        String ln2 = ln2tf.getText();
        String age = agetf.getText();
        String pn = pntf.getText();
        String address = addresstf.getText();
        String em = emtf.getText();

        // Autogenerate id
        idCount++;

        // Data Into Table
        if (idCount == 0) {
            t.setValueAt(Integer.toString(idCount), 0, 0);
            t.setValueAt(name, 0, 1);
            t.setValueAt(ln1, 0, 2);
            t.setValueAt(ln2, 0, 3);
            t.setValueAt(age, 0, 4);
            t.setValueAt(pn, 0, 5);
            t.setValueAt(address, 0, 6);
            t.setValueAt(em, 0, 7);
        } else if (ed == true) {
            t.setValueAt(name, rowSelected, 1);
            t.setValueAt(ln1, rowSelected, 2);
            t.setValueAt(ln2, rowSelected, 3);
            t.setValueAt(age, rowSelected, 4);
            t.setValueAt(pn, rowSelected, 5);
            t.setValueAt(address, rowSelected, 6);
            t.setValueAt(em, rowSelected, 7);
            ed = false;
        } else {
            String[] newRow = { Integer.toString(idCount), name, ln1, ln2, age, pn, address, em };
            dtm.addRow(newRow);
        }

        idtf.setText("");
        nametf.setText("");
        ln1tf.setText("");
        ln2tf.setText("");
        agetf.setText("");
        pntf.setText("");
        addresstf.setText("");
        emtf.setText("");

    }

}

public class Delete implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        dtm.removeRow(rowSelected);
    }

}

public class Edit implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        ed = true;
        selRowInfoGotten = new String[t.getColumnCount()];

        for (int i = 0; i < t.getColumnCount(); i++) {
            selRowInfoGotten[i] = (String) t.getValueAt(rowSelected, i);
        }

        idtf.setText(selRowInfoGotten[0]);
        nametf.setText(selRowInfoGotten[1]);
        ln1tf.setText(selRowInfoGotten[2]);
        ln2tf.setText(selRowInfoGotten[3]);
        agetf.setText(selRowInfoGotten[4]);
        pntf.setText(selRowInfoGotten[5]);
        addresstf.setText(selRowInfoGotten[6]);
        emtf.setText(selRowInfoGotten[7]);

    }

}

public class Clear implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        if (ed == false) {
            idtf.setText("");
            nametf.setText("");
            ln1tf.setText("");
            ln2tf.setText("");
            agetf.setText("");
            pntf.setText("");
            addresstf.setText("");
            emtf.setText("");
        } else {
            nametf.setText("");
            ln1tf.setText("");
            ln2tf.setText("");
            agetf.setText("");
            pntf.setText("");
            addresstf.setText("");
            emtf.setText("");
        }

    }

}

public class AlphabeticList implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
        // Letters only
        char testChar = e.getKeyChar();
        if (!Character.isAlphabetic(testChar)) {
            e.consume();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {   
        if (e.getKeyChar() == KeyEvent.VK_TAB) {
            nametf.getFocusTraversalPolicy();
            ln1tf.getFocusTraversalPolicy();
            ln2tf.getFocusTraversalPolicy();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {    }

}

public class NumericList implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
        // Numbers only
        char testChar = e.getKeyChar();
        if (!Character.isDigit(testChar)) {
            e.consume();
        }
        // 3-digit ages max
        String ageText = agetf.getText();
        int ageLength = ageText.length();
        if (ageLength >= 3) {
            e.consume();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_TAB) {
            agetf.getFocusTraversalPolicy();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

}

public class AddressList implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_TAB) {
            addresstf.getFocusTraversalPolicy();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

}

public class PhoneList implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
        // Numbers only
        char testChar = e.getKeyChar();
        if (!Character.isDigit(testChar)) {
            e.consume();
        }
        String pnText = pntf.getText();
        int pnLength = pnText.length();
        // Add hyphens
        if (pnLength == 3 || pnLength == 7) {
            pntf.setText(pnText + "-");
        }
        // 10-digit numbers
        if (pnLength >= 12) {
            e.consume();
        }
        // Erase even hyphens
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            String pnTxt = pntf.getText();
            int start = 0;
            int end = pnLength - 2;
            String pnErased = pnTxt.substring(start, end);
            System.out.println(
                    "PNLength: " + pnLength + ", Start: " + start + ", End: " + end + ", PNErased: " + pnErased);
            pntf.setText(pnErased);
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_TAB) {
            pntf.getFocusTraversalPolicy();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

}

public class EmailList implements KeyListener {

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_TAB) {
            emtf.getFocusTraversalPolicy();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

}

}

1 Ответ

0 голосов
/ 02 апреля 2020

К счастью, у меня есть гораздо меньший пример пользовательской формы, где я добавил политику обхода фокуса.

Код состоит из двух частей. Пока я создаю GUI, я устанавливаю свою политику обхода фокуса. Я поместил все поля JTextFields в список в том порядке, в котором я хочу их обойти. Каждое редактируемое поле в JPanel должно быть включено в этот список.

Я также написал класс, который расширяет FocusTraversalPolicy. Я сделал это частным и включил его в класс представления. Это кажется подходящим местом для занятий. Вы можете поместить его в отдельный файл, если хотите.

Вот код. Вы можете скомпилировать его, запустить и увидеть, что табуляция через форму следует за столбцами. Это то, что мы хотели бы назвать минимальным воспроизводимым примером .

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

public class UserForm {

    // top, left, bottom, right
    private static final Insets topInsets = new Insets(10, 10, 10, 10);
    private static final Insets topCenterInsets = new Insets(10, 0, 10, 10);
    private static final Insets middleInsets = new Insets(0, 10, 10, 10);
    private static final Insets middleCenterInsets = new Insets(0, 0, 10, 10);

    public UserForm() {

        JFrame frame = new JFrame("User Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Miscelaneous
        Font plain = new Font("Tahoma", Font.PLAIN, 12);
        Font bold11 = new Font("Tahoma", Font.BOLD, 11);
        Font bold12 = new Font("Tahoma", Font.BOLD, 12);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());

        int gridy = 0;

        // Data-In Form Components
        JLabel idl = new JLabel("Id:");
        idl.setFont(bold12);
        addComponent(mainPanel, idl, 0, gridy, 1, 1, topInsets, GridBagConstraints.LINE_START, GridBagConstraints.NONE);

        JTextField idtf = new JTextField(40);
        idtf.setFont(plain);
        addComponent(mainPanel, idtf, 1, gridy, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel agl = new JLabel("Age:");
        agl.setFont(bold12);
        addComponent(mainPanel, agl, 2, gridy, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField agtf = new JTextField(40);
        agtf.setFont(plain);
        addComponent(mainPanel, agtf, 3, gridy++, 1, 1, topCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel namel = new JLabel("Name:");
        namel.setFont(bold12);
        addComponent(mainPanel, namel, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField nametf = new JTextField(40);
        nametf.setFont(plain);
        addComponent(mainPanel, nametf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel adl = new JLabel("Address:");
        adl.setFont(bold12);
        addComponent(mainPanel, adl, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField adtf = new JTextField(40);
        adtf.setFont(plain);
        addComponent(mainPanel, adtf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel pnl = new JLabel("Phone Number:");
        pnl.setFont(bold12);
        addComponent(mainPanel, pnl, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField pntf = new JTextField(40);
        pntf.setFont(plain);
        addComponent(mainPanel, pntf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel ln1l = new JLabel("First Lastname:");
        ln1l.setFont(bold12);
        addComponent(mainPanel, ln1l, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField ln1tf = new JTextField(40);
        ln1tf.setFont(plain);
        addComponent(mainPanel, ln1tf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel ln2l = new JLabel("Second Lastname:");
        ln2l.setFont(bold12);
        addComponent(mainPanel, ln2l, 0, gridy, 1, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField ln2tf = new JTextField(40);
        ln2tf.setFont(plain);
        addComponent(mainPanel, ln2tf, 1, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel eml = new JLabel("E-Mail:");
        eml.setFont(bold12);
        addComponent(mainPanel, eml, 2, gridy, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        JTextField emtf = new JTextField(40);
        emtf.setFont(plain);
        addComponent(mainPanel, emtf, 3, gridy++, 1, 1, middleCenterInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        List<Component> order = new ArrayList<>(8);
        order.add(idtf);
        order.add(nametf);
        order.add(pntf);
        order.add(ln2tf);
        order.add(agtf);
        order.add(adtf);
        order.add(ln1tf);
        order.add(emtf);
        MyOwnFocusTraversalPolicy newPolicy = new MyOwnFocusTraversalPolicy(order);
        frame.setFocusTraversalPolicy(newPolicy);

        // JTable Creation
        String[] headline = { "Id", "Name", "First Lastname", "Second Lastname", "Age", "Address", "Phone Number",
                "E-Mail" };
        String[][] data = { { "", "", "", "", "", "", "", "" }, { "", "", "", "", "", "", "", "" } };
        JTable dataShow = new JTable(data, headline);
        dataShow.setPreferredScrollableViewportSize(new Dimension(900, 300));
        dataShow.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(dataShow);
        addComponent(mainPanel, scrollPane, 0, gridy++, 4, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        // Table Personalization
        dataShow.getTableHeader().setFont(bold11);
        new HeaderRenderer(dataShow);

        // buttons Components
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        JButton save = new JButton("Save");
        save.setFont(bold12);
        addComponent(buttonPanel, save, 0, 0, 1, 1, topInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        JButton del = new JButton("Delete");
        del.setFont(bold12);
        addComponent(buttonPanel, del, 1, 0, 1, 1, topInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);

        JButton edit = new JButton("Edit");
        edit.setFont(bold12);
        addComponent(buttonPanel, edit, 2, 0, 1, 1, topInsets, GridBagConstraints.CENTER,
                GridBagConstraints.HORIZONTAL);

        addComponent(mainPanel, buttonPanel, 0, gridy++, 4, 1, middleInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        // set content pane
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        // For future table filling
        /*
         * String ids = idtf.getText(); String names = nametf.getText(); String ln1s =
         * ln1tf.getText(); String ln2s = ln2tf.getText(); String ags = agtf.getText();
         * String ads = adtf.getText(); String pns = pntf.getText(); String ems =
         * emtf.getText();
         */

    }

    private void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth,
            int gridheight, Insets insets, int anchor, int fill) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0, anchor, fill,
                insets, 0, 0);
        container.add(component, gbc);
    }

    public static void main(String[] args) {

        // invoke runnable for thread safety
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new UserForm();
            }
        });

    }

    // LEFT alignment renderer
    private class HeaderRenderer implements TableCellRenderer {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) {
            renderer = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.LEFT);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
                int row, int col) {
            return renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        }

    }

    private class MyOwnFocusTraversalPolicy extends FocusTraversalPolicy {

        private List<Component> componentList;

        public MyOwnFocusTraversalPolicy(List<Component> componentList) {
            this.componentList = componentList;
        }

        @Override
        public Component getComponentAfter(Container aContainer, Component aComponent) {
            int index = getComponentIndex(aComponent);
            index++;
            index = (index >= componentList.size()) ? 0 : index;
            return componentList.get(index);
        }

        @Override
        public Component getComponentBefore(Container aContainer, Component aComponent) {
            int index = getComponentIndex(aComponent);
            index--;
            index = (index < 0) ? index + componentList.size() : index;
            return componentList.get(index);
        }

        @Override
        public Component getFirstComponent(Container aContainer) {
            return componentList.get(0);
        }

        @Override
        public Component getLastComponent(Container aContainer) {
            return componentList.get(componentList.size() - 1);
        }

        @Override
        public Component getDefaultComponent(Container aContainer) {
            return componentList.get(0);
        }

        private int getComponentIndex(Component test) {
            for (int i = 0; i < componentList.size(); i++) {
                Component component = componentList.get(i);
                if (component.equals(test)) {
                    return i;
                }
            }
            return -1;
        }

    }

}
...