如何在单击焦点超出表格并按<enter>键时在JTable中添加行</enter>

时间:2014-01-27 10:27:21

标签: java swing jtable

我正在设计一个客户端交互应用程序,其中的要求如下: -

  1. 用户已经在单元格中进行了编辑。
  2. 按Enter键,将插入新行。
  3. 从上面开始,如果客户端在单元格中编辑某些内容并按ENTER键,它将创建一个带编辑的新行。换句话说,当用户从单元格失焦时,必须使用ENTER键添加一行。当用户聚焦一个单元格并按ENTER键时,它不能添加一行。

    1. 单元格焦点+按下ENTER键=除了编辑单元格外什么都不做。
    2. 外部单元格焦点+按下ENTER键=添加新行。
    3. SimpleTableDemo

      package com.ajay.test;
      
      /*
       * SimpleTableDemo.java requires no other files.
       */
      
      import java.awt.Dimension;
      import java.awt.GridLayout;
      import java.awt.KeyEventDispatcher;
      import java.awt.KeyboardFocusManager;
      import java.awt.event.KeyEvent;
      import java.awt.event.MouseAdapter;
      import java.awt.event.MouseEvent;
      import java.util.Vector;
      
      import javax.swing.JFrame;
      import javax.swing.JPanel;
      import javax.swing.JScrollPane;
      import javax.swing.JTable;
      import javax.swing.table.DefaultTableModel;
      
      public class SimpleTableDemo extends JPanel {
          private boolean DEBUG = false;
          private JTable table = null;
      
          public SimpleTableDemo() {
              super(new GridLayout(1,0));
      
              String[] columnNames = {"First Name",
                                      "Last Name",
                                      "Sport",
                                      "# of Years",
                                      "Vegetarian"};
      
              Object[][] data = {
              {"Kathy", "Smith",
               "Snowboarding", new Integer(5), new Boolean(false)},
              {"John", "Doe",
               "Rowing", new Integer(3), new Boolean(true)}};
      
      
              table = new JTable(new javax.swing.table.DefaultTableModel(data, columnNames));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
      
              if (DEBUG) {
                  table.addMouseListener(new MouseAdapter() {
                      public void mouseClicked(MouseEvent e) {
                          printDebugData(table);
                      }
                  });
              }
      
              //Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
      
              KeyboardFocusManager.getCurrentKeyboardFocusManager()
              .addKeyEventDispatcher(new KeyEventDispatcher() {
                  @Override
                  public boolean dispatchKeyEvent(KeyEvent e) {
                   if(e.getID() == KeyEvent.KEY_PRESSED)
                   {
                        if(e.getKeyCode() == KeyEvent.VK_ENTER)
                        {
                          addRow();
                        }
                   }
      
                    return false;
                  }
            });
      
      
      
              //Add the scroll pane to this panel.
              add(scrollPane);
          }
      
          private void addRow()
          {
              DefaultTableModel model = (DefaultTableModel)table.getModel();
      
             if (model != null) {
             Vector v = new Vector(1);
             for (int j = 0; j < table.getColumnCount(); j++){
                      v.add("");
                  }
                  model.addRow(v);
                  }
      
          }
      
          private void printDebugData(JTable table) {
              int numRows = table.getRowCount();
              int numCols = table.getColumnCount();
              javax.swing.table.TableModel model = table.getModel();
      
              System.out.println("Value of data: ");
              for (int i=0; i < numRows; i++) {
                  System.out.print("    row " + i + ":");
                  for (int j=0; j < numCols; j++) {
                      System.out.print("  " + model.getValueAt(i, j));
                  }
                  System.out.println();
              }
              System.out.println("--------------------------");
          }
      
          /**
           * Create the GUI and show it.  For thread safety,
           * this method should be invoked from the
           * event-dispatching thread.
           */
          private static void createAndShowGUI() {
              //Create and set up the window.
              JFrame frame = new JFrame("SimpleTableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
              //Create and set up the content pane.
              SimpleTableDemo newContentPane = new SimpleTableDemo();
              newContentPane.setOpaque(true); //content panes must be opaque
              frame.setContentPane(newContentPane);
      
              //Display the window.
              frame.pack();
              frame.setVisible(true);
          }
      
          public static void main(String[] args) {
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      }
      

      如果不存在细胞焦点,请建议添加一行。并且如果有焦点,则进行编辑。

2 个答案:

答案 0 :(得分:0)

我通过以下代码找到了上述问题的解决方案: -

package com.ajay.test;

/*
 * SimpleTableDemo.java requires no other files.
 */

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class SimpleTableDemo extends JPanel {
    private boolean DEBUG = false;
    private JTable table = null;

    public SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)}};


        table = new JTable(new javax.swing.table.DefaultTableModel(data, columnNames));
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }

        table.addKeyListener(new KeyListener(){

            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getID() == KeyEvent.KEY_PRESSED)
                {
                  if(e.getKeyCode() == KeyEvent.VK_ENTER)
                  {
                    addRow();
                  }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyTyped(KeyEvent e) {
                // TODO Auto-generated method stub

            }
        }


        );

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);





        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    private void addRow()
    {
        DefaultTableModel model = (DefaultTableModel)table.getModel();

       if (model != null) {
       Vector v = new Vector(1);
       for (int j = 0; j < table.getColumnCount(); j++){
                v.add("");
            }
            model.addRow(v);
            }

    }

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

我们还必须在上面的代码中添加KeyBoardListener。

谢谢!

答案 1 :(得分:0)

我不知道你是否得到了你想要的东西,但只是在听众中添加一个条件就可以做到(如果我理解你的话):

/*
 * SimpleTableDemo.java requires no other files.
 */

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class SimpleTableDemo extends JPanel {
    private boolean DEBUG = false;
    private JTable table = null;

    public SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)}};


        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);

        table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);


        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        KeyboardFocusManager.getCurrentKeyboardFocusManager()
        .addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) {
             if(e.getID() == KeyEvent.KEY_PRESSED)
             {
                  if(e.getKeyCode() == KeyEvent.VK_ENTER && table.isEditing()==false)
                  {//HERE IS THE CHANGE
                    addRow();
                  }

             }

              return false;
            }
      });



        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    private void addRow()
    {
        DefaultTableModel model = (DefaultTableModel)table.getModel();

       if (model != null) {
       Vector v = new Vector(1);
       for (int j = 0; j < table.getColumnCount(); j++){
                v.add("");
            }
            model.addRow(v);
            }

    }

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        SimpleTableDemo newContentPane = new SimpleTableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

添加table.isEditing()==false条件后,您会在按ENTER时添加新行,但如果刚刚编辑过单元格并按ENTER则不会。