JTable keylistener

Hello.
I would like that the user can delete a row of my table by pressing the 'delete' key. In fact, I add a keylistener to my table and and I can catch all key event except the special keys like 'delete'
Can you help me ?

Are you using [Key Bindings|http://www.camick.com/java/blog.html?name=key-bindings]?
For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.
Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

Similar Messages

  • How can I add KeyListener to JTable editor

    Hi, I want to know how can I add a KeyListener to a JTable editor?
    I want to capture the event when any of the cell in the jtable has a key typed.

    If your goal is to check the entered value, it's more elegant to do this in overriding
    DefaultCellEditor#stopCellEditing and return false when the value is not correct.
    Example from a DateEditor:
            @Override public boolean stopCellEditing() {
                String value = ((JTextField)getComponent()).getText();
                if(!value.equals("")) {
                    try {
                        formatterE.parse(value);
                    } catch (ParseException e) {
                        ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
                        return false;
                return super.stopCellEditing();
            }

  • Why Component do not invoke KeyListener,when it is a CellEditor in JTable?

    when I edit at a cell ,the JTextField do not invoke keylilsten,why?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.EventObject;
    public class Test extends JFrame {
         public JTable table;
         public JScrollPane scrollpane;
         public Test() {
              JTextField editor;          
              this.table = new JTable(5,5);
              this.scrollpane=new JScrollPane(table);
              for (int i=0;i<5;i++) {
                   editor=new JTextField();
                   editor.setBackground(Color.blue);
                   editor.setForeground(Color.white);
                   editor.addKeyListener(new kl());  //addkeylistener
                   this.table.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(editor));
              this.getContentPane().add(this.scrollpane);
              this.scrollpane.setVisible(true);
              this.setSize(300,300);
              this.setVisible(true);
           public static void main(String args[]){
                Test test=new Test();
    //KeyListener
    class kl implements KeyListener {
         public void keyReleased(KeyEvent e) {
              System.out.println("keyReleased...");
         public void keyPressed(KeyEvent e) {
              System.out.println("keyPressed...");
         public void keyTyped(KeyEvent e){
              System.out.println("keytype...");          
    }

    I changed your code a bit to show you what you were doing wrong, you need to implement KeyListener:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.EventObject;
    public class Test extends JFrame implements KeyListener {
    public JTable table;
    public JScrollPane scrollpane;
    public Test() {
    JTextField editor;
    this.table = new JTable(5,5);
    this.scrollpane=new JScrollPane(table);
    for (int i=0;i<5;i++) {
    editor=new JTextField();
    editor.setBackground(Color.blue);
    editor.setForeground(Color.white);
    editor.addKeyListener( this ); //addkeylistener
    this.table.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(editor));
    this.getContentPane().add(this.scrollpane);
    this.scrollpane.setVisible(true);
    this.setSize(300,300);
    this.setVisible(true);
    public static void main(String args[]){
    Test test=new Test();
    public void keyReleased(KeyEvent e) {
    System.out.println("keyReleased...");
    public void keyPressed(KeyEvent e) {
    System.out.println("keyPressed...");
    public void keyTyped(KeyEvent e){
    System.out.println("keytype...");

  • Add event(keyListener) to JTable Cell default editor.

    I've got a form(Jdialog) with a Jtable on it.
    I've added a keyListener to the JButtons and Jtable so that, wherever the the focus IS, when I hit the "F7" key, it fills the Jtable from the database connection.
    It's working REALLY fine now but there is one small glitch.
    When I'm editing a cell, the keyListener event is not thrown. I supposed it's because the "DefaultCellEditor" does not throw the event.
    How can I add such a thing??
    I'm looking for something like :
    table.getDefaultEditor().addKeyListener
    but it does not exists.
    If it's not possible, is there a way to make the JDialog listen to all the keyListener events from its childs??(Mimics the JDK < 1.4)
    Thx

    Using key binding is better implementation.
    After you read the tutorial your next move is to google for it.
    http://www.google.com/search?hl=en&q=jtable+keybinding
    Second result brings you to camickr's example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • How to add KeyListener on JTable

    Hello everybody,
    I have a Jtable and i want to use the up and down key on the keyboard. I don't find the method how allow me to do that. I try "addKeyListener" but no result.
    Please help me !!!!
    Thanks .
    PS : excuse for my bad english.

    i try to be clear :o)))
    I have a text on a JtextPane and i have a table (include in a JSrcollPane)
    when i clicked in the text, il select the good entry in the table, when a do the same (by clicking addmouselistener) on the Jtable i hightlight un part of text. OK !!! for this its good !!!
    The second thing i must doing :
    when i use the up and down key on the Jtextpane its good i have the comportment describe before. But when i use the up and key doxn in my table its doesnt work !!!
    the focus is also in my jtextpane, this event is not catch by my Jtable but by JtextPane

  • How can I change the default process of VK_ENTER in JTable

    Now I have met a requirment to process the "enter" key event in JTable. But it is found that the JTable has a default process on the ENTER key press, and it will select the next row. Even the worse, the default process is invoked before the KeyListener I registered.
    How can I remove that?
    I have tried the follow ways: 1.remove several keys, such as "selectNextRow","selectNextRowExtendSelection", from the actionMap,
    2.invoke processKeyBinding() in the constructor of my subclass of JTable.
    But both lead to failure.
    And I can't find the default process to the VK_ENTER in the java source code. I need help on this.
    BTW, does anyone know how to eliminate the focus traversal between cells. When I press left arrow or right arrow, the focus traverses in the scope of the selected row.

    thanks
    i also found solution for my poblem:
    i have this code:
    jMenuItem jMnItEdit;
    jMnItEdit.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0));
    also i had ActionListener bounded to this JMenuItem
    but Ialso had in form JTable and it always grabbed my VK_ENTER event and that menu item wasn't working at all
    but when i overrode that input map for JTable and set
    tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "none");
    everything started to work perfectly,
    thanks a lot

  • How to paint a Custom Cell  while you are editing on adjacent Cell in JTabl

    Hi All,
    I have two Columns in my Custom Table . Both Two Columns are Custom Cell Editors/Renderers.
    I have made UI such that Column1 is Label , Column 2 is TextBox / Combo/ UI Input any
    My Custom Table View when i edit some value against Max Conn. it should display Blue
    =================================
    Column A | Column B
    ==================================
    Timeout | some_unchanged_value
    *{color:#0000ff}Session{color}* | some_unchanged_value
    Log File | some_unchanged_value
    ===================================
    My issue is when i start typing in my Custom Editor suppose i Type /invoke Edtir of Index 2, Column 2 font should become Blue.
    It becomes blue only when i debug this issue it perfectly works, without Debugger it doesnt changes the Font
    MyDefaultRenderer is my Custom renderer - I have set Foregroud Color as BLUE
    NOTE:_
    In run method if table.repaint() instead of single renderer:
    It turns Blue when i make call on table.repaint() methosd but i feel that repainting full table on every key Stroke should not be very good programming. Whats is more appropriate way?
    I want to repaint only that particular cell against which i change the Value
        private class MyDefaultEditor extends AbstractCellEditor implements TableCellEditor {
            private JTextField txtField = null;
            private int rowIndex;
            public MyDefaultEditor() {
                txtField = new JTextField();
                txtField.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyTyped(KeyEvent e) {
                        super.keyTyped(e);
                        System.out.println("########### Hello This is MyDefaultEditor");
                  SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                  // Call Renderer adjacentt to input to turn Blue (Is this Valid Code ??)
                                MyDefaultRenderer defRen = (MyDefaultRenderer) thisTable.getCellRenderer(activeRowIndex, 0);
                                defRen.paintMe();
              // table.repaint() works for me but i dont want to call it on evey ket type, that will be Heave rite???
            public Component getTableCellEditorComponent(JTable table,
                    Object value, boolean isSelected, int row, int column) {
                rowIndex = row;
                String valStr = "";
                if (value != null && value instanceof String) {
                    valStr = value.toString();
                txtField.repaint();
                return txtField;
            public Object getCellEditorValue() {
                return txtField.getText();
        }Edited by: Shubhadeep on Jun 27, 2009 1:58 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:01 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:06 AM
    Edited by: Shubhadeep on Jun 27, 2009 2:12 AM

    Well, I think you need to add a custom renderer to the first column. The renderer would check if the table.isEditing(). If it is and the editing is done on the same row, then you set the font color blue, otherwise you use the default font color.
    Then the next question is how do you repaint the cell. Well you can use the table.repaint(Rectangle) method. You can get the Rectangle to repaint by using the table.getCellRect(...) method.
    Finally, you need to know when to repaint the cell. Well a PropertyChangeEvent is fired when a cell starts and stops editing. So you only need to handle these events. Don't use a KeyListener. The PropertyChangeListener you add to the table might be something like:
    public void propertyChange(PropertyChangeEvent e)
         if ("tableCellEditor".equals(e.getPropertyName()))
              if (table.isEditing())
                   processEditingStarted();
              else
                   processEditingStopped();
    }So when editing is started you need to determine the "adjacent" cell you want to repaint to the blue font is used. You would save the cell Rectangle so you can restore the font when editing is stopped.

  • Want jtable  to be refreshed...on change of the textfield change..

    The code is below and question follows the code :
    import java.sql.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.event.*;
    public class sample extends JFrame
         JTable tableFindsymbol;
         JFrame FindSymbolFrame;
         JTextField symbolText = new JTextField(35);
        private String getsymbolTextfieldtext;
        private int columns;
         Vector columnNames = new Vector();
        Vector data = new Vector();
        private String query;
         public sample()
                   FindSymbolFrame = new JFrame("sample");
                  FindSymbolFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                  Container myPane = FindSymbolFrame.getContentPane();
                  myPane.setLayout(new GridBagLayout());
                  GridBagConstraints c = new GridBagConstraints();
                  setMyConstraints(c,0,0,GridBagConstraints.CENTER);myPane.add(getFieldPanel(),c);
                  setMyConstraints(c,0,1,GridBagConstraints.CENTER);myPane.add(getTable(),c);
                  FindSymbolFrame.pack();
                  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                  Dimension frameSize = FindSymbolFrame.getSize();
                  FindSymbolFrame.setLocation(new Point((screenSize.width - frameSize.width) / 2 , (screenSize.height - frameSize.width) / 2));
                  FindSymbolFrame.setVisible(true);
         public JPanel getFieldPanel()
              JPanel p = new JPanel(new GridBagLayout());
              p.setBorder(BorderFactory.createTitledBorder("Enter Details"));
              GridBagConstraints c = new GridBagConstraints();
              setMyConstraints(c,0,0,GridBagConstraints.CENTER);p.add(symbolText,c);
              symbolText.addKeyListener(listener);
              return p;
         KeyListener listener = new KeyListener()
                    public void keyPressed(KeyEvent e) {}
                    public void keyReleased(KeyEvent e)
                              getsymbolTextfieldtext = symbolText.getText();
                              getTable();
                   public void keyTyped(KeyEvent e){}
         public JPanel getTable()
              try{
                        query =  "SELECT SYMBOL, CO_NAME FROM CO_DB_WITH_NAME where CO_NAME LIKE '"+ getsymbolTextfieldtext +"'";
                        JOptionPane.showMessageDialog(null,query);
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:sdb","scott","tiger");
                        final Statement st = con.createStatement();
                        ResultSet rs = st.executeQuery(query);
                        ResultSetMetaData md = rs.getMetaData();
                        int columns = md.getColumnCount();
                        for (int i = 1; i <= columns; i++)
                               columnNames.addElement( md.getColumnName(i) );
                       while(rs.next())
                             Vector row = new Vector(columns);
                              for (int i = 1; i <= columns; i++)
                                  row.addElement( rs.getObject(i));
                          data.addElement( row );
                     rs.close();
              }catch(Exception e)
                               System.out.println( e );
                        JPanel tablePane = new JPanel(new GridBagLayout());
                        DefaultTableModel model = new DefaultTableModel(data,columnNames);
                        tableFindsymbol = new JTable(model);
                        tablePane.add(tableFindsymbol);
                         JScrollPane scrollPane = new JScrollPane(tableFindsymbol);     
                         getContentPane().add(scrollPane);
                        tablePane.add(getContentPane());
                        tableFindsymbol.setRowSelectionAllowed(true);
                        tableFindsymbol.setColumnSelectionAllowed(false);
                        tablePane.setVisible(true);
                      return tablePane;
         private  void setMyConstraints(GridBagConstraints c, int gridx, int gridy, int anchor)
              c.gridx = gridx;
              c.gridy = gridy;
              c.anchor = anchor;
         public static void main(String[] args)
              sample fsymf=new sample();
    }what i want to do is: make the jtable get updated as soon the text in the text field changes..
    how do i call the jtable panel so it updates the table or any jtable update method
    Thanks for reply in advance..

    Quit multi-posting questions.
    You where already given the answer to this question in your last posting:
    [http://forum.java.sun.com/thread.jspa?threadID=5270240]
    Also, in the future don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Using a JPanel as cell editor in JTable

    I have a composite component (JPanel that contains a JTextField and a
    JButton) that I would like to use as the a cell editor in a JTable.The JButton instantiates a UI editor component that I have designed. Example would be date editor for dates, tet editor for strings etc. This editor allows the user to select a date to populate the JTextField (the date may also be manually entered).
    I have no problem with the rendering of the component within the table.However, I would like for the JTextField embedded within the JPanel to receive focus and a visible caret, when using the tab key to navigate to the cell. After reading through some of the posts here , I was able to transfer the focus. But I dont see a visible caret. I am unable to edit. I have to click on the text box and then start typing. Its a great pain in the ass.
    I have a custom designed table and custom designed editor. Code is attached...
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))) {     
    if (selCol == 1) {
    isSelected= getCellEditor(selRow,selCol).stopCellEditing();
    targetRow = (selRow + 1) % rowCount;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    if (editCellAt(targetRow, 1, obj)) {
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    } else {
    getCellEditor(selRow, selCol).shouldSelectCell(obj);
    return super.processKeyBinding(ks,e,condition,pressed);
    </pre>
    Relevant code of my custom editor is below....
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    lastEditedRow = row;
    lastEditedCol = column;
    lastEditedTable = table;
    lastEditedValue = value;
    val = value;
    ((JTextField)editorComponent).
    setText(val == null ? "" : val.toString());
    setClickCountToStart(1);
    if (value instanceof CycCollectionChooserModel) {
    String collection = ((CycCollectionChooserModel)value).
    getCollection().cyclify();
    button.setVisible(EditorForCollectionMap.hasUIEditor(collection));
    button.setMargin (new Insets (1,1,1,1));
    button.setIconTextGap(0);
    buttonListener.model = (CycCollectionChooserModel)value;
    buttonListener.rowIndex = row;
    buttonListener.localTable = table;
    return panel;
    public boolean isCellEditable(EventObject evt) {
    if (evt instanceof MouseEvent) {
    int clickCount;
    clickCount = 1;
    return ((MouseEvent)evt).getClickCount() >= clickCount;
    return super.isCellEditable(evt);
    public boolean stopCellEditing() {   
    if (super.stopCellEditing()) {
    final int targetRow = (lastEditedRow+1)%lastEditedTable.getRowCount();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    lastEditedTable.changeSelection(targetRow, 1, false, false);
    lastEditedTable.getComponentAt(targetRow, 1).requestFocus();
    return true;
    return false;
    Does any one know why I am not able to see the caret? Any insights you have will be most welcome.
    Thanks in advance,
    Praveen.

    Almost solved the problem. Navigation through Tab key, up/ down arrow, Enter key works for text boxes. Navigation through Tab Key, Up/down arrow works for combo boxes. But for "Enter" key it doesnt. Changes in code ....
    (I have added a key listener to my editor class)
    <pre>
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed) {
    final int selRow = getSelectedRow();
    final int rowCount = getRowCount();
    final int selCol = getSelectedColumn();
    final EventObject obj = (EventObject) e;
    if (selRow == -1) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {           
    changeSelection(0, 1, false, false);
    editCellAt(0, 1, obj);
    boolean isSelected = false;
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)) ||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0))) {     
    if (selCol == 1) {
    final int targetRow = (selRow + 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    if ((ks == KeyStroke.getKeyStroke(KeyEvent.VK_UP,0))||
    (ks == KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1))) {
    if (selCol == 1) {
    final int targetRow = (selRow - 1) % rowCount;
    getCellEditor(selRow,selCol).stopCellEditing();
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    editCellAt(targetRow, 1, obj);
    changeSelection(targetRow, 1, false, false);
    getComponentAt(targetRow, 1).requestFocus();
    return super.processKeyBinding(ks,e,condition,pressed);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    public class FactEditorComboBoxTableEditor extends DefaultCellEditor implements KeyListener{
    //// Constructors
    /** Creates a new instance of FactEditorComboBoxTableEditor. */
    public FactEditorComboBoxTableEditor(JComboBox comboBox) {
    super(comboBox);
    JTextField TF =(JTextField)((ComboBoxEditor)comboBox.getEditor()).
    getEditorComponent();
    TF.addKeyListener(this);
    </pre>
    P.S : viravan, help me solve this problem and you will get the rest of the dukes LOL

  • TAB in JTable works in 1.3 doesnt in 1.4

    Hello World!
    i wrote an application with a jtable.
    now i want to navigate in this table with TAB (from left to right, top down)
    and
    with ENTER (like TAB).
    i created a KeyListener on the table.
    i wrote my app in 1.3 and it works well in jre 1.3
    now i tested it in jre 1.4 and it doesnt work.
    any ideas??
    thanks
    Sergej

    Hi
    //it works well JDK1.4.1
    JTable table = new JTable(model);
    table.addKeyListener(new KeyAdapter()
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode()==KeyEvent.VK_ENTER)
    e.consume();
    KeyEvent tabEvent = new KeyEvent(table,e.getID(),
    e.getWhen()+1,e.getModifiers(),KeyEvent.VK_TAB,'\t');
    table.dispatchEvent(tabEvent);
    });

  • JTable blues

    Hello, I am having a hard time getting my JTable to show up on my panel. There is a fair bit of code to wade through so I have put comments in all CAPS lined with an '*' so it should be easy to find where I am having my problems.
    What I would like to do is have a new table row added each time the user enters a service and clicks a button. A service name and an integer for the durration of the service. Additonaly the opposite when the remove service button is clicked.
    When running the app, click the employees tab; there is a NullPointerException error right now with the line
    return getValueAt(0, c).getClass(); at line 904 once that tab is clicked.
    Things to look for in my code are:
    -westPanel
    -westRight
    -table
    -MyTableModel
    -scrollpane2
    -(maybe servicePanel) undecided and it is commented out at this moment.
    Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.
    Thanks in advance.
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.plaf.metal.MetalLookAndFeel;
    import javax.swing.table.AbstractTableModel;
    public class Administration extends JFrame implements ActionListener,ListSelectionListener,ItemListener {
         private JTabbedPane      jtp;
         public String[] columnNames;
         public Object[][] data;
         public static JPanel     servicePanel;
         public static int          checkRow;
         private JPanel                westPanel;
         private JPanel                westTop;
         private JPanel                westCenter;
         private JPanel                westCenterTop;
         private JPanel                westCenterBottom;
         private JPanel                westBottom;
         private JPanel               westBottomRight;
         private JPanel               westLeft;
         private JPanel               westRightTop;
         private JPanel               westRight;
         private JPanel                northPanel;
         private JPanel               centerPanel;
         private JPanel                centerRight;
         private JPanel               centerLeft;
         private JPanel                eastPanel;
         private JPanel                eastRight;
         private JPanel                eastLeft;
         private JPanel                eastBottom;
         public static JPanel               eastEastTop;
         private JPanel               eastEastCenter;
         private JPanel                southPanel;
         private JPanel                southTop;
         private JPanel                southLeft;
         private JPanel                southCenter;
         private JPanel                southBottom;
         private GridBagLayout      gbl;
         private GridBagConstraints gbc;
         //private JComboBox      employees;
         private JComboBox[]      openAmPm = new JComboBox[7];
         private JComboBox[]      closedAmPm = new JComboBox[7];
         private JComboBox     startAmPm;
         private JComboBox     endAmPm;
         private JComboBox      cmbServices;
         private JList          employees;
         private JList           listEmpl;
         private JList           listServices;
         private JList          listDays;
         private JList          listSchedule;
         //private Vector           nameData;
         private JScrollPane      scrollpane;
         private JScrollPane          scrollpane2;
         private JScrollPane      scrollPane3;
         private JScrollPane          scrollPane4;
         private JLabel           lblEmployees;
         public static JLabel          lblEmployeeName;
         public static JLabel      lblMonthStat;
         public static JLabel          lblDay;
         public static JLabel           lblYear;
         public static String service = null;
         private JLabel          lblLength;
         private JLabel           lblBizHours;
         private JLabel           lblServices;
         private JLabel          lblHoliday;
         private JLabel           lblOpen;
         private JLabel           lblClosed;
         private JLabel           lblsouthHeading;
         private JLabel           lblStartTime;
         private JLabel           lblEndTime;
         private JLabel          lblDayOff;
         private JLabel          space;
         private JLabel          space2;
         private JLabel           space3;
         private JLabel           space4;
         private JLabel          space5;
         private JLabel          blank1;
         private JLabel          blank2;
         private JLabel           colon;
         private JLabel           colon2;
         private JLabel      lblSelect;
         private JLabel[] weekDay =new JLabel[7];
         //private String[] fakeName = {"Leon","Mike","Lori","Shannon","Rob"};
         private final static String[] dow = {"Sunday",
                                  "Monday",
                                  "Tuesday",
                                     "Wednesday",
                                  "Thursday",
                                  "Friday",
                                     "Saturday"};
         public static JTextField[]      startHr = new JTextField[7];
         public static JTextField[]      startMin = new JTextField[7];
         public static JTextField[]     finishHr = new JTextField[7];
         public static JTextField[]     finishMin = new JTextField[7];
         private JButton[]      btnUpdate = new JButton[7];
         private JButton          btnAddEmployee;
         private JButton         btnNextDay;
         private DefaultListModel nameData;
         private DefaultListModel serviceData;
         private DefaultListModel dayData;
         private DefaultListModel holidayData;
         private DefaultListModel scheduleData;
         private static final String hireString="Add Employee";
         private static final String fireString="Remove Employee";
         private static final String addService="Add Service";
         private static final String removeService="Remove Service";
         private JButton fireButton;
         private JButton hireButton;
         private JButton addServices;
         private JButton removeServices;
         private JButton btnAttatch;
         private JTextField employeeName;
         private JTextField serviceName;
         private JTextField txtOpenTime;
         private JTextField txtClosedTime;
         private int size;
         public static String timeText;
         private boolean result;
         private boolean totalResult;
         private String holidayMsg = "Here, you can select and \n schedule off days \n for employees from \n the list";
         private String message1 = "Enter a maximum of \n 3 digits";
         private String message2 = "Enter numbers only";
         private String minutes=" min";
         private String name;
         private boolean dbRecord=true;
         private int serviceSize;
         private JCheckBox[] dayOff = new JCheckBox[7];
         private int jlistCellWidth =100;
         public static final int MAX_CHARS = 1;
         private String myMonth;
         public static boolean removed=false;
         public Administration()
              //jtp.setDefaultLookAndFeelDecorated(true);
              checkRow = 0;
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              gbl = new GridBagLayout();
              gbc = new GridBagConstraints();
              //employees = new JComboBox();
              //employees.setEditable(false);
              cmbServices = new JComboBox();
              startAmPm = new JComboBox();
              startAmPm.addItem("AM");
              startAmPm.addItem("PM");
              startAmPm.setEditable(false);
              endAmPm = new JComboBox();
              endAmPm.addItem("AM");
              endAmPm.addItem("PM");
              endAmPm.setEditable(false);
              employeeName=new JTextField("",10);
              serviceName = new JTextField("",10);
              txtOpenTime = new JTextField("",5);
              txtClosedTime = new JTextField("",5);
              nameData = new DefaultListModel();
              holidayData = new DefaultListModel();
    /**     Eventualy put this into an isItemSelected function that retrieves names from
    *     the database
              /*nameData.addElement("Leon");
              nameData.addElement("Brenda");
              nameData.addElement("Megumi");
              nameData.addElement("jun");
              //populate employee combobox with names from nameData
              //int listSize = nameData.getSize();
         /*     for(int i=0;i<fakeName.length;i++)
                   nameData.addElement(fakeName);
                   //listEmpl.setSelectedIndex(i);
                   //String eName =(String)nameData.get(listEmpl.getSelectedIndex());
                   holidayData.addElement(fakeName[i]);
              serviceData = new DefaultListModel();
              dayData = new DefaultListModel();
              listEmpl=new JList(nameData);
              listEmpl.addListSelectionListener(this);
              listServices = new JList(serviceData);
              employees = new JList(holidayData);
              employees.addListSelectionListener(this);
              employees.setFixedCellWidth(jlistCellWidth);
              listDays = new JList(dayData);
              scheduleData = new DefaultListModel();
              listSchedule = new JList(scheduleData);
              listSchedule.setFixedCellWidth(jlistCellWidth);
              dayData.addElement("Sunday");
              dayData.addElement("Monday");
              dayData.addElement("Tuesday");
              dayData.addElement("Wednesday");
              dayData.addElement("Thursday");
              dayData.addElement("Friday");
              dayData.addElement("Saturday");
         //     listEmpl.setSelectedIndex(0);
              listDays.setSelectedIndex(0);
              listSchedule.setSelectedIndex(0);
              //listEmpl.addListSelectionListener(this);
              listEmpl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              listDays.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              employees.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              size = nameData.getSize();
              //employeeName.setText("size is "+size);
              listEmpl.setVisibleRowCount(5);
              listDays.setVisibleRowCount(7);
              employees.setVisibleRowCount(5);
              listSchedule.setVisibleRowCount(5);
              gbc.fill=GridBagConstraints.HORIZONTAL;
              gbc.anchor=GridBagConstraints.CENTER;
                   //declare labels
                        lblLength = new JLabel("SERVICE LENGTH",lblLength.CENTER);
                        lblSelect=new JLabel("Select a name from the list",lblSelect.CENTER);
                        lblsouthHeading = new JLabel("EMPLOYEE SCHEDULE",lblsouthHeading.CENTER);
                        lblEmployees = new JLabel("CURRENT EMPLOYEES",lblEmployees.CENTER);
                        lblEmployees.setOpaque(true);
                        //lblEmployees.setBackground(Color.yellow);
                        lblServices = new JLabel("CURRENT SERVICES",JLabel.LEFT);
                        lblBizHours= new JLabel("BUSINESS HOURS",lblBizHours.CENTER);
                        lblStartTime = new JLabel("Open",lblStartTime.LEFT);
                        lblEndTime = new JLabel("Closed",lblEndTime.LEFT);
                        blank1 = new JLabel("");
                        blank2=new JLabel("");
                        lblHoliday = new JLabel(holidayMsg);
                        lblEmployeeName = new JLabel("Name");
                        //lblEmployeeName.setForeground(Color.white);
                        lblMonthStat = new JLabel("");
                        lblDay = new JLabel("");
                        lblYear = new JLabel("");
                        //check myCalendar method to see if a button has been clicked
                        lblMonthStat.setForeground(Color.white);
                        lblDay.setForeground(Color.white);
                        lblYear.setForeground(Color.white);
              //declare buttons
              JButton btnAttatch = new JButton("<html>Attatch service<br> to employee</html>");
              btnAttatch.setBorder(BorderFactory.createRaisedBevelBorder());
              JButton fireButton = new JButton(fireString);
              JButton hireButton = new JButton(hireString);
              JButton addServices = new JButton(addService);
              JButton removeServices = new JButton(removeService);
              addServices.addActionListener(this);
              addServices.setActionCommand(addService);
              removeServices.addActionListener(this);
              removeServices.setActionCommand(removeService);
              hireButton.addActionListener(this);
              fireButton.setActionCommand(fireString);
              fireButton.addActionListener(this);
              JButton btnAddEmployee = new JButton("Add Employee");
              fireButton.setBorder(BorderFactory.createRaisedBevelBorder());
              JButton btnServices = new JButton("Add Service");
              addServices.setBorder(BorderFactory.createRaisedBevelBorder());
              removeServices.setBorder(BorderFactory.createRaisedBevelBorder());
              hireButton.setBorder(BorderFactory.createRaisedBevelBorder());
              //declare layouts
              BorderLayout southBorder = new BorderLayout();
              FlowLayout flo = new FlowLayout(FlowLayout.CENTER,30,30);
              FlowLayout westFlo = new FlowLayout(FlowLayout.CENTER,10,10);
              FlowLayout southFlo = new FlowLayout(FlowLayout.LEFT,10,10);
              GridLayout northGrid = new GridLayout(0,4);
              GridLayout southGrid = new GridLayout(1,1);
              GridLayout westGrid = new GridLayout(1,2);
              GridLayout southRow1 = new GridLayout(1,1,10,10);
              GridLayout southRow2 = new GridLayout(2,0,10,10);
              GridLayout eastGrid = new GridLayout(0,2,10,10);
              //declare panels
              servicePanel=new JPanel();
              servicePanel.setLayout(new GridLayout(0,2));
              //servicePanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
              servicePanel.setPreferredSize(new Dimension(100,0));
              westPanel = new JPanel();
              westTop = new JPanel();
              westCenter = new JPanel();
              westBottomRight= new JPanel();
              westCenterBottom = new JPanel();
              westBottom = new JPanel();
              westLeft = new JPanel();
              westRightTop = new JPanel();
              westRight = new JPanel();
              northPanel = new JPanel();
              centerPanel = new JPanel();
              centerRight = new JPanel();
              centerLeft = new JPanel();
              eastPanel=new JPanel();
              eastRight = new JPanel();
              eastLeft = new JPanel();
              eastBottom = new JPanel();
              eastEastTop = new JPanel();
              eastEastCenter = new JPanel();
              southPanel = new JPanel();
              southTop = new JPanel();
              southLeft = new JPanel();
              southCenter = new JPanel();
              southBottom = new JPanel();
              /////////////////set the panels/////////////////////
              //NORTH
              northPanel.setLayout(flo);
              //northPanel.setBackground(Color.cyan);
              //WEST
              westPanel.setLayout(westGrid);
              westPanel.setBorder(BorderFactory.createEtchedBorder());
              westTop.setLayout(new GridLayout(2,1));
              westTop.setBorder(BorderFactory.createEtchedBorder());
              westCenter.setBorder(BorderFactory.createRaisedBevelBorder());
              westCenter.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
              westBottom.setLayout(new GridLayout(3,3,10,10));
              westLeft.setLayout(new GridLayout(0,1));
              //westRightTop.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
              westRightTop.setLayout(new GridLayout(0,2));
              westRight.setLayout(new GridLayout(1,1));
              //westBottom.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
              //westBottom.setLayout(new GridLayout(2,2,20,20));
              //CENTER
              centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
              centerRight.setLayout(gbl);
              centerRight.setPreferredSize(new Dimension(500,200));
              centerRight.setBorder(BorderFactory.createRaisedBevelBorder());
              //EAST
              eastPanel.setLayout(eastGrid);
              eastRight.setLayout(new GridLayout(1,1));
              eastEastTop.setLayout(new FlowLayout(FlowLayout.LEFT));
              eastEastCenter.setLayout(new FlowLayout(FlowLayout.CENTER));
              eastPanel.setBorder(BorderFactory.createEtchedBorder());
              //SOUTH
              southPanel.setBorder(BorderFactory.createRaisedBevelBorder());
              southPanel.setLayout(southBorder);
              southPanel.setPreferredSize(new Dimension(0,227));
              southTop.setLayout(westGrid);
              southLeft.setLayout(southGrid);
              southLeft.setPreferredSize(new Dimension(70,0));
              //southLeft.setBorder(BorderFactory.createRaisedBevelBorder());
              //southRight.setLayout(westGrid);
              southCenter.setLayout(southFlo);
              southCenter.setPreferredSize(new Dimension(100,200));
              southCenter.setBorder(BorderFactory.createRaisedBevelBorder());
              //add to scrolling pane
              scrollpane = new JScrollPane(employees);
              scrollpane.getViewport().add(employees);
              CREATING AN INSTANCE OF JTABLE
              JTable table = new JTable(new MyTableModel());
              table.setPreferredScrollableViewportSize(new Dimension(200,200));
              ADDING THE TABLE TO THE SCROLLPANE2
              scrollpane2 = new JScrollPane(table);
              //scrollpane2.getViewport().add(servicePanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane3 = new JScrollPane(listEmpl);
              scrollPane3.getViewport().add(listEmpl);
              scrollPane4 = new JScrollPane(listSchedule);
              scrollPane4.getViewport().add(listSchedule);
              //get the content pane
              Container pane = getContentPane();
              JPanel calendars = new JPanel(new GridLayout(0,1));
              JScrollPane jsp = new JScrollPane(calendars);
              GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);
         for (int i=0; i<12; i++)
         calendars.add(new CalendarPanel(gc,this));
         gc.add(GregorianCalendar.MONTH, 1);
              cmbServices.setEditable(true);
              //add components to the panels
              northPanel.add(lblsouthHeading);
              westTop.add(lblEmployees);
              westTop.add(scrollpane);
              westCenter.add(hireButton);
              westCenter.add(employeeName);
              westCenter.add(fireButton);
              westCenter.add(addServices);
              westCenter.add(serviceName);
              westCenter.add(removeServices);
              westLeft.add(westTop);
              westLeft.add(westCenter);
         ADDING THE SCROLLPANE2 WHICH HOLDS
         JTABLE TO THE WESTRIGHT PANEL
         THEN FINALY TO THE WESTPANEL
              westRight.add(scrollpane2);
              westRight.add(new JLabel("TEST"));
              westPanel.add(westLeft);
              westPanel.add(westRight);
              //westPanel.add(westCenter);
              //westPanel.add(westBottom,BorderLayout.SOUTH);
              westPanel.setBorder(BorderFactory.createRaisedBevelBorder());
              eastLeft.add(lblSelect);
              eastLeft.add(scrollPane3);
              eastRight.add(eastLeft,BorderLayout.CENTER);
              eastRight.add(jsp,BorderLayout.EAST);
              //eastEastTop.add(lblEmployeeName);
              //eastEastTop.setBackground(Color.black);
              //eastEastTop.add(lblMonthStat);
              eastEastTop.add(lblDay);
              eastEastTop.add(lblYear);
              eastPanel.add(eastRight,BorderLayout.CENTER);
              eastPanel.add(eastEastTop);
              //eastPanel.add(eastEastCenter);
              //eastPanel.add(eastBottom,BorderLayout.SOUTH);
              southTop.add(lblBizHours);
              //southLeft.add(scrollpane);
              southLeft.add(listDays);
              southCenter.add(lblStartTime);
              southCenter.add(txtOpenTime);
              southCenter.add(startAmPm);
              southCenter.add(lblEndTime);
              southCenter.add(txtClosedTime);
              southBottom.add(btnNextDay = new JButton("Next Day"));
              southCenter.add(endAmPm);
              southPanel.add(southTop,BorderLayout.NORTH);
              southPanel.add(southLeft,BorderLayout.WEST);
              southPanel.add(southCenter,BorderLayout.CENTER);
              //southPanel.add(jsp,BorderLayout.EAST);
              southPanel.add(southBottom,BorderLayout.SOUTH);
              int row =1;
              lblOpen = new JLabel("Start Time",lblOpen.RIGHT);
              lblClosed = new JLabel("Quiting Time",lblClosed.RIGHT);
              lblDayOff = new JLabel("Day Off");
              space5 = new JLabel();
              centerLeft.add(lblEmployeeName);
              addComp(centerRight,lblDayOff,gbl,gbc,0,5,1,1,1,1);
              for(int i=0;i<dow.length;i++){
                   weekDay[i]= new JLabel(""+dow[i],weekDay[i].LEFT);
                   colon = new JLabel(":",colon.CENTER);
                   colon2 = new JLabel(":",colon2.CENTER);
                   weekDay[i].setForeground(Color.red);
                   startHr[i] = new JTextField("",1);
                   keyListener kl=new keyListener();
                   startHr[i].addKeyListener(kl);
                   startMin[i] = new JTextField("",1);
                   startMin[i].addKeyListener(kl);
                   finishHr[i] = new JTextField("",1);
                   finishHr[i].addKeyListener(kl);
                   finishMin[i] = new JTextField("",1);
                   finishMin[i].addKeyListener(kl);
                   btnUpdate[i] = new JButton("Update");
                   dayOff[i] = new JCheckBox();
                   dayOff[i].addItemListener(this);
                   space = new JLabel();
                   space2 = new JLabel();
                   space3 = new JLabel();
                   space4 = new JLabel();
                   btnUpdate[i].setBorder(BorderFactory.createRaisedBevelBorder());
                   //lblOpen = new JLabel("Shift Start",lblOpen.RIGHT);
                   //lblClosed = new JLabel("Shift End",lblClosed.RIGHT);
                   openAmPm[i] = new JComboBox();
                   closedAmPm[i] = new JComboBox();
                   openAmPm[i].addItem("AM");
                   openAmPm[i].addItem("PM");
                   closedAmPm[i].addItem("AM");
                   closedAmPm[i].addItem("PM");
                   addComp(centerRight,space,gbl,gbc,row,2,1,1,1,1);
                   addComp(centerRight,weekDay[i],gbl,gbc,row,3,1,1,1,1);
                   addComp(centerRight,space3,gbl,gbc,row,4,1,1,1,1);
                   addComp(centerRight,dayOff[i],gbl,gbc,row,5,1,1,1,1);
                   //addComp(centerRight,lblOpen,gbl,gbc,row,6,1,1,1,1);
                   addComp(centerRight,startHr[i],gbl,gbc,row,7,1,1,1,1);
                   addComp(centerRight,colon,gbl,gbc,row,8,1,1,1,1);
                   addComp(centerRight,startMin[i],gbl,gbc,row,9,1,1,1,1);
                   addComp(centerRight,openAmPm[i],gbl,gbc,row,10,1,1,1,1);
                   //addComp(centerRight,lblClosed,gbl,gbc,row,11,1,1,1,1);
                   addComp(centerRight,finishHr[i],gbl,gbc,row,12,1,1,1,1);
                   addComp(centerRight,colon2,gbl,gbc,row,13,1,1,1,1);
                   addComp(centerRight,finishMin[i],gbl,gbc,row,14,1,1,1,1);
                   addComp(centerRight,closedAmPm[i],gbl,gbc,row,15,1,1,1,1);
                   addComp(centerRight,space4,gbl,gbc,row,16,1,1,1,1);
                   addComp(centerRight,btnUpdate[i],gbl,gbc,row,17,1,1,1,1);
                   addComp(centerRight,space2,gbl,gbc,row,18,1,1,1,1);
                   row++;
              }//end for loop
              //add the panels
              //pane.add(northPanel,BorderLayout.NORTH);
              //pane.add(centerRight,BorderLayout.CENTER);
              //pane.add(westPanel,BorderLayout.WEST);
         //     pane.add(eastPanel,BorderLayout.EAST);
         //     pane.add(southPanel,BorderLayout.SOUTH);
              centerPanel.add(centerLeft);
              centerPanel.add(centerRight);
              //set up tabbed pane
              jtp = new JTabbedPane();
              jtp.addTab("Schedule",centerPanel);
              jtp.addTab("Employees",westPanel);
              jtp.addTab("Holidays",eastPanel);
              jtp.addTab("Business Hours",southPanel);
              pane.add(jtp,BorderLayout.CENTER);
         }//end init
         private void addComp(JPanel panel,Component c,GridBagLayout gbl,
                        GridBagConstraints gbc, int row,
                        int column, int numRows, int numColumns,
                        int weightx, int weighty)
                   gbc.gridy = row;
                   gbc.gridx = column;
                   gbc.gridheight = numRows;
                   gbc.gridwidth = numColumns;
                   gbc.weightx = weightx;
                   gbc.weighty = weighty;
                   //set the constraints in the GridBagLayout
                   gbl.setConstraints(c,gbc);
                   panel.add(c);
              }//end addcomp
         public void actionPerformed(ActionEvent e)
              //This method can be called only if
              //there's a valid selection
              int intLength;
              String command=e.getActionCommand();
              int listIndex1 = listEmpl.getSelectedIndex();
              int listIndex2 = listServices.getSelectedIndex();
              String firstName=null;
              //String service=null;
              if(command.equals("Add Employee"))
                   firstName = employeeName.getText();
                   //employeeName.setText(""+index);
                   //User didn't type in a unique name...
                   if (firstName.equals("") || alreadyInList(nameData,firstName))
                        Toolkit.getDefaultToolkit().beep();
                        employeeName.requestFocusInWindow();
                        employeeName.selectAll();
                        return;
                   }//end if
                   //int index = listEmpl.getSelectedIndex();
                   //get selected index
                   //if (listIndex1 == -1)
                        //no selection, so insert at beginning
                        //listIndex1 = 0;
                        //employeeName.setText("listIndex=-1");
                   //}//end if
                   else
                        //add after the selected item
                        //promptServices();
                        nameData.addElement(firstName);
                        size=nameData.getSize();
                        //fill the employee combobox
                        //employees.addItem(firstName);
                        holidayData.addElement(firstName);
                        listIndex1++;
                        employeeName.setText("size is "+size);
                        //Reset the text field.
                        employeeName.requestFocusInWindow();
                        employeeName.setText("");
                        scrollpane.revalidate();
                        scrollpane.repaint();
              }//end if
              if(command.equals("Remove Employee"))
                   nameData.remove(listIndex1);
                   holidayData.remove(listIndex1);
                   //removed item in last position
                   listIndex1--;
                   size = nameData.getSize();
                   employeeName.setText("size is "+size);
                   if (size==0)
                        //Nobody's left, disable firing.
                        fireButton.setEnabled(false);
                   }//end if
                   else
                   //Select an index.
                   if (listIndex1 == nameData.getSize())
                        listEmpl.setSelectedIndex(listIndex1);
                        listEmpl.ensureIndexIsVisible(listIndex1);
                   }//end if
              }//end if
              HERE IS WHERE A NEW ROW WITH A SERVICE AND DURRATION SHOULD BE ADDED TO THE JTABLE
              EACH TIME THE BUTTON IS CLICKED
              if(command.equals("Add Service"))
                        service=serviceName.getText();
                        if (service.equals("") || alreadyInList(serviceData,service))
                             Toolkit.getDefaultToolkit().beep();
                             serviceName.requestFocusInWindow();
                             serviceName.selectAll();
                             return;
                        }//end if
                        else
                             do{
                             timeText = JOptionPane.showInputDialog(listServices, "Enter the time allowed in minutes for \n a "+service+ " appointment");
                             totalResult=validateInputBox(timeText);
                             }while(!totalResult);
                             repaint();
                             //add after the selected item
                             //serviceData.addElement(service+" "+ timeText+ minutes);
                             //cmbServices.addItem(service);
                             serviceName.requestFocusInWindow();
                             serviceName.setText("");
                             listIndex2++;
                             //scrollpane.revalidate();
                             //scrollpane.repaint();
                             scrollpane2.revalidate();
                             scrollpane2.repaint();
                             //int time = Integer.parseInt(timeText);
                   }//end else
              }//end if
         /*     else if(command.equals("Remove Service"))
                   System.out.println("Selected:"+CheckServices.selected);
                   if(CheckServices.selected){
                        //for(int i=0;i<
                        servicePanel.remove(CheckServices.newChk);
                        servicePanel.remove(CheckServices.lengthLbl);
                        repaint();
                   int index = listEmpl.getSelectedIndex();
                   serviceData.remove(listIndex2);
                   //removed item in last position
                   listIndex2--;
                   size = serviceData.getSize();
                   //employeeName.setText("size is "+size);
                   if (size == 0)
                        //Nobody's left, disable firing.
                        removeServices.setEnabled(false);
                   }//end if
                   else
                   //Select an index.
                   if (listIndex2 == serviceData.getSize())
                        listServices.setSelectedIndex(listIndex2);
                        listServices.ensureIndexIsVisible(listIndex2);
                   }//end if
              }//end if
              //Select the new item and make it visible.
              //listEmpl.setSelectedIndex(listIndex1);
              //listEmpl.ensureIndexIsVisible(listIndex1);
              //listServices.ensureIndexIsVisible(listIndex2);
              //listServices.setSelectedIndex(listIndex2);
         }//end actionperformed
         public void itemStateChanged(ItemEvent e)
              boolean selected=false;
              int status = e.getStateChange();
              if(status==ItemEvent.SELECTED)
                   for(int i=0;i<dayOff.length;i++)
                        if(dayOff[i].isSelected())
                             int index = i;
                             startHr[i].setEditable(false);
                             startHr[i].setText("DAY OFF");
                             startMin[i].setEditable(false);
                             finishHr[i].setEditable(false);
                             finishMin[i].setEditable(false);
                        }//end if
                   }//end for
              }//end if
              if(status==ItemEvent.DESELECTED)
                   for(int i = 0;i<dayOff.length;i++)
                        if(!dayOff[i].isSelected())
                             startHr[i].setEditable(true);
                             startMin[i].setEditable(true);
                             finishHr[i].setEditable(true);
                             finishMin[i].setEditable(true);
                        }//end if
                   }//end for
              }//end if
         public boolean validateInputBox(String t)
              result=false;
              int intLength= t.length();
              if(intLength <=3)
                   for(int i = 0;i<intLength;i++)
                        if(!Character.isDigit(timeText.charAt(i)))
                             JOptionPane.showMessageDialog(listServices,message2 );
                             return result;
                             //break;
                   result=true;
                   return result;
              }//end if
              else{
              JOptionPane.showMessageDialog(listServices,message1 );
              return result;
         }//end validate method
              //This method tests for string equality. You could certainly
              //get more sophisticated about the algorithm. For example,
              //you might want to ignore white space and capitalization.
              protected boolean alreadyInList(DefaultListModel myList,String name)
                   return myList.contains(name);
         //handler for list selection changes
         public void valueChanged(ListSelectionEvent event)
              if(event.getSource()==listEmpl && !event.getValueIsAdjusting())
                   /**Load up any relating service information from the database
                   for the selected employee. If there is no record then reset the
                   serviceData list to empty so new services can be added
                   if(dbRecord){
                        serviceData.addElement("Record added");
                        dbRecord=false;
                   else
                        serviceData.clear();
              }//end if
              if(event.getSource()==employees ||event.getSource()==listEmpl && !event.getValueIsAdjusting()){
                   System.out.println("value changed");
                   int index = employees.getSelectedIndex();
                   Object item =employees.getModel().getElementAt(index);
                   lblEmployeeName.setText((String)item);
                   //lblEmployeeName.setText("Changed");
                   //centerLeft.add(lblEmployeeName);
         }//end valueChanged
         public void promptServices()
              JOptionPane.showMessageDialog(employees,"Enter a service");
    HERE IS THE MYTABLEMODEL CLASS. NOTE:ELEMENT INTEGER(5) WILL BE REPLACED
    WITH THE VARIABLE TIMETEXT BECAUSE THIS ELEMENT IS USER DEFINED BUT
    DOING SO RIGHT NOW THROWS AN ERROR
    class MyTableModel extends AbstractTableModel{
                   String columnNames[] = {"Service", "Minutes", "Select"};
                   Object data[][] = { {service, new Integer(5), new Boolean(false)} };
                        public int getColumnCount()
                             return columnNames.length;
                        public int getRowCount()
                             return data.length;
                        public String getColumnName(int col)
                             return columnNames[col];
                        public Object getValueAt(int row, int col)
                             return data[row][col];
              /* * JTable uses this method to determine the default renderer
                        / * editor for each cell. If we didn't implement this method,
                        * then the last column would contain text ("true"/"false"),
                        * rather than a check box. */
         public Class getColumnClass(int c)
                   THIS LINE IS THROWING A NULLPOINTEREXCEPTION ERROR
                   return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
              System.out.println("hey hey hey");
    //Note that the data/cell address is constant
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    //public void setValueAt(Object value, int row, int col) {
    // data[row][col] = value;
    // fireTableCellUpdated(row, col);
    class keyListener extends java.awt.event.KeyAdapter
    //key listener class watches character count
         public void keyTyped(java.awt.event.KeyEvent event){
         Object object = event.getSource();
         for(int i =0; i<7;i++)
              if (object == startHr[i])
                   if ( startHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume(); //if over limit, pretend nothing happened..
              if(object ==startMin[i])
                   if ( startMin[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume();
              if(object==finishHr[i])
                   if ( finishHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume();
              if(object==finishMin[i])
                   if ( finishMin[i].getText().length()>MAX_CHARS && event.getKeyChar(

    Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.So why do you start by writing a 1000 line program. Start with something small. Understand how they work and then incorporate it into your program.
    First. Use the DefaultTableModel. It will do everything you need. Why reinvent the wheel by extending AbstractTableModel. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418866]posting shows how to create a table and populate it with some data in 5 lines of code or less. It also gives examples of adding new rows of data to the DataModel (something your TableModel can't do) in a couple of lines of code.
    Next, we have Basic Debugging 101. If you have a NullPointerException, then you need to determine which variable is null. I simply added the following code before the line that was causing the problem:
    System.out.println(getValueAt(0, c) + " : " + c);
    return getValueAt(0, c).getClass();
    The value in column 0 was null. So where does the value from the first column come from. Well in your TableModel you tried to create it with one default row of data:
    Object data[][] = { {service, new Integer(5), new Boolean(false)} };
    So it would appear the "service" variable is null.
    Don't post 1000 lines programs again. Create simple code that demonstrates the problem. Chances are while your creating this demo program you will resolve your problem.

  • Update JTable model col through header name in fast way

    old day, i update my JTable model through the way :
    tableModel.setValueAt(aValue, rowIndex, jTable1.getColumn("HeaderName").getModelIndex());now, i am adding a feature to my table, where the user can remove column.
    when user remove the column, is just the JTable GUI column being removed,. the underlining TableModel column is still there.
    my new feature will broke my above code.
    hence, i change my code to :
    for(columnIndex=0; columnIndex<columnCount; columnIndex++) {
         String name = tableModel.getColumnName(columnIndex)
         if(name.equals("HeaderName"))
              tableModel.setValueAt(aValue, rowIndex, columnIndex)
    }instead of looping through, is there any way i can retrieve the column model index in a fast way?
    a way i can think off, is inherit from DefaultTableModel, and add a map member, so that it can directly map the header name to col index.
    is there any better way?
    thanks

    i don't know why but the KeyListener does work fine with another application that i have also created Not a good solution. First of all the column still exists, so the user will tab from one column to your "hidden" column and wonder whats happening.
    The correct solution is to remove the TableColumn from the TableColumnModel. You can still access the data in the TableModel:
    table.getModel().getValueAt(...)
    No need to use the convertColumnIndexToModel.

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • Implementing Copy and Paste on JTable cells.

    Hi to all,
    Can anybody suggest as how to impose copy and paste with Ctrl-C and Ctrl-V by using keys on JTable cells.
    Thanks in advance.
    khiz_eng

    First, add a key listener to the table itself (most likely in the constructor for your table), like so:
      addKeyListener(new KeyListener()
        public void keyTyped(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {}
        public void keyPressed(KeyEvent e)
          tableKeyPressed(e);
      });Next, add the code for the "tableKeyPressed" method. Here's a skeleton you can use as a starting point (obviously, the exact code to copy and paste will depend on the nature of the data you are trying to transfer).
      protected void tableKeyPressed(KeyEvent e)
        // Get selected cols and rows:
        int[] selectedRows = getSelectedRows();
        int[] selectedCols = getSelectedColumns();
        // A "copy" is signified by either ctrl+c, meta+c, or the "copy" button on a Sun keyboard.
        // Unfortunately, Java does not abstract this for us, so we have to test each of these conditions:
        if ((e.getKeyCode() == KeyEvent.VK_COPY) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isControlDown()) ||
            ((e.getKeyCode() == KeyEvent.VK_C) && e.isMetaDown()))
          // Grab the cell(s) that are currently selected by using the selectedRows
          // and selectedCols arrays from above.  Then copy this data to the clipboard.
        // A "paste" is signified by either ctrl+v, meta+v, or the "paste" button on a Sun keyboard.
        // Again, Java does not abstract this for us, so each condition must be tested:
        else if ((e.getKeyCode() == KeyEvent.VK_PASTE) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isControlDown()) ||
             ((e.getKeyCode() == KeyEvent.VK_V) && e.isMetaDown()))
          // Make sure there is valid data in the clipboard.
          // If so, paste it into the selected cell(s).
      }(By the way, this code assumes that you are running on a Sun machine with a Sun keyboard. If you are only targeting windows boxes, then the only key press you really need to worry about is CTRL+C. There's no harm in leaving the other keys in, though.
    Hope that helps,
    Steve

  • KeyListener on combobox calander not working?

    Am trying to add keylistener on this combobox calander, but somehow its not working right. The calendar is added to a JTable and the keyListener on it works, when i gets focus, but when the popup is visible it looses the keylistener? Can someone help me with this?
    import com.sun.java.swing.plaf.motif.*;
    import com.sun.java.swing.plaf.windows.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.table.*;
    public class DateComboBox extends JComboBox
        public DateComboBox()
        public DateComboBox(int raekke,DefaultTableModel model,JTable tabel)
            this.raekke=raekke;
            this.model=model;
            this.tabel=tabel;
        public void setDateFormat(SimpleDateFormat dateFormat)
            this.dateFormat = dateFormat;
        public void setSelectedItem(Object item)
            // Could put extra logic here or in renderer when item is instanceof Date, Calendar, or String
            // Dont keep a list ... just the currently selected item
            removeAllItems(); // hides the popup if visible
            addItem(item);
            super.setSelectedItem(item);
        public void setText(String texte)
            setSelectedItem(texte);
        public String getText()
            return (String)this.getSelectedItem();
        public void setRaekke(int raekke)
            this.raekke=raekke;
        public void updateUI()
            ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
            if (cui instanceof MetalComboBoxUI)
                cui = new MetalDateComboBoxUI();
            } else if (cui instanceof MotifComboBoxUI)
                cui = new MotifDateComboBoxUI();
            } else if (cui instanceof WindowsComboBoxUI)
                cui = new WindowsDateComboBoxUI();
            setUI(cui);
        // Inner classes are used purely to keep DateComboBox component in one file
        // UI Inner classes -- one for each supported Look and Feel
        class MetalDateComboBoxUI extends MetalComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        class WindowsDateComboBoxUI extends WindowsComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        class MotifDateComboBoxUI extends MotifComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        // DatePopup inner class
        class DatePopup implements
        ComboPopup,
        MouseMotionListener,
        MouseListener,
        KeyListener,
        PopupMenuListener
            public DatePopup(JComboBox comboBox)
                this.comboBox = comboBox;
                setFocusable(true);
                addKeyListener(this);
                calendar = Calendar.getInstance();
                // check Look and Feel
                background = UIManager.getColor("ComboBox.background");
                foreground = UIManager.getColor("ComboBox.foreground");
                selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
                selectedForeground = UIManager.getColor("ComboBox.selectionForeground");
                initializePopup();
            //========================================
            // begin ComboPopup method implementations
            public void show()
                try
                    // if setSelectedItem() was called with a valid date, adjust the calendar
                    calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
                } catch (Exception e)
                {e.printStackTrace();}
                updatePopup();
                popup.show(comboBox, 0, comboBox.getHeight());
            public void hide()
                popup.setVisible(false);
            protected JList list = new JList();
            public JList getList()
                return list;
            public MouseListener getMouseListener()
                return this;
            public MouseMotionListener getMouseMotionListener()
                return this;
            public KeyListener getKeyListener()
                return null;
            public boolean isVisible()
                return popup.isVisible();
            public void uninstallingUI()
                popup.removePopupMenuListener(this);
            // end ComboPopup method implementations
            //======================================
            //===================================================================
            // begin Event Listeners
            // MouseListener
            public void mousePressed( MouseEvent e )
            // something else registered for MousePressed
            public void mouseClicked(MouseEvent e)
            public void mouseReleased( MouseEvent e )
                if (!SwingUtilities.isLeftMouseButton(e))
                    return;
                if (!comboBox.isEnabled())
                    return;
                if (comboBox.isEditable())
                    comboBox.getEditor().getEditorComponent().requestFocus();
                else
                    comboBox.requestFocus();
                togglePopup();
            protected boolean mouseInside = false;
            public void mouseEntered(MouseEvent e)
                mouseInside = true;
            public void mouseExited(MouseEvent e)
                mouseInside = false;
            // MouseMotionListener
            public void mouseDragged(MouseEvent e)
            public void mouseMoved(MouseEvent e)
            public void keyPressed(KeyEvent e)
                if(e.getSource()==this)
                    if(e.getKeyCode()==KeyEvent.VK_CONTROL)
                        System.out.println("keytyped1");
            public void keyTyped(KeyEvent e)
            public void keyReleased( KeyEvent e )
                if(e.getKeyCode()==KeyEvent.VK_CONTROL)
                    System.out.println("keytyped2");
                if ( e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER )
                    togglePopup();
             * Variables hideNext and mouseInside are used to
             * hide the popupMenu by clicking the mouse in the JComboBox
            public void popupMenuCanceled(PopupMenuEvent e)
            protected boolean hideNext = false;
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
                hideNext = mouseInside;
            public void popupMenuWillBecomeVisible(PopupMenuEvent e)
            // end Event Listeners
            //=================================================================
            //===================================================================
            // begin Utility methods
            protected void togglePopup()
                if( isVisible() || hideNext)
                    hide();
                else
                    show();
                hideNext = false;
            // end Utility methods
            //=================================================================
            // Note *** did not use JButton because Popup closes when pressed
            protected JLabel createUpdateButton(final int field, final int amount)
                final JLabel label = new JLabel();
                final Border selectedBorder = new EtchedBorder();
                final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
                label.setBorder(unselectedBorder);
                label.setForeground(foreground);
                label.addMouseListener(new MouseAdapter()
                    public void mouseReleased(MouseEvent e)
                        calendar.add(field, amount);
                        updatePopup();
                    public void mouseEntered(MouseEvent e)
                        label.setBorder(selectedBorder);
                    public void mouseExited(MouseEvent e)
                        label.setBorder(unselectedBorder);
                return label;
            protected void initializePopup()
                JPanel header = new JPanel();
                header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
                header.setBackground(background);
                header.setOpaque(true);
                JLabel label;
                label = createUpdateButton(Calendar.YEAR, -1);
                label.setText("<<");
                label.setToolTipText("Sidste �r");
                header.add(Box.createHorizontalStrut(12));
                header.add(label);
                header.add(Box.createHorizontalStrut(12));
                label = createUpdateButton(Calendar.MONTH, -1);
                label.setText("< ");
                label.setToolTipText("Sidste m�ned");
                header.add(label);
                monthLabel = new JLabel("", JLabel.CENTER);
                monthLabel.setForeground(foreground);
                header.add(Box.createHorizontalGlue());
                header.add(monthLabel);
                header.add(Box.createHorizontalGlue());
                label = createUpdateButton(Calendar.MONTH, 1);
                label.setText(" >");
                label.setToolTipText("N�ste m�ned");
                header.add(label);
                label = createUpdateButton(Calendar.YEAR, 1);
                label.setText(">>");
                label.setToolTipText("N�ste �r");
                header.add(Box.createHorizontalStrut(12));
                header.add(label);
                header.add(Box.createHorizontalStrut(12));
                popup = new JPopupMenu();
                popup.setBorder(BorderFactory.createLineBorder(Color.black));
                popup.setLayout(new BorderLayout());
                popup.setBackground(background);
                popup.addPopupMenuListener(this);
                popup.add(BorderLayout.NORTH, header);
                popup.getAccessibleContext().setAccessibleParent(comboBox);
            // update the Popup when either the month or the year of the calendar has been changed
            protected void updatePopup()
                monthLabel.setText( monthFormat.format(calendar.getTime()) );
                if (days != null)
                    popup.remove(days);
                days = new JPanel(new GridLayout(0, 7));
                days.setBackground(background);
                days.setOpaque(true);
                Calendar setupCalendar = (Calendar) calendar.clone();
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
                for (int i = 0; i < 7; i++)
                    int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
                    JLabel label = new JLabel();
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setForeground(foreground);
                    if (dayInt == Calendar.SUNDAY)
                        label.setText("s�n");
                    else if (dayInt == Calendar.MONDAY)
                        label.setText("man");
                    else if (dayInt == Calendar.TUESDAY)
                        label.setText("tir");
                    else if (dayInt == Calendar.WEDNESDAY)
                        label.setText("ons");
                    else if (dayInt == Calendar.THURSDAY)
                        label.setText("tor");
                    else if (dayInt == Calendar.FRIDAY)
                        label.setText("fre");
                    else if (dayInt == Calendar.SATURDAY)
                        label.setText("l�r");
                    //                days.add(label);
                    setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
                setupCalendar = (Calendar) calendar.clone();
                setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
                int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
                for (int i = 0; i < (first-2) ; i++)
                    days.add(new JLabel(""));
                for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++)
                    final int day = i;
                    final JLabel label = new JLabel(String.valueOf(day));
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setForeground(foreground);
                    label.addMouseListener(new MouseAdapter()
                        public void mouseReleased(MouseEvent e)
                            label.setOpaque(false);
                            label.setBackground(background);
                            label.setForeground(foreground);
                            calendar.set(Calendar.DAY_OF_MONTH, day);
                            hide();
                            comboBox.requestFocus();
                            if (tabel.isEditing())
                                tabel.getCellEditor(tabel.getEditingRow(),
                                tabel.getEditingColumn()).stopCellEditing();
                            model.setValueAt(dateFormat.format(calendar.getTime()),raekke,1);
                            tabel.requestFocus();
                        public void mouseEntered(MouseEvent e)
                            label.setOpaque(true);
                            label.setBackground(selectedBackground);
                            label.setForeground(selectedForeground);
                        public void mouseExited(MouseEvent e)
                            label.setOpaque(false);
                            label.setBackground(background);
                            label.setForeground(foreground);
                    days.add(label);
                popup.add(BorderLayout.CENTER, days);
                popup.pack();
            private JComboBox comboBox;
            private Calendar calendar;
            private JPopupMenu popup;
            private JLabel monthLabel;
            private JPanel days = null;
            private SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
            //        private int antaldage=1;
            private Color selectedBackground;
            private Color selectedForeground;
            private Color background;
            private Color foreground;
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        private int raekke=-1;
        private DefaultTableModel model;
        private JTable tabel;
    }

    come on help plz....

Maybe you are looking for