Редактирование Jtable с помощью JtextField и FocusTraversalPolicy - PullRequest
1 голос
/ 13 апреля 2020

Запустив пример (пренебрегаемый, но функциональный, чтобы продемонстрировать мою проблему), вы можете увидеть шаги в консоли в focustraversalpolicy

Test1: просто нажмите TAB или ShiftTab. В консоли вы увидите шаги в getComponentAfter и методы getComponentBefore; в частности видно, что, поскольку ячейки не редактируются, в случае второго компонента возвращается компонент JScrollPane. так что все в порядке

Test2: нажмите на ячейку JTable, напишите что-нибудь (для ввода редактирования) и нажмите TAB. В консоли вы видите отрывок в методе getComponentAfter; в частности видно, что, имея фокус на JTable, возвращается компонент JTable. так что все в порядке

Test3: нажмите на ячейку JTable, напишите что-нибудь (чтобы войти в редактирование) и нажмите ShiftTAB. Ничего не происходит, по крайней мере, с точки зрения focustraversalpolicy. Если вы снова нажмете ShiftTab В консоли вы увидите отрывок в методе getComponentBefore ; в частности, мы видим, что компонент JTextField, используемый для редактирования ячейки, возвращается

Почему смещение TAB в первый раз не влияет на политику focustraversalpolicy?

Почему TAB в focustraversalpolicy возвращает компонент JTable и Shift TAB вернуть компонент JTextField?

public class Prova2
{
    public static final Double VideoDefaultFontIncrementWidth = 0.92;
    public static final Double VideoDefaultFontIncrementHeight = 1.5;

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Prova2();
            }
        });
    }

    public Prova2()
    {
        JFrame frame = new JFrame("Prova");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //
        Object[] columnHeaders = {"Codice", "Nome", "Prezzo", "Data", "Noedit"};
        Object rows[][] = { 
            { "A", "About", 44.36, null, "aa" }, 
            { "B", "Boy", 44.84, null, "aa" }, 
            { "C", "Cat", 463.63, null, "aa" }, 
            { "D", "Day", 27.14, null, "aa" }, 
            { "E", "Eat", 44.57, null, "aa" }, 
            { "F", "Fail", 23.15, null, "aa" }, 
            { "G", "Good", 4.40, null, "aa" }, 
            { "H", "Hot", 24.96, null, "aa" }, 
            { "I", "Ivey", 5.45, null, "aa" }, 
            { "J", "Jack", 49.54, null, "aa" }, 
            { "K", "Kids", 280.00, null, "aa" }, 
            { "2A", "About", 44.36, null, "aa" }, 
            { "2B", "Boy", 44.84, null, "aa" }, 
            { "2C", "Cat", 463.63, null, "aa" }, 
            { "2D", "Day", 27.14, null, "aa"}, 
            { "2E", "Eat", 44.57, null, "aa" }, 
            { "2F", "Fail", 23.15, null, "aa" }, 
            { "2G", "Good", 4.40, null, "aa" }, 
            { "2H", "Hot", 24.96, null, "aa" }, 
            { "2I", "Ivey", 5.45, null, "aa" }, 
            { "2J", "Jack", 49.54, null, "aa" }, 
            { "2K", "Kids", 280.00, null, "aa" } };
        //
        // text 1
        JTextField Text1 = new JTextField("");
        Text1.setName("Text1");
        frame.add(Text1, BorderLayout.NORTH);
        //
        // JTable soluzione 2
        JTable myTable = new JTable(rows, columnHeaders);
        myTable.setName("Table");
        myTable.setFillsViewportHeight(true);
        myTable.putClientProperty("autoStartsEdit", true);
        myTable.putClientProperty("terminateEditOnFocusLost", true);
        ActionMap myTableActionMap = myTable.getActionMap();
        myTableActionMap.put("selectPreviousColumnCell", new myPreviousFocusHandler());
        myTableActionMap.put("selectNextColumnCell", new myNextFocusHandler());
        for (int i = 0; i < myTable.getColumnCount()-1; i++)
        {
            JTextField myTextField = new JTextField();
            myTable.getColumn(columnHeaders[i]).setCellEditor(new DefaultCellEditor(myTextField));
        }
        JScrollPane pane = new JScrollPane(myTable);
        frame.add(pane, BorderLayout.CENTER);       
        //
        // text2
        JTextField Text2 = new JTextField("");
        Text2.setName("Text2");
        frame.add(Text2, BorderLayout.SOUTH);
        //
        // frame
        frame.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
        frame.setSize(800, 400);
        frame.setVisible(true);
    }

    public static class MyFocusTraversalPolicy extends FocusTraversalPolicy
    {
        @Override
        public Component getComponentAfter(Container arg0, Component arg1)
        {
            System.out.println("getComponentAfter1: "+arg1.toString());
            JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
            JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
            if (arg1 instanceof JPanel == true)
            {
                return getFirstComponent(arg0);
            }
            int myNewPosition = 0;
            myNewPosition = myComponentPosition(myPanel, arg1);
            myNewPosition = myComponentNext(myPanel, myNewPosition, 1);
            if (myNewPosition > -1)
            {
                System.out.println("getComponentAfter2: "+myComponent(myPanel, myNewPosition));
                return myComponent(myPanel, myNewPosition);
            }
            else
            {
                return getFirstComponent(arg0);
            }
        }
        @Override
        public Component getComponentBefore(Container arg0, Component arg1)
        {
            System.out.println("getComponentBefore1: "+arg1.toString());
            JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
            JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
            if (arg1 instanceof JPanel == true)
            {
                return getFirstComponent(arg0);
            }
            int myNewPosition = 0;
            myNewPosition = myComponentPosition(myPanel, arg1);
            myNewPosition = myComponentNext(myPanel, myNewPosition, -1);
            if (myNewPosition > -1)
            {
                System.out.println("getComponentBefore2: "+myComponent(myPanel, myNewPosition));
                return myComponent(myPanel, myNewPosition);
            }
            else
            {
                return getLastComponent(arg0);
            }
        }
        @Override
        public Component getDefaultComponent(Container arg0)
        {
            System.out.println("getDefaultComponent1: ");
            JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
            JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
            System.out.println("getDefaultComponent2: "+myPanel.getComponent(0));
            return myPanel.getComponent(0);
        }
        @Override
        public Component getFirstComponent(Container arg0)
        {
            System.out.println("getFirstComponent1: ");
            JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
            JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
            System.out.println("getFirstComponent2: "+myPanel.getComponent(0));
            return myPanel.getComponent(0);
        }
        @Override
        public Component getLastComponent(Container arg0)
        {
            System.out.println("getLastComponent1: ");
            JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
            JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
            System.out.println("getLastComponent2: "+myPanel.getComponent(myPanel.getComponentCount()-1));
            return myPanel.getComponent(myPanel.getComponentCount()-1);
        }
        private int myComponentPosition(Container parm_Container, Component parm_Component)
        {
            for (int i = 0; i < parm_Container.getComponentCount(); i++)
            {
                if (parm_Container.getComponent(i) == parm_Component)
                {
                    return i;
                }
                if (parm_Container.getComponent(i).getClass() == JScrollPane.class)
                {
                    if (parm_Component.getClass() == JTable.class)
                    {
                        return i;
                    }
                }
            }
            return -1;
        }
        private int myComponentNext(Container parm_Container, int parm_Position, int parm_Increment)
        {
            for (int i = parm_Position + parm_Increment; i > -1 && i < parm_Container.getComponentCount(); i = i + parm_Increment)
            {
                if (parm_Container.getComponent(i).isEnabled() && parm_Container.getComponent(i).isFocusable())
                {
                    return i;
                }
            }
            return -1;
        }

        private Component myComponent(Container parm_Container, int parm_Position)
        {
            return parm_Container.getComponent(parm_Position);
        }
    }


    public class myPreviousFocusHandler extends AbstractAction
    {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            KeyboardFocusManager myManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            myManager.focusPreviousComponent();
        }
    }

    public class myNextFocusHandler extends AbstractAction
    {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            KeyboardFocusManager myManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            myManager.focusNextComponent();
        }

    }

}
...