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.

Similar Messages

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • Can You Help Me ABout getSelectedRow in JTable

    Can you help me on how to solve my problem about the getSelectedRow .....
    I have one JComboBox and a SearchButton
    ... Once I selected an Item in a JComboBox, I will press the SearchButton
    and then it will look up to the database and display it in the JTable..........
    i used the getSelectedRow to print the value that I selected in the table...
    like this...
    public void mouseClicked(MouseEvent e) {
    // Ilabas yung form
    if(e.getClickCount() == 1 ) {
    System.out.println(table1.getSelectedRow());
    In the first press in the SearchButton and then clicking the row
    , It will print the selected row...... but when i press again the SearchButton then clicking a row again........
    there is a problem occured....... selectedRow is always -1, can you help me to solve this.....

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.text.*;
    import java.beans.*;
    public class OpenProject extends JDialog {
         ResultSet rs, rs1, rs2, rs3;
         JFrame JFParentFrame; // create a JFrame
         JFrame OwnerFrame; // create a JFrame
         public JLabel proj_name;
         public JLabel proj = new JLabel("Project Name:");
         public JLabel form = new JLabel("Form Name");
         public JLabel lang = new JLabel("Language");
         public JComboBox form_lang = new JComboBox();
         public JComboBox form_name = new JComboBox();
         public JButton edit = new JButton("Edit");
         public JButton reload = new JButton("Search");
         public JButton def = new JButton("Set Text Default");
         public JButton langs = new JButton("Add Language");
         public JButton exit = new JButton("Exit");
         public JPanel panel1 = new JPanel ();
         public JTable table1, table2, table3,table4;
         public JScrollPane scrollPane1, scrollPane2, scrollPane3, scrollPane4;
         public JTabbedPane UITab,UITab1;
         Container c = getContentPane();
         Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
         public String column[][];
         public String strRow;
         public String strCol;
         public String strForm;
         public String strGetProj_id;
         public String strForm_lang;
         public String strForm_name;
         private boolean DEBUG = false;
         public int getLang;
         public int getForm;
         public int getDef_id;
         public int count2 = 0,count3 = 0,count4 = 0;
         public int row2 = 0,row3 = 0,row4 = 0;
         public int selectedRow1 = 0, selectedRow2 = 0;
         public DbBean db = new DbBean();
         public OpenProject(JFrame OwnerForm, String getProj_id) {
              super(OwnerForm,true);
                   strGetProj_id = getProj_id;
              try{
                   db.connect();
              } catch(SQLException sqlex) {
              } catch(ClassNotFoundException cnfex) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch(Exception e) {
              // Para ito sa paglalagay sa dalawang combo box ng value.......
              try {
                   rs = db.execSQL("Select * from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   rs = db.execSQL("Select distinct from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   int counts;
                   rs = db.execSQL("Select * from mst_project where proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        counts = rs.getInt("proj_lang_id");
                        System.out.println(counts);
                        rs1 = db.execSQL("Select * from mst_language where lang_id = "+counts+"");
                        while (rs1.next()) {
                             form_lang.addItem(rs1.getString("lang_name"));     
              } catch(SQLException sqlex) {
              edit.setActionCommand("edit");
              edit.addActionListener(actions);
              reload.setActionCommand("load");
              reload.addActionListener(actions);
              def.setActionCommand("default");
              def.addActionListener(actions);
              langs.setActionCommand("lang");
              langs.addActionListener(actions);
              exit.setActionCommand("exit");
              exit.addActionListener(actions);
              proj_name = new JLabel();     
              proj_name.setBackground(new Color(255,255,255));
              form_name.setMaximumRowCount(5);
              form_name.setBackground(new Color(255,255,255));
              form_lang.setMaximumRowCount(5);
              form_lang.setBackground(new Color(255,255,255));
              proj.setBounds(20, 20,100,20);
              proj_name.setBounds(120, 20,250,20);
              form.setBounds(20, 50,100,20);
              form_name.setBounds(120, 50,150,20);
              lang.setBounds(300, 50,100,20);     
              form_lang.setBounds(380, 50,150,20);
              reload.setBounds(560,50,80, 20);
              edit.setBounds(110,360,115,20);
              def.setBounds(230,360,115,20);
              langs.setBounds(350,360,115,20);
              exit.setBounds(470,360,115,20);
              panel1.add(getTable());
              panel1.setLayout(null);     
              panel1.setBackground(Color.white);     
              panel1.add(proj);
              panel1.add(proj_name);
              panel1.add(form);
              panel1.add(form_name);
              panel1.add(lang);
              panel1.add(form_lang);
              panel1.add(reload);     
              panel1.add(def);
              panel1.add(langs);
              panel1.add(exit);
              panel1.add(edit);
              c.add(panel1);
              setSize(680,420);
              setTitle("Open Project");
              setLocation((screen.width - 590)/2,((screen.height - 280)/2) - 45);
         public JTabbedPane getTable() {
              UITab = new JTabbedPane();
              strForm_lang = form_lang.getSelectedItem().toString();
              strForm_name = form_name.getSelectedItem().toString();
              int count1=0;
              int row1=0;
              try {
                   rs = db.execSQL("Select * from mst_default where def_proj_id = '"+strGetProj_id+"' AND def_category = 'Title'" );
                   while(rs.next()) {
                        count1 += 1;
                        getDef_id = rs.getInt("def_id");
                   column = new String[count1][2];
                   rs1 = db.execSQL("Select form_id from mst_form WHERE form_name = '"+strForm_name+"'");
                   while(rs1.next()) {
                        getForm = rs1.getInt("form_id");
                        System.out.println("getForm");
                   rs2 = db.execSQL("Select lang_id from mst_language WHERE lang_name = '"+strForm_lang+"'");
                   while(rs2.next()) {
                        getLang = rs2.getInt("lang_id");
                        System.out.println("getLang");
                   rs3 = db.execSQL("Select * from mst_default a, mst_translation b WHERE a.def_form_id = '"+getForm+"' AND b.trans_lang_id = '"+getLang+"' AND a.def_proj_id = '"+strGetProj_id+"' AND b.trans_def_id = '"+getDef_id+"' AND a.def_category = 'Title' " );
                   while(rs3.next()) {
                        column[row1][0] = "" + rs3.getString("display_name");          // rowNum ay kung ilan ang row na ilalabas
                   column[row1][1] = "" + rs3.getString("translation"); // Default yung isang array ng column ko, kaya fixed
                        row1++;
                   row1 = 0;
              } catch(SQLException sqlex) {
                   sqlex.printStackTrace();
                   System.exit(1);
              // End
              table1 = new JTable(new MyTableModel()){
              scrollPane1 = new JScrollPane(table1);
              UITab.setBounds(30,100,610,250);
              UITab.add("Title",scrollPane1);
              return UITab;
         class MyTableModel extends AbstractTableModel {     
                   // Pagawa ng header Coloumn
                   String ColumnHeaderName[] = {
                        "Default Text",""+strForm_lang+" Translation"
                   //End
                   public int getColumnCount() {     
                        //System.out.println("The Column Count is" + ColumnHeaderName.length);
         return ColumnHeaderName.length;
         public int getRowCount() {
              //System.out.println("The Row Count is" + column.length);
         return column.length;
         public String getColumnName(int col) {
                        //System.out.println("The Column Name is" + ColumnHeaderName[col]);     
         return ColumnHeaderName[col];
         public Object getValueAt(int row,int col) {
              System.out.println("The value at row and column = " + column[row][col]);
         return column[row][col];
         public int getSelectedRow() {
              System.out.println("Integer" + column.length);
              return column.length;
         ActionListener actions = new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                   String source = ae.getActionCommand();
                   if (source == "load") {
                        table1.clearSelection();
                        panel1.add(getTable());
                        table1.addNotify();
                        repaint();
                   } else if (source == "default") {
                        dispose();
                        TextDefaultForm form = new TextDefaultForm(OwnerFrame,JFParentFrame);
                        form.setVisible(true);
                   } else if (source == "lang") {
                        dispose();
                        CreateProject lang = new CreateProject(JFParentFrame);
                        lang.setVisible(true);
                   } else if (source == "exit") {
                        dispose();
                   } else if (source == "edit") {
                        if (table1.getValueAt(table1.getSelectedRow(),table1.getSelectedColumn()) != null){
                             formLang lang = new formLang(OwnerFrame,strCol,strRow, strGetProj_id);
                             lang.setVisible(true);
         MouseListener MouseTableListener = new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        // Ilabas yung form
                        if(e.getClickCount() == 2 ) {
                             dispose();
                             int col_a = 0;
                             int col_b = 1;
                             selectedRow1 = table1.getSelectedRow();     
                             Object objColumn1 = table1.getValueAt(selectedRow1, col_a);
                             Object objRow1 = table1.getValueAt(selectedRow1, col_b);
                             strCol = objColumn1.toString();
                             strRow = objRow1.toString();
                             formLang lang = new formLang(OwnerFrame,strCol,strRow,strGetProj_id);
                             System.out.println(selectedRow1);
                             System.out.println(strCol);
                             System.out.println(strRow);
                             lang.txtProj.setText(strCol);
                             lang.txtLang.setText(strRow);
                             lang.show();
                        } else if (e.getClickCount() == 1) {
                             table1.setSelectionBackground(Color.blue);
                             table1.setColumnSelectionAllowed(false);
                        table1.setRowSelectionAllowed(true);
                        table1.setFocusable(true);
                             int a = table1.getRowCount();
                             System.out.println("Row Count = " + a);
                             int sel = table1.getSelectedRow();     
                             //if (sel == -1) return;
                             System.out.println("Selected Row = " + sel);
                             System.out.println(table1.isRowSelected(sel));
                   public void mouseReleased(MouseEvent e) {
                   public void mouseExited(MouseEvent e) {
                   public void mouseEntered(MouseEvent e) {
                   public void mousePressed(MouseEvent e) {
         //public static void main(String leo[]) {
              //OpenProject open = new OpenProject();
    }

  • How to give different Colour to Columns in JTable

    Hi,
    I am using a JTable and entering Data into it. I want each column of the JTable to be in different colour. Kindly Help. Some example code will be very helpful.
    Waiting Eagerly.....
    My Code....
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.Window;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagLayout;
    import javax.swing.*;
    import java.util.Vector;
    import java.awt.GridLayout;
    import java.util.*;
    import javax.swing.table.TableModel;
    public class SummScr extends JPanel {
    public JTable ProSerSumTable;
    public String ColumnNames[];
    public String dataValues[][];
    //public Vector ProSerDet = new Vector();
    //constructor
    public SummScr(){     
    super(new GridLayout(1,0));
    createColumns();
    createData();
    TableModel ProSerTabMod = new AbstractTableModel(){
    public int getColumnCount(){return ColumnNames.length; }
    public int getRowCount(){return dataValues.length;}
    public Object getValueAt(int row, int col){return dataValues[row][col]; }
    public String getColumnName(int col){return ColumnNames[col];}
    public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
    public void setValueAt(Object aValue, int row, int col){dataValues[row][col] = (String)aValue; }
    ProSerSumTable = new JTable(ProSerTabMod);
    ProSerSumTable.setPreferredScrollableViewportSize(new Dimension(400,200));
    JScrollPane scrollpane = new JScrollPane(ProSerSumTable);
    //JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    //scrollpane.add(ProSerSumTable);
    add(scrollpane);
    public void createColumns(){
    ColumnNames = new String[4];
    ColumnNames[0] = "Processes";
    ColumnNames[1] = "Normal Threshold";
    ColumnNames[2] = "On Hold";
    ColumnNames[3] = "Exceeded Threshold";
    public void createData(){
    dataValues = new String[3][4];
    dataValues[0][0] = "Merit";
    dataValues[0][1] = "60%";
    dataValues[0][2] = "0%";
    dataValues[0][3] = "40%";
    dataValues[1][0] = "SuperMarket";
    dataValues[1][1] = "70%";
    dataValues[1][2] = "0%";
    dataValues[1][3] = "30%";
    dataValues[2][0] = "Passport";
    dataValues[2][1] = "65%";
    dataValues[2][2] = "0%";
    dataValues[2][3] = "35%";
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Summary Screen");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    SummScr newContentPane = new SummScr();
    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();
    }

    try this, also put your code into the code tags to help read your code
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class SummScr extends JPanel {
         private static final long serialVersionUID = 1L;
         public JTable ProSerSumTable;
         public String ColumnNames[];
         public String dataValues[][];
         // public Vector ProSerDet = new Vector();
         // constructor
         public SummScr() {
              super(new GridLayout(1, 0));
              createColumns();
              createData();
              TableModel ProSerTabMod = new AbstractTableModel() {
                   private static final long serialVersionUID = 1L;
                   public int getColumnCount() {
                        return ColumnNames.length;
                   public int getRowCount() {
                        return dataValues.length;
                   public Object getValueAt(int row, int col) {
                        return dataValues[row][col];
                   public String getColumnName(int col) {
                        return ColumnNames[col];
                   public Class<?> getColumnClass(int col) {
                        return getValueAt(0, col).getClass();
                   public void setValueAt(Object aValue, int row, int col) {
                        dataValues[row][col] = (String) aValue;
              ProSerSumTable = new JTable(ProSerTabMod);
              TableColumn tc = null;
    //next line sets the renderer to your columns, in this example there are only four columns so its fairly easy,
    //though it should be no harder no matter how many columns
              for(int i = 0; i < 4; i++){
                   tc = ProSerSumTable.getColumnModel().getColumn(i);
                   tc.setCellRenderer(new ColumnColourRenderer());
              ProSerSumTable.setPreferredScrollableViewportSize(new Dimension(400,
                        200));
              JScrollPane scrollpane = new JScrollPane(ProSerSumTable);
              // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              // scrollpane.add(ProSerSumTable);
              add(scrollpane);
         public void createColumns() {
              ColumnNames = new String[4];
              ColumnNames[0] = "Processes";
              ColumnNames[1] = "Normal Threshold";
              ColumnNames[2] = "On Hold";
              ColumnNames[3] = "Exceeded Threshold";
         public void createData() {
              dataValues = new String[3][4];
              dataValues[0][0] = "Merit";
              dataValues[0][1] = "60%";
              dataValues[0][2] = "0%";
              dataValues[0][3] = "40%";
              dataValues[1][0] = "SuperMarket";
              dataValues[1][1] = "70%";
              dataValues[1][2] = "0%";
              dataValues[1][3] = "30%";
              dataValues[2][0] = "Passport";
              dataValues[2][1] = "65%";
              dataValues[2][2] = "0%";
              dataValues[2][3] = "35%";
         private static void createAndShowGUI() {
              // Make sure we have nice window decorations.
              JFrame.setDefaultLookAndFeelDecorated(true);
              // Create and set up the window.
              JFrame frame = new JFrame("Summary Screen");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              SummScr newContentPane = new SummScr();
              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();
         class ColumnColourRenderer extends DefaultTableCellRenderer{
              public ColumnColourRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean cellHasFocus, int row, int column) {
                   if (column %2 == 0) {
                        setText((table.getModel().getValueAt(row, column)).toString());
                        if (isSelected) {
                              setBackground(table.getSelectionBackground());
                              setForeground(table.getSelectionForeground());
                        else {
                             setBackground(Color.RED);
                   } else if (column %2 != 0){
                        setText((table.getModel().getValueAt(row, column)).toString());
                        if (isSelected) {
                              setBackground(table.getSelectionBackground());
                              setForeground(table.getSelectionForeground());
                        else {
                             setBackground(Color.BLUE);
                   return this;
    }

  • JTable with JComboBox

    Hi friends,
    I am adding JComboBox in JTable its working properly
    But data is not adding dynamically to JComboBox
    I am Sending my Code plz give me reply
    I am Struggleing from 1 week on wards
    package com.dnt.autopopulation;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.event.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.TableModelEvent;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;
    import java.text.SimpleDateFormat;
    import java.util.Vector;
    import javax.swing.border.*;
    import com.dnt.eaip.Connectmagr;
    import com.dnt.eaip.*;
    import com.dnt.util.*;
    import javax.swing.plaf.ButtonUI;
    import com.dnt.admin.EndStartDateCheck;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    public class AutoPopRollBack extends JPanel {
    boolean selection = false;
    public static final int HAND_CURSOR = 12;
    Cursor cursor = new Cursor(HAND_CURSOR);
    int selectedRow = -1;
    ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
    JLabel HeaderLabe = new JLabel(headertop1);
    Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
    Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
    new Color(154, 254, 211), new Color(108, 178, 148),
    new Color(37, 60, 50), new Color(53, 87, 72));
    DefaultTableModel dm = new DefaultTableModel();
    Vector searchlist = new Vector();
    Vector rows = new Vector();
    Vector returnList;
    Connectmagr objConnectmagr = new Connectmagr();
    JFrame frame = new JFrame();
    JLabel headlab = new JLabel();
    JCalendarComboBox EndDateTxt;
    JLabel HawbLab = new JLabel();
    JTextField HawbTxt = new JTextField();
    JLabel AgentLab = new JLabel();
    JLabel StartDateLab = new JLabel();
    JCalendarComboBox StartDateTxt;
    JComboBox AgentLBox = new JComboBox();
    JLabel EnddateLab = new JLabel();
    JPanel ReviewJobsPane = new JPanel();
    JButton SearchBtn = new JButton();
    ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
    ArrayList AgentList = new ArrayList();
    JComboBox DocTypeLBox = new JComboBox();
    JLabel doctypelab = new JLabel();
    JPanel displayPanel = new JPanel();
    ButtonGroup group1;
    JRadioButton rb;
    JTable table;
    public ArrayList jobList = new ArrayList();
    public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
    this.frame = frame;
    this.AgentList = agentArrayList;
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public void jbInit() throws Exception {
    Calendar cal = Calendar.getInstance();
    Locale loc = new Locale("");
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    HeaderLabe.setBackground(new Color(250, 233, 216));
    HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
    this.setLayout(null);
    this.setBackground(SystemColor.control);
    headlab.setBackground(new Color(250, 233, 216));
    headlab.setFont(new java.awt.Font("Verdana", 1, 12));
    headlab.setForeground(Color.blue);
    headlab.setHorizontalAlignment(SwingConstants.CENTER);
    headlab.setText(" :: Auto Population Rollback");
    headlab.setBounds(new Rectangle(39, 2, 247, 25));
    EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
    EndDateTxt.setBackground(Color.white);
    EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EndDateTxt.setForeground(Color.blue);
    EndDateTxt.setBorder(null);
    HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
    HawbLab.setForeground(Color.blue);
    HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
    HawbLab.setText("Job No/Airway Bill No:");
    HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
    HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
    HawbTxt.setText("");
    HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    HawbTxt.setForeground(Color.blue);
    HawbTxt.setBorder(border1);
    AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
    AgentLab.setForeground(Color.blue);
    AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
    AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
    AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
    StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    StartDateLab.setForeground(Color.blue);
    StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    StartDateLab.setText("Start Date:");
    StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
    StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
    StartDateTxt.setBackground(Color.white);
    StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    StartDateTxt.setForeground(Color.blue);
    StartDateTxt.setBorder(null);
    AgentLBox.setBackground(Color.white);
    AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    AgentLBox.setForeground(Color.blue);
    AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
    AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    EnddateLab.setForeground(Color.blue);
    EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    EnddateLab.setText("End Date:");
    EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
    ReviewJobsPane.setBackground(new Color(240, 233, 216));
    ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
    ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
    ReviewJobsPane.setLayout(null);
    SearchBtn.setUI(ui);
    SearchBtn.setCursor(cursor);
    SearchBtn.setBackground(new Color(76, 125, 104));
    SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
    SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
    SearchBtn.setForeground(Color.white);
    SearchBtn.setBorder(border2);
    SearchBtn.setOpaque(true);
    SearchBtn.setFocusPainted(false);
    SearchBtn.setText("Search");
    SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
    for (int i = 0; i < AgentList.size(); i++)
    AgentLBox.addItem( (String) AgentList.get(i));
    DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    DocTypeLBox.setForeground(Color.blue);
    DocTypeLBox.setMinimumSize(new Dimension(22, 19));
    DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
    DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    DocTypeLBox.addItem("New Jobs");
    DocTypeLBox.addItem("Draft jobs");
    DocTypeLBox.addItem("Finished jobs");
    doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
    doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
    doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
    doctypelab.setForeground(Color.blue);
    doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
    displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
    this.add(headlab, null);
    this.add(HeaderLabe, null);
    this.add(ReviewJobsPane, null);
    ReviewJobsPane.add(HawbLab, null);
    ReviewJobsPane.add(AgentLab, null);
    ReviewJobsPane.add(AgentLBox, null);
    ReviewJobsPane.add(StartDateLab, null);
    ReviewJobsPane.add(StartDateTxt, null);
    ReviewJobsPane.add(HawbTxt, null);
    ReviewJobsPane.add(EnddateLab, null);
    ReviewJobsPane.add(EndDateTxt, null);
    ReviewJobsPane.add(DocTypeLBox, null);
    ReviewJobsPane.add(doctypelab, null);
    this.add(SearchBtn, null);
    this.add(displayPanel, null);
    //this.add(scrollPaneView, null);
    // scrollPaneView.getViewport().add(displayPanel, null);
    this.setVisible(true);
    void FieldEditable(boolean str) {
    StartDateTxt.setEnabled(str);
    EndDateTxt.setEnabled(str);
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    ArrayList agentlist = new ArrayList();
    agentlist.add(0, "BF0651");
    agentlist.add(1, "PF0010");
    AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
    frame.getContentPane().add(objAutoPopRollBack);
    frame.setBounds(new Rectangle(0, 0, 820, 593));
    frame.setVisible(true);
    void SearchBtn_actionPerformed(ActionEvent e) {
    displayPanel.setVisible(false);
    Vector data=new Vector();
    rows.removeAllElements();
    boolean flag = true;
    String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
    try {
    if(HawbTxt.getText().equalsIgnoreCase("")){
    if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(this, "Please Select Start Date",
    "Warning", JOptionPane.WARNING_MESSAGE);
    flag = false;
    else if (!che.equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
    flag = false;
    }else{
    FieldEditable(true);
    if (flag) {
    try {
    displayPanel.removeAll();
    } catch (Exception ex) {
    rows.removeAllElements();
    data.removeAllElements();
    SearchBtn.setEnabled(true);
    searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
    if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
    searchlist.add(1, HawbTxt.getText().toString().trim());
    else
    searchlist.add(1, "");
    searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
    String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
    String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
    Vector columns = new Vector();
    columns.add(0, "");
    columns.add(1, "JOB No");
    columns.add(2, "Status");
    columns.add(3, "Current Form Type");
    columns.add(4, "New Form Type");
    System.out.println("Before calling Data Base");
    jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
    if (jobList.size() > 0) {
    for (int i = 0; i < jobList.size(); i++) {
    ArrayList temp = new ArrayList();
    temp = (ArrayList) jobList.get(i);
    Vector col = new Vector();
    col.add(0, new Boolean(false));
    col.add(1, temp.get(0).toString().trim());
    col.add(2, temp.get(1).toString().trim());
    col.add(3, temp.get(2).toString().trim());
    Vector tempstr=new Vector();
    String [] tem=temp.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    col.add(4, new JComboBox(tempstr));
    data.add(col);
    dm.setDataVector(data, columns);
    table = new JTable(dm) {
    public void tableChanged(TableModelEvent e) {
    super.tableChanged(e);
    public boolean isCellEditable(int rowIndex, int vColIndex) {
    return true;
    JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(false);
    table.setBackground(SystemColor.inactiveCaptionText);
    table.setRowHeight(20);
    JTableHeader head = table.getTableHeader();
    head.setSize(850, 75);
    table.setTableHeader(head);
    table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
    table.getTableHeader().setBackground(new Color(130, 170, 150));
    table.getTableHeader().setForeground(Color.BLUE);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
    table.setForeground(new Color(125, 25, 0));
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setMinWidth(75);
    col.setMaxWidth(75);
    TableColumn col1 = table.getColumnModel().getColumn(1);
    col1.setMinWidth(150);
    col1.setMaxWidth(150);
    TableColumn col2 = table.getColumnModel().getColumn(2);
    col2.setMinWidth(150);
    col2.setMaxWidth(150);
    TableColumn col3 = table.getColumnModel().getColumn(3);
    col3.setMinWidth(150);
    col3.setMaxWidth(150);
    TableColumn col4 = table.getColumnModel().getColumn(4);
    col4.setMinWidth(160);
    col4.setMaxWidth(160);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
    Vector tempstr=new Vector();
    for(int j=0;j<jobList.size();j++){
    ArrayList temlist=(ArrayList)jobList.get(j);
    String [] tem=temlist.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    JComboBox portTypesCombo = new JComboBox(tempstr);
    col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
    col4 = table.getColumnModel().getColumn(4);
    col4.setCellEditor(new MyComboBoxEditor(tempstr));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
    System.out.println(tempstr);
    displayPanel.setLayout(new BorderLayout());
    displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    table.setEditingColumn(0);
    int column = 0;
    if (e.getClickCount() == 1) {
    Point p = e.getPoint();
    selectedRow = table.rowAtPoint(p);
    column = table.columnAtPoint(p);
    System.out.println(table.isCellEditable(selectedRow, column));
    if (column != 0) {
    selectedRow = -1;
    returnList = new Vector();
    returnList = (Vector) rows.get(selectedRow);
    else if (column == 0) {
    table.revalidate();
    table.repaint();
    scroll.getViewport().add(table);
    displayPanel.add(scroll, BorderLayout.CENTER);
    displayPanel.setVisible(true);
    else {
    JOptionPane.showMessageDialog(this, "No Data Available");
    } catch (Exception e1) {
    e1.printStackTrace();
    class MyItemListener implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if (source instanceof AbstractButton == false)return;
    boolean checked = e.getStateChange() == ItemEvent.SELECTED;
    for (int x = 0, y = table.getRowCount(); x < y; x++) {
    table.setValueAt(new Boolean(checked), x, 0);
    class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
    AutoPopRollBack adaptee;
    AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.SearchBtn_actionPerformed(e);
    class RadioButtonRenderer implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value == null)return null;
    return (Component) value;
    class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
    private JRadioButton button;
    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row,
    int column) {
    if (value == null)return null;
    button = (JRadioButton) value;
    button.addItemListener(this);
    return (Component) value;
    public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
    protected static Border m_noFocusBorder;
    public CheckCellRenderer() {
    super();
    m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(m_noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (value instanceof Boolean) {
    Boolean b = (Boolean) value;
    setSelected(b.booleanValue());
    setBackground(isSelected && !hasFocus ?
    table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected && !hasFocus ?
    table.getSelectionForeground() : table.getForeground());
    setFont(table.getFont());
    setBorder(hasFocus ? UIManager.getBorder(
    "Table.focusCellHighlightBorder") : m_noFocusBorder);
    return this;
    class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
    protected CheckBoxHeader rendererComponent;
    protected int column;
    protected boolean mousePressed = false;
    public CheckBoxHeader(ItemListener itemListener) {
    rendererComponent = this;
    rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    rendererComponent.setForeground(header.getForeground());
    rendererComponent.setBackground(header.getBackground());
    rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
    header.addMouseListener(rendererComponent);
    setColumn(column);
    rendererComponent.setText("Select All");
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return rendererComponent;
    protected void setColumn(int column) {
    this.column = column;
    public int getColumn() {
    return column;
    protected void handleClickEvent(MouseEvent e) {
    if (mousePressed) {
    mousePressed = false;
    JTableHeader header = (JTableHeader) (e.getSource());
    JTable tableView = header.getTable();
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
    doClick();
    public void mouseClicked(MouseEvent e) {
    handleClickEvent(e);
    ( (JTableHeader) e.getSource()).repaint();
    public void mousePressed(MouseEvent e) {
    mousePressed = true;
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    // Select the current value
    setSelectedItem(value);
    return this;
    class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    and Bringing data from data base by using this method
    if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
    else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
    st = con.createStatement();
    System.out.println("---new jobs search-->" + sqlString);
    rs = st.executeQuery(sqlString);
    while (rs.next()) {
    retVector = new ArrayList();
    retVector.add(0, rs.getString("JOBNO"));
    retVector.add(1, "New Job");
    retVector.add(2, rs.getString("DOC_TYPE"));
    String temp="";
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    temp="K8I|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
    temp="K8E";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
    // temp="K1|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
    temp="K1|K8I";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
    temp="K2";
    retVector.add(3,temp);
    retVector.add(3, rs.getString("AGENT_CODE"));
    retVectorlist.add(retVector);
    i am sending data To ComboBox like this
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    K8I and K8T
    if K2 adding k8E and for other types as mentioned above
    But for ComboBoxes it is showing same Items not changing
    Please any body can help to me
    Thanks and Regards
    Ravichandra

    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • How to select JLabel inside a JTable

    hi all,
    I have a Jtable which has own renderer so it can store components in it. I have added a Jlabel one of its cells but when I select that row the label stays upon the selected background color. here is a sample screenshot to decribe my problem clearly [http://www.imagecross.com/06/image-hosting-view-01.php?id=6570label.jpg]
    is there any way to select the label inside selected background color.
    - I have already tried to make the label not opaque but it didnt work -
    thanks...

    I have added bold parts of the code below. if you use other components you can make a type casting and do what you want.
    thanks again..
    class ComponentRenderer *extends JComponent*  implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
        *     JLabel l = (JLabel)value;*
        *     if(isSelected) {*
        *          l.setForeground(Color.BLUE);*
        *          l.setOpaque(true);*
        *          l.setBackground(new Color(184, 207, 229));*
        *     else {*
        *          l.setForeground(Color.BLACK);*
        *          l.setOpaque(true);*
        *          l.setBackground(Color.WHITE);*
            return l;
        /*public ComponentRenderer() {
    }

  • How to add a JMenubar and a JTable in a JFrame in a single application

    Hi all,
    I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
    package com.BSS;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class newssa extends JFrame
         public JMenuBar menuBar;
         public JToolBar toolBar;
         public JFrame frame;
         private JLabel jLabel1;
         private JLabel jLabel2;
         private JLabel jLabel3;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel6;
         private JComboBox jComboBox1;
         private JComboBox jComboBox2;
         private JComboBox jComboBox3;
         private JComboBox jComboBox4;
         private JComboBox jComboBox5;
         private JComboBox jComboBox6;
         private JTable jTable1;
         private JScrollPane jScrollPane1;
         private JPanel contentPane;
         public newssa()
              super();
              initializeComponent();
              this.setVisible(true);
         private void initializeComponent()
              jLabel1 = new JLabel();
              jLabel2 = new JLabel();
              jLabel3 = new JLabel();
              jLabel4 = new JLabel();
              jLabel5 = new JLabel();
              jLabel6 = new JLabel();
              jComboBox1 = new JComboBox();
              jComboBox2 = new JComboBox();
              jComboBox3 = new JComboBox();
              jComboBox4 = new JComboBox();
              jComboBox5 = new JComboBox();
              jComboBox6 = new JComboBox();
              frame=new JFrame();
              //Included here
              JMenuBar menuBar = new JMenuBar();
              JMenu general = new JMenu("General");
         menuBar.add(general);
         JMenu actions =new JMenu("Actions");
         menuBar.add(actions);
         JMenu view=new JMenu("View");
         menuBar.add(view);
         JMenu Timescale=new JMenu("TimeScale");
         menuBar.add(Timescale);
         Timescale.add("Today CTRL+D");
         Timescale.add("Current Week CTRL+W");
         Timescale.add("Current Month CTRL+M");
         Timescale.add("Current Quarter CTRL+Q");
         Timescale.add("Current Year CTRL+Y");
         Timescale.add("Custom TimeScale CTRL+U");
         JMenu start=new JMenu("Start");
         menuBar.add(start);
         JMenu options=new JMenu("Options");
         menuBar.add(options);
         JMenu help=new JMenu("Help");
         menuBar.add(help);
         JFrame.setDefaultLookAndFeelDecorated(true);
         frame.setJMenuBar(menuBar);
         frame.pack();
         frame.setVisible(true);
         toolBar = new JToolBar("Formatting");
         toolBar.addSeparator();
              //Before this included new
              String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
              // Create some data
              String dataValues[][] =
                   { "blue", "flash", "ORT001" },
                   { "AVCONF", "av configuration with warrenty"}
              // Create a new table instance
              //jTable1 = new JTable( dataValues, columnNames );
              jTable1 = new JTable(dataValues,columnNames);
              jScrollPane1 = new JScrollPane(jTable1);
              contentPane = (JPanel)this.getContentPane();
              //scrollPane = new JScrollPane( table );
              //topPanel.add( scrollPane, BorderLayout.CENTER );
              // jLabel1
              jLabel1.setText("Service Centers");
              // jLabel2
              jLabel2.setText("Service Areas");
              // jLabel4
              jLabel3.setText("Skills");
              jLabel4.setText("Availablity Types");
              // jLabel5
              jLabel5.setText("From Date");
              // jLabel6
              jLabel6.setText("To");
              // jComboBox1
              jComboBox1.addItem("Coimbatore");
              jComboBox1.addItem("Chennai");
              jComboBox1.addItem("Mumbai");
              jComboBox1.addItem("New Delhi");
              jComboBox1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox1_actionPerformed(e);
              // jComboBox2
              jComboBox2.addItem("North Zone");
              jComboBox2.addItem("South Zone");
              jComboBox2.addItem("Central Zone");
              jComboBox2.addItem("Eastern Zone");
              jComboBox2.addItem("Western Zone");
              jComboBox2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox2_actionPerformed(e);
              // jComboBox3
              jComboBox3.addItem("Microsoft Components");
              jComboBox3.addItem("Java Technologies");
              jComboBox3.addItem("ERP");
              jComboBox3.addItem("Others");
              jComboBox3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox3_actionPerformed(e);
              // jComboBox4
              jComboBox4.addItem("One");
              jComboBox4.addItem("Two");
              jComboBox4.addItem("Three");
              jComboBox4.addItem("Four");
              jComboBox4.addItem("Five");
              jComboBox4.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox4_actionPerformed(e);
              // jComboBox5
              jComboBox5.addItem("12/12/2004");
              jComboBox5.addItem("13/12/2004");
              jComboBox5.addItem("14/12/2004");
              jComboBox5.setEditable(true);
              jComboBox5.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox5_actionPerformed(e);
              // jComboBox6
              jComboBox6.addItem("12/11/2004");
              jComboBox6.addItem("13/11/2004");
              jComboBox6.addItem("14/11/2004");
              jComboBox6.setEditable(true);
              jComboBox6.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox6_actionPerformed(e);
              // jTable1
              jTable1.setModel(new DefaultTableModel(4, 4));
              // jScrollPane1
              jScrollPane1.setViewportView(jTable1);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 2,29,84,18);
              addComponent(contentPane, jLabel2, 201,33,76,18);
              addComponent(contentPane, jLabel3, 384,32,59,18);
              addComponent(contentPane, jLabel4, 2,77,85,18);
              addComponent(contentPane, jLabel5, 197,79,84,18);
              addComponent(contentPane, jLabel6, 384,80,60,18);
              addComponent(contentPane, jComboBox1, 85,32,100,22);
              addComponent(contentPane, jComboBox2, 276,32,100,22);
              addComponent(contentPane, jComboBox3, 419,30,100,22);
              addComponent(contentPane, jComboBox4, 88,76,100,22);
              addComponent(contentPane, jComboBox5, 276,79,100,22);
              addComponent(contentPane, jComboBox6, 421,78,100,22);
              addComponent(contentPane, jScrollPane1, 33,158,504,170);
              // newssa
              this.setTitle("SSA Service Scheduler");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(560, 485));
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jComboBox1_actionPerformed(ActionEvent e)
              int index = jComboBox1.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Area Coimbatore Selected "); break;
                   case 1: System.out.println("Area Chennai selected"); break;
                   case 2: System.out.println("Mumbai being selected"); break;
                   case 3: System.out.println("New Delhi being selected"); break;
         private void jComboBox2_actionPerformed(ActionEvent e)
              int index = jComboBox2.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("North Zone Selcted "); break;
                   case 1: System.out.println("South Zone being selected"); break;
                   case 2: System.out.println("Central Zone being selected"); break;
                   case 3: System.out.println("Eastern Zone being selected"); break;
                   case 4: System.out.println("Western Zone being selected"); break;
         private void jComboBox3_actionPerformed(ActionEvent e)
              int index = jComboBox3.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Microsoft Components being selected"); break;
                   case 1: System.out.println("Java Technologies being selected"); break;
                   case 2: System.out.println("ERP Tehnologies being selected"); break;
                   case 3: System.out.println("Other's selected"); break;
         private void jComboBox4_actionPerformed(ActionEvent e)
              int index = jComboBox4.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("One selected"); break;
                   case 1: System.out.println("Two selected"); break;
                   case 2: System.out.println("Three selected"); break;
                   case 3: System.out.println("Four selected"); break;
                   case 4: System.out.println("Five selected"); break;
         private void jComboBox5_actionPerformed(ActionEvent e)
              int index = jComboBox5.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/12/2004 being selected"); break;
                   case 1: System.out.println("13/12/2004 being selected"); break;
                   case 2: System.out.println("14/12/2004 being selected"); break;
         private void jComboBox6_actionPerformed(ActionEvent e)
              int index = jComboBox6.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/11/2004 being selected"); break;
                   case 1: System.out.println("13/11/2004 being selected"); break;
                   case 2: System.out.println("14/11/2004 being selected"); break;
         public static void main(String[] args)
              newssa ssa=new newssa();
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              //JFrame frame = new JFrame("SSA Service Scheduler");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setJMenuBar(ssa.menuBar);
    //frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
    //frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
    //frame.pack( );
    //frame.setVisible(true);
              try
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
    But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
    VERY URGENT PLEASE..
    Thanks in advance
    with kind regds
    Satheesh.K

    But did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
    And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all.

  • Change the color of a particular row in a jtable

    I have a jtable and i want to change the color of one particular column and few rows to blue and underline the text depending on some condition. In my view class if a condition is true
    for( count=0;count<grdTest.getRowcount;count++)
    if(some condition true)
    grdTest.getColumnModel().getColumn(0).
    setCellRenderer(new MyTestCellRenderer(count));
    And my cell renderer
    public class MyTestCellRenderer extends DefaultTableCellRenderer {
    int rowIndex=-1;
    public MyTestCellRenderer(int rowcount) {
    super();
    rowIndex=rowcount;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value,
    isSelected, hasFocus, row, column);
    if(row == rowIndex)
    setText("<html> <u> <font color='blue'>" + value.toString());
    return this;
    This is behaving very wierd . If suppose there are 50 rows and all of them have the condition true then only the last one in the row color is changes.
    However if only one out othe say10 has the condition true then it changes the color and underlines the particular row,column.
    Is there any other way to do this or what i am doing wrong
    Thanks

    if(row == rowIndex)Your code is a shambles because of the lack of tags, but I don't believe I see anything being called when this boolean condition is not true. That would be a problem.                                                                                                                                                                                                                                                                                                                                                                                                           

  • Changing background color in JTable, only changes one row at a time...

    I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
    What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
    In this part of the CellRenderer:
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            //row that meets special conditions
            if(row == specRow && col == specCol)
                color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
    Here's the rest of the relevant code:
        public void tableChanged(TableModelEvent e)
            int firstRow = e.getFirstRow();
            int lastRow  = e.getLastRow();
            int colIndex = e.getColumn();
            if(colIndex == 4)
                String value = (String)centerTable.getValueAt(firstRow, colIndex);
                // check for our special selection criteria
                if(value.equals("KEY WORD"))
                    for(int j = 0; j < centerTable.getColumnCount(); j++)
                        CellRenderer renderer =
                            (CellRenderer)centerTable.getCellRenderer(firstRow, j);
                        renderer.setSpecialSelection(firstRow, j);
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.Color;
    public class CellRenderer extends DefaultTableCellRenderer
        int specRow, specCol;
        public CellRenderer()
            specRow = -1;
            specCol = -1;
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int col)
            setHorizontalAlignment(JLabel.CENTER);
            Color color = Color.green;
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            if(row == specRow && col == specCol)
                color = color.white;
            //setForeground(color);
            setBackground(color);
            setText((String)value);
            return this;
        public void setSpecialSelection(int row, int col)
            specRow = row;
            specCol = col;
    }If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.

    That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
    Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class TableRowRenderingTip extends JPanel
        JTable table;
        public TableRowRenderingTip()
            Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
            Object[][] data =
                {"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
                {"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
                {"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
                {"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
                {"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Alternating", createAlternating(model));
            tabbedPane.addTab("Border", createBorder(model));
            tabbedPane.addTab("Data", createData(model));
            add( tabbedPane );
        private JComponent createAlternating(DefaultTableModel model)
            JTable table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Alternate row color
                    if (!isRowSelected(row))
                        c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        private JComponent createBorder(DefaultTableModel model)
            JTable table = new JTable( model )
                private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
                private Border inside = new EmptyBorder(0, 1, 0, 1);
                private Border highlight = new CompoundBorder(outside, inside);
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    JComponent jc = (JComponent)c;
                    // Add a border to the selected row
                    if (isRowSelected(row))
                        jc.setBorder( highlight );
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public JComponent createData(DefaultTableModel model)
            table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Color row based on a cell value
                    if (!isRowSelected(row))
                        c.setBackground(getBackground());
                        String type = (String)getModel().getValueAt(row, 0);
                        if ("Buy".equals(type)) {
                            table.setRowHeight(row, 30);
                            c.setBackground(Color.GREEN);
                        if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public static void createAndShowGUI()
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Table Row Rendering");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableRowRenderingTip() );
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }Edited by: scavok on Apr 26, 2010 6:43 PM

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • How to set background color of row in JTable

    Hi,I want to set different background color to rows in JTable according to some value in the this row.
    eg.
    no name isGood
    1 aaa yes (this row's background color is red)
    2 bbb no (this row's background color is blue)
    3 ccc yes (this row's background color is red)
    4 ddd yes (this row's background color is red)
    5 eee no (this row's background color is blue)
    thanks

    thanks!*_*                                                                                                                                                                                                                                                       

  • Color a row in JTable according to specific column value

    I'm having problem setting row color according to specific values set in listData. Color values are also stored inside the listData. Each row has a specific color value assigned to it(either black or blue).
    ColorRenderer is called from table.setDefaultRenderer(Object.class, new ColorRenderer(listData))
    The color values are passed through to ColorRender constructor but not to the getTableCellRendererComponent() method.
    Here is my code. Any help is much appreciated.
    class ColorRenderer extends DefaultTableCellRenderer {
    Color[] colors;
    public ColorRenderer(ListData[] listData) {
    if (listData != null) {
    for (int i=0; i<listData.length; i++) {
         if (listData[i] != null) {
         colors = new Color[listData.length];
         colors[i] = listData.getForegroundColor();
         System.out.println(colors[i].toString());
    else System.out.println("null listData");
    public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel c =(JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    c.setOpaque(true);
    System.out.println("colors.length: " + colors.length);
    for (int i=0; i<colors.length; i++) {
    if (colors[i] != null) {        
    System.out.println("colors["+i+"]: " + colors[i]);
    c.setForeground(colors[i]);
    } else c.setForeground(Color.black);
    return c;

    Well, first of all, you didn't use the code tokens for your posting. Second, this source won't even compile how you have it. But anyway...
    If you want to change the color of the cell based on the row, assuming you have a matching color in your color list for each row, in your getTableCellRendererComponent() method, just do something like this.
    c.setForeground( colors[row] );

  • 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.

  • Print JTable with Multiple pages and rows

    I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
    1) To Print Multiple pages
    2) To wrap lines that is too long for the column
    3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
    4) To align the numbers to the right and center column headings
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    public class Report implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame frame;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public Report()
              frame = new JFrame("Sales Report");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              final String[] headers =
                   "ID",
                   "Description",
                   "open price",
                   "latest price",
                   "End Date",
                   "Quantity"
              int count = 0;
              final Object[][] data =
                   {new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
              TableModel dataModel = new AbstractTableModel()
                   public int getColumnCount() { return headers.length; }
                   public int getRowCount() { return data.length;}
                   public Object getValueAt(int row, int col)
                        return data[row][col];
                   public String getColumnName(int column)
                        return headers[column];
                   public Class getColumnClass(int col)
                        return getValueAt(0,col).getClass();
                   public boolean isCellEditable(int row, int col)
                        return (col==1);
                   public void setValueAt(Object aValue, int row, int column)
                        data[row][column] = aValue;
              tableView = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(tableView);
              scrollpane.setPreferredSize(new Dimension(500, 80));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
              frame.pack();
              JButton printButton= new JButton();
              printButton.setText("print me!");
              frame.getContentPane().add(BorderLayout.SOUTH,printButton);
              // for faster printing turn double buffering off
              RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
              printButton.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        doPrint();
              frame.setVisible(true);
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 10);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
          * We can't guarantee that the same amount of rows will be displayed on each page,
          * the row heights are dynamic and may wrap onto 2 or more lines.
          * Thus we need to calculate the height of each row and then test how may rows
          * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = tableView.getValueAt(i, j).toString();
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
          * Print the headers or a row from the table to the graphics context
          * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = obj.toString();
                   else
                        align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
                             pageFormat.getImageableY() + pageFormat.getImageableWidth(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public static void main(String[] args)
              new Report();
    }

    Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    import java.math.*;
    public class PrintJTable implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame m_parent;
         private String m_title;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public PrintJTable(JFrame parent, JTable table)
              m_parent = parent;
              tableView = table;
              doPrint();
         public PrintJTable(JFrame parent, String title, JTable table)
              m_parent = parent;
              m_title = title;
              tableView = table;
              doPrint();
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 8);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              double test = 0;
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
                   test += columnWidths;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   g2.drawString(m_title,
                                       (int)(pageFormat.getImageableX()),
                                       next_row);
                   Color current_color = g2.getColor();
                   g2.setColor(Color.lightGray);
                   int y = next_row + fontMetrics.getDescent();
                   g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                                  y,
                                  (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                                  y));
                   g2.setColor(current_color);
                   next_row += fontMetrics.getHeight();
              next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
         * We can't guarantee that the same amount of rows will be displayed on each page,
         * the row heights are dynamic and may wrap onto 2 or more lines.
         * Thus we need to calculate the height of each row and then test how may rows
         * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              headerHeight = 0;
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   headerHeight = fontMetrics.getHeight();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = formatObject(tableView.getValueAt(i, j));
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
         * Print the headers or a row from the table to the graphics context
         * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = formatObject(obj);
                   else
                        //align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              Color current_color = g2.getColor();
              g2.setColor(Color.lightGray);
              int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             y,
                             (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                             y));
              g2.setColor(current_color);
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public String formatObject(Object obj)
              String value = (obj == null) ? "" : obj.toString();
              return value;

  • Urgent help needed in jtable

    PLEASE could someone help me look at this and see why the color of my data in a jtable cell is niot turning red when I press enter
    THX
    package mintest;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import com.borland.jbcl.layout.*;
    import java.awt.color.*;
    import javax.swing.event.*;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import java.awt.datatransfer.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    import javax.swing.border.EtchedBorder;
    import java.io.*;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.table.DefaultTableCellRenderer;
    public class VeckoSchema extends JPanel
    private boolean DEBUG = false;
    JTabbedPane tabbedPane;
    Color rgdcolor2= new Color (0,153,255); //Definiera f?rgen f?r schema-,projekt- och l?nehuvudflikarna
    Color rgdcolor1= new Color (0,102,255);
    Color rgdcolor3= new Color (51,204,255); //Definiera f?rgen f?r schema-,projekt- och l?nehuvudflikarna
    Color rgdcolor= new Color (0,0,153);
    Color rgdcolor4= new Color (153,153,153);
    JList list;
    DefaultListModel listModel = new DefaultListModel();
    ImageIcon icon= new ImageIcon ("D:\\Dokument\\Skolarbete\\Examens projekt\\JAVA\\minTest\\Bakgrundsbild2.jpg");
    ImageIcon icon1= new ImageIcon ("D:\\Dokument\\Skolarbete\\Examens projekt\\JAVA\\minTest\\Save16.gif");
    ImageIcon icon2= new ImageIcon ("D:\\Dokument\\Skolarbete\\Examens projekt\\JAVA\\minTest\\printer2.gif");
    JButton spara;
    JButton Ok_knapp = new JButton();
    JPanel panel7;
    TitledBorder title;
    Border blackline;
    JTable table = new JTable(new MyTableModel());
    int x;int y;
    Object data1;
    //ColorRenderer renderer;
    Color mincellColor= Color.red;
    TableCellRenderer Renderer;
    public VeckoSchema() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception
    this.setBackground(rgdcolor2);
    this.setLayout(null);
    //Skapa tabellen
    //JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(30, 40, 1000, 600);//(avst?nd fr?n v?nster sidan 49, avst?nd fr?n norr 39, bredd 144, h?jd 38));
    this.add(scrollPane);
    //TableCellRenderer weirdRenderer = new WeirdRenderer();
    table.setCellSelectionEnabled(true);
    table.requestFocus(true);
    table.getInputMap().put(KeyStroke.getKeyStroke(
    KeyEvent.VK_ENTER, 0),
    "check");
    table.getActionMap().put("check", new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    try {
    System.out.println("BINGO");
    x= table.getSelectedColumn() ;
    y= table.getSelectedRow() ;
    //System.out.println("markerad kolumn ?r" + table.getSelectedColumn()) ;
    //System.out.println("markerad Rad ?r" + table.getSelectedRow()) ;
    // table.setColumnSelectionAllowed(true);
    data1 = table.getModel().getValueAt(
    table.getSelectedRow(),
    table.getColumnModel().getColumn(
    table.getSelectedColumn()).getModelIndex());
    System.out.println("markerad text inneh?ller" + data1);
    x= table.getSelectedColumn() ;
    y= table.getSelectedRow() ;
    /* table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    System.out.println("hejsan hoppsan markerad text inneh?ller" + data1);
    Component cell =super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
    if (row == y && column == x ) {
    System.out.println("rad"+y);
    System.out.println("column"+x);*/
    //cell.setFont(new java.awt.Font("Dialog", 0, 20));
    /* cell.setForeground(Color.red);
    else
    cell.setForeground(null);
    return cell;
    // ColorRenderer centerRenderer = new ColorRenderer();
    // Use renderer on a specific column
    /* TableColumn column = table.getColumnModel().getColumn(
    table.getColumnModel().getColumn(
    table.getSelectedColumn()).getModelIndex()
    column.setCellRenderer( centerRenderer );
    table.setDefaultRenderer(String.class, centerRenderer);*/
    class table extends JTable {
    ColorRenderer multiRenderer=new ColorRenderer();
    table(MyTableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
    if (row == y && col == x) return multiRenderer;
    else return super.getCellRenderer(row,col);
    catch(Exception x) {
    x.printStackTrace();
    class MyTableModel extends AbstractTableModel {
    String[] columnNames = {"",
    "M?NDAG",
    "TISDAG",
    "ONSDAG",
    "TORSDAG",
    "FREDAG",
    "L?RDAG",
    "S?NDAG"};
    Object[][] data = {
    {"Anna Svensson","", "","Eji Eze", "","","",""},
    {"","", "","", "Christopher ?kesson","Eji Eze","",""},
    {"","", "","", "","Sara Eggert","",""},
    {"Eji Eze","", "","", "","","",""},
    {"Stefan Wielsel","", "","", "","","",""},
    {"","", "","", "","","Anna Persson","Markus Nilsson"},
    {"","Markus Nilsson", "Malin Mejby","", "","","",""},
    {"","Stefan Wiesel", "","", "","","",""},
    {"","Anna Svensson", "","", "","","",""},
    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];
    /* Denna metod g?r det m?jligt att ?ndrar i tabellen*/
    public boolean isCellEditable(int row, int col) {
    if (col < 8) {
    return false;
    } else {
    return true;
    /*Denna metod g?r s? ?ndringarna som g?rs i en viss cell inte f?rsvinnar d? man l?mnar cellen*/
    Object[][] value = {              {"Chiji Eze"},
    int row= 3;
    int col = 4;
    public void setValueAt(Object value, int row, int col) {
    /* if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    /* if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    /* private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");*/
    /*class MyCellColor extends DefaultTableCellRenderer
    public MyCellColor()
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    JLabel result = null;
    if(isSelected && value != null)
    result = new JLabel(value.toString());
    result.setOpaque(true);
    result.setForeground(Color.blue);
    System.out.println("Result "+result.getText());
    System.out.println("Color is "+result.getForeground());
    return result;
    /* public TableCellRenderer getCellRenderer (int row, int column)
    //seulement pour la premiere colonne
    if (column == 0)
    return Renderer;
    // sinon le Renderer par d?faut
    return super.getCellRenderer (row, column);
    class ColorRenderer extends JTextArea implements TableCellRenderer{ //DefaultTableCellRenderer
    Color testfarg;
    public ColorRenderer( ){
    testfarg= Color.red;
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    System.out.println("hejsan hoppsan markerad text inneh?ller" + data1);
    //Component cell =super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
    if(row==y && column == x)
    setForeground(testfarg);
    else
    setBackground(null);
    return this;

    You really need to study this tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    After you have read it, take a look at this example, and tweak it to suit your needs:
    import javax.swing.table.*;
    import javax.swing.*;
    public class Test {
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JScrollPane(new JTable(new MyTableModel())));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    class MyTableModel extends AbstractTableModel {
      private String columnNames[] = new String[] {
          "Name", "Checked"
      private Class columnClasses[] = new Class[] {
          String.class, Boolean.class
      private Object data[][] = new Object[][] {
          { "One", Boolean.TRUE },
          { "Two", Boolean.FALSE },
          { "Three", Boolean.FALSE },
          { "Four", Boolean.TRUE },
      public int getColumnCount() {
        return columnNames.length;
      public int getRowCount() {
        return data.length;
      public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
      public Class getColumnClass(int columnIndex) {
        return columnClasses[columnIndex];
      public String getColumnName(int columnIndex) {
        return columnNames[columnIndex];
      public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex == 1)
          return true;
        else
          return false;
      public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        data[rowIndex][columnIndex] = aValue;
    }

Maybe you are looking for

  • Error while installing OIMCluster in Web logic server

    I completed OIM 9.1.0.1 installation on WLS 10.3 Cluster... Below is the architecture. Domain: OIMCLUSTER AdminServer:7001 OIMInstanceOne:7010 OIMInstanceTwo:7020 OIMInstanceOne and OIMInstanceTwo are in a cluster called "OIMCluster" Now I completed

  • Hp 4000n, WIN 7 HOME NETWORK PRINTER GOES OFFLINE ON REBOOT

    I have 2 WIN7 desktops and 2 printers.  One HP L4000n is attached locally to one computer and shared by the other computer on the home network.  It is attached to a standard parallel printer port (via) a IEEE1284 controller card.  The other printer i

  • Need help on this MPG program

    Hi all, The purpose of this program is listed in // Inputs the miles driven and gallons used (both integers) for each tankful. // Calculates and displays miles per gallon obtained for each tankful and print // the combined miles per gallon obtained f

  • Best Cloud Storage for iPhoto backup?

    Hello, it seems ridiculous that Apples iCloud doesn't allow you to backup your entire iPhoto library... so I'm looking for some advice on the best alternative options. I currently have TM backup automatically, but I travel between the USA and Europe

  • Multiple jars with applet

    I have an applet that requires jmf.jar, however this jar file may not be on the client site. I have done some looking but am unable to come up with a solution that allows me to sucessfully send this jar along with the jar containing the applet code t