Help with multilined cells in JTable?

Can someone plz help me with this class, I want to make cells multilined. I tried cellrenderer but without succes... :-(
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
public class GK_Styringspunkter extends JFrame
     Container panel = getContentPane();
     JTable tabel;
     DataModel model;
     JScrollPane scroll;
GK_Styringspunkter()
          model = new DataModel();
          tabel = new JTable(model);
          scroll = new JScrollPane(tabel);
          panel.add("Center",scroll);
          setSize(1024,768);
          setVisible(true);
class DataModel extends AbstractTableModel
     String hoved[];
     Object data[][];
     DataModel()
          hoved = new String[]{"Processtrin","Kritisk styringspunkt","Risikofaktor","Styrende foranstaltning",
          "Kritisk gr�nse","Overv�gning","Afhj�lpende foranstaltning","Ansvarlig"};
          data = new Object[1][8];
          data[0][0] = "Fiskeafdelingen";
          data[0][1] = "Temperatur";
          data[0][2] = "Opformering af mikroorganismer";
          data[0][3] = "Temperatur kontrol ved modtagelse";
          data[0][4] = "Frisk fisk:2C R�get fisk: 5C";
void opdater()
public int getColumnCount()
return hoved.length;
public int getRowCount()
return data.length;
public String getColumnName(int col)
return hoved[col];
public Object getValueAt(int row, int col)
return data[row][col];
public boolean isCellEditable(int row, int col)
return true;
public void setValueAt(Object value, int row, int col)
data[row][col] = value;
fireTableCellUpdated(row,col);      
public static void main(String[] aslan)
     new GK_Styringspunkter();
}

sorry my fault... but when I try like this am still not getting the multilines in cells?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
public class GK_Styringspunkter extends JFrame
     Container panel = getContentPane();
     JTable tabel;
     DataModel model;
     JScrollPane scroll;
GK_Styringspunkter()
          model = new DataModel();
          tabel = new JTable(model);
          tabel.setRowHeight(0, 60);
          tabel.setDefaultRenderer(String.class, new MultiLineRenderer());
          scroll = new JScrollPane(tabel);
          panel.add("Center",scroll);
          setSize(1024,768);
          setVisible(true);
class DataModel extends AbstractTableModel
     String hoved[];
     Object data[][];
     DataModel()
          hoved = new String[]{"Processtrin","Kritisk styringspunkt","Risikofaktor","Styrende foranstaltning",
          "Kritisk gr�nse","Overv�gning","Afhj�lpende foranstaltning","Ansvarlig"};
          data = new Object[1][8];
          data[0][0] = "Fiskeafdelingen";
          data[0][1] = "Temperatur";
          data[0][2] = "Opformering \n af mikroorganismer";
          data[0][3] = "Temperatur kontrol \n ved modtagelse";
          data[0][4] = "Frisk fisk:2C \n R�get fisk: 5C";
void opdater()
public int getColumnCount()
return hoved.length;
public int getRowCount()
return data.length;
public String getColumnName(int col)
return hoved[col];
public Object getValueAt(int row, int col)
return data[row][col];
public boolean isCellEditable(int row, int col)
return true;
public void setValueAt(Object value, int row, int col)
data[row][col] = value;
fireTableCellUpdated(row,col);      
class MultiLineRenderer extends JTextArea implements javax.swing.table.TableCellRenderer
     public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
     setLineWrap(true);
     setText((String)value);
     if (isSelected)setBackground(Color.BLUE);
     else setBackground(Color.WHITE);
     return this;
public static void main(String[] aslan)
     new GK_Styringspunkter();

Similar Messages

  • Aligning the Text in Centre for MultiLine Cells in JTable

    Hi;
    Does anyone know how I could make a java table that has multiline text cells AND this multiline text is aligned to center? I tried to extend JTextArea and to implement TableRenderer - multiline was OK but it did not do anything on setHorizontalAlign. If I extend DefaultTableRender than I can align the text to center but I got no multiline...
    Any ideas?
    Kindly to provide me a solution for this its urgent.

    Hi;
    Thanks for the reply,on using Text Area as renderer i.e using Multi-Line cells in JTable, i achieved the objective of displaying the text on multiple lines in the cell."In my Table there are 5 columns and i'm setting renderer on 3rd and 5th column,If the text is too large in column 5 it automatically gets wrapped off for all the cells in column 5.For column 3 my text is not so large as compared to column 5 and due to which the Text in the column 3 starts from the top for all the cells i.e (the first row in column 3 is parallel to first row in column 5 ),Now the problem is i can't display the text in the center of all cells for Column 3 .
    Thanks in advance

  • Row with one cell in JTable

    I have a JTable with multiple cells per row. However, in-between some rows, I would like to have a header row which doesn't change as I scroll horizontally. Is that possible?
    Another question about JTables: Is it possible to have fixed cells on the right as well as on the left, with some cells in-between which you can scroll?

    I have a JTable with multiple cells per row. However, in-between some rows, I would like to have a header row which doesn't change as I scroll horizontally. Is that possible?
    Another question about JTables: Is it possible to have fixed cells on the right as well as on the left, with some cells in-between which you can scroll?

  • Help with merged cells in table

    I'm just learning how to use Dreamweaver 8 and tables. I am
    trying to use a table with merged cells filled with graphics --
    only one graphic per cell. I make my jpg the size of my cell, which
    it seems to fill. Then, when I upload it to view in browser, it
    looks as though the graphic doesn't take up the entire cell. At one
    point, it was working both in Dreamweaver and the browser. Now, in
    the browser view, it looks as though there is extra space above the
    graphic and below it. Any suggestions on what is going on???

    It's not the use of tables with your graphics that is
    necessarily the
    problem, it's HOW you are using the tables with your
    graphics. Can we see
    the page you have built so we can examine the code?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "degazon" <[email protected]> wrote in
    message
    news:gasr2p$10m$[email protected]..
    > Thanks! It's now evident that I shouldn't use tables
    with the graphics.

  • JTable - help with custom cell renderers and editors

    I've got myself into a bit of a mess with cell renderers and editors.
    I've got a custom component that wants displaying in a column and then hand over all functionality to this component when you start editing it.
    Now how I went out about this was to create a custom cell renderer that extends this component and implements TableCellRenderer.
    I then created a table cell editor that extends AbstractCellEditor and implements TableCellEditor and this cell editor creates a new component when it's initialized. I then use setCellEditor(new MyCellEditor()) on the column and setCellRenderer(new MyCellRenderer()).
    This works slightly but I'm wondering how this is all implemented.
    When I set the cell editor on it's own it seems to be sharing a reference to the single component that's being used which means that if you edit one cell all the cells get changed to the new value.
    Thanks for the help,
    Alex

    only a few forums are actually browsedAnd theSwing forum is one of the most active. Did you search it for editiing examples? I've seen many editing examples posted in a SSCCE format.
    SSCEE is also impossible as the functionality spans over about 10 classes We did not ask for your application, we asked for a SSCCE. The whole point of a SSCCE is to simplify the 10 classes into a single class and maybe an inner class for the editor to make sure you haven't made a silly mistake that is hidden because of the complexity of your real application.

  • Help with adding rows to JTable

    Could any body help me with the following problem:
    I have created form where I use JTable.Initially I should show 5 rows in JTable. User can enter data into the cells.And commit I should store the data in database.
    My problem is how to dynamically add rows to JTable as user is entering the data. And how to retain the data in the cells when it is entered.
    Right now when user edits a cell and tabs to next one the data in previous cell disappears.
    Its Urgent can anybody help me
    Thanks in advance
    Babu

    The number of rows, number of columns, etc, are all determined by the TableModel used in the JTable.
    What is the easiest solution is to subclass AbstractTableModel adding methods to support your dynamic row adding/deleting/etc that you need. If you go to the javadoc for JTable, there's a link to a tutorial which contains most of what you need to know.
    - David

  • Multiline cells in JTable

    Hi all,
    Im created a JTable,but im not able to read the lengthy text when it is bigger than the cell width.So, i want the text to be be align in the next line of that cell same as in excel sheet.
    Can anyone help me in this.
    Thank you

    Im created a JTable,but im not able to read the lengthy text when it is bigger than the cell width.So, i want the text to be be align in the next line of that cell same as >in excel sheet.You should look at using your own cellRenderer ( TableCellRenderer)
    Regards,
    Alan Mehio
    London,UK

  • Help with updating imageIcon in JTable

    Hi All
    Please I am hoping that some out there will know what is going on with this
    I am setting a Cell with a ImageIcon with this code
            Object[] data = {
                rSet.getString(1),
                new ImageIcon("imagesTest/" + "check" + rSet.getString(2) + ".png"),
                rSet.getString(2),
                "yes",
                rSet.getString(3)};
            model.addRow(data);and this work fine as I have this set to the table
          public Class getColumnClass(int c) {
            return getValueAt(1, c).getClass();
          }Now I want to update the ImageIcon with a new image that I create
    and I am trying to set the new ImageIcon to the cell with this code
          model.setValueAt(new ImageIcon("imagesTest/" + "check" +table.getValueAt
    (table.getSelectedRow(), 2) +".png"), table.getSelectedRow(), 1);but it does not want to paint it
    I have tried
    repaint();
    super.repaint();
    revalidate();I have also tried reloading the data by removing all the rows in the model with this
        model.setRowCount(0);
       then reloading the data.
    It seams like it holds ImageIcom in memory or something .
    Has anyone got an idea on how I can get this to work
    p.s I don't have the full code to show as it is hard to pull it apart.
    I hope I have given enough code to so you what is going on.
    Thanks for any insight into this
    Craig

    You should write an appropriate cell renderer.
    If the cell is defined editable, you'd also need cell editor.

  • PLS help with stupid JPanel and JTable :-(

    Hi all im crying now :-(
    Ive just recreated a panel for use with SWING. Now I want the table to be displayed but it just is not there.
    Nothing i seem to do makes it appear and im really confused????? Just add this to a simple JFrame and you will see what I mean
    it should look like this
    TITLE
    lbl1 txt1 lbl2 txt2
    lbl3 txt3 lbl4 txt 4
    button
    Table
    however the table is not there :-(
    Author: Justin Thomas
    Date  : 14 Jan 2002
    Notes : A simple login display
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Options extends JPanel implements ActionListener
        private IDNTester parent;
        private TextArea Results = new TextArea(18,80);
        private JButton Start = new JButton("Start Test");
        private JLabel error = new JLabel ("");
        private JTextField txtConns = new JTextField("1",4);
        private JTextField txtClients = new JTextField("10",4);
        private JTextField txtServer = new JTextField("Nutcracker",10);
        private JTextField txtPort = new JTextField("8101",5);
        public String Server;
        public int Port;
        public int Connections;
        public int Clients;
        private String newline;
        public Options(IDNTester ref)
            parent = ref;
            newline = System.getProperty("line.separator");
            JLabel lblMain = new JLabel ("WebIDN Performance Tester");
            JLabel  lblServer = new JLabel ("Server:");
            JLabel  lblPort = new JLabel ("Port:");
            JLabel  lblConns = new JLabel ("Connections:");
            JLabel  lblClients = new JLabel ("Clients:");
            GridBagLayout gridBag = new GridBagLayout();
            GridBagConstraints constraints = new GridBagConstraints();
            setLayout(gridBag);
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridwidth = 4;
            constraints.gridx = 0;
            gridBag.setConstraints(lblMain, constraints);
            add(lblMain);
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridy = 1;
            gridBag.setConstraints(error, constraints);
            error.setForeground(Color.red);
            add(error);
            constraints.anchor = GridBagConstraints.WEST;
            constraints.gridwidth = 1;
            constraints.gridx = 0;
            //********************************Server and COnnections***************
            constraints.fill = GridBagConstraints.BOTH;
            constraints.gridy = 2;
            gridBag.setConstraints(lblServer, constraints);
            add(lblServer);
            constraints.gridx = 1;
            gridBag.setConstraints(txtServer, constraints);
            add(txtServer);
            // Add some space between fields
            constraints.gridx = 2;
            gridBag.setConstraints(lblConns, constraints);
            add(lblConns);
            constraints.gridx = 3;
            gridBag.setConstraints(txtConns, constraints);
            add(txtConns);
            //********************************** Port and clients******************
            constraints.gridy = 3;
            constraints.insets = new Insets(5,0,0,0);
            constraints.gridx = 0;
            gridBag.setConstraints(lblPort, constraints);
            add(lblPort);
            constraints.gridx = 1;
            gridBag.setConstraints(txtPort, constraints);
            add(txtPort);
            constraints.gridx = 2;
            gridBag.setConstraints(lblClients, constraints);
            add(lblClients);
            constraints.gridx = 3;
            gridBag.setConstraints(txtClients, constraints);
            add(txtClients);
            //********************************** Buttons***************************
            constraints.anchor = GridBagConstraints.CENTER;
            constraints.gridy = 4;
            constraints.insets = new Insets(10,0,0,0);  //top padding
            constraints.gridwidth = 4;   //4 columns wide
            constraints.gridx = 0;
            gridBag.setConstraints(Start, constraints);
            add(Start);
            // Results area
            constraints.gridx = 0;
            constraints.gridy = 5;
            constraints.gridwidth = 5;   //Colum width
            //gridBag.setConstraints(Results, constraints);
            //add(Results);
            // JTable
            DefaultTableModel defaultTab = new DefaultTableModel();
            JTable jtable = new JTable(defaultTab);
            defaultTab.addColumn("ThreadID");
            defaultTab.addColumn("ClientID");
            defaultTab.addColumn("RIC");
            defaultTab.addColumn("TimeTaken");
            defaultTab.addColumn("RCount");
            defaultTab.addColumn("Bytes");
            //add scrollpane to our table
            gridBag.setConstraints(jtable, constraints);
            add(new JScrollPane(jtable));
            // Add listeners
            txtConns.addActionListener(this);
            txtClients.addActionListener(this);
            txtServer.addActionListener(this);
            txtPort.addActionListener(this);
            Start.addActionListener(this);
        public void actionPerformed(ActionEvent event)
            // Validate fields and if correct then start
            boolean valid = true;
            Server = txtServer.getText();
            try {
                Port= Integer.parseInt(txtPort.getText());
                Connections = Integer.parseInt(txtConns.getText());
                Clients = Integer.parseInt(txtClients.getText());
            catch(NumberFormatException nfe) {
                valid = false;
            if (valid && Server.length() > 0)
                error.setText("");
                parent.connect();
            else
                error.setText("Port/Client/Connections must be numerical");
                validate();
        // Add a new line to the test
        public void addLine(String text)
            Results.append(text + newline);
    }

    Hi,
    It looks like you haven't closed the comments. Is anything added after error.
    Anyway try setting the fill constrains on your table to BOTH. The table you have created in empty so it may have trouble determining it's size.
    regards,
    Terry

  • Help with displaying dataBase onto JTable

    hi
    i've got this code(below ) ,but i don't get any anything at all, so can u have alook at it, please
    <code>
    tableData = new Vector();
    Vector titles = new Vector();
    int currentRow = 0;
    try
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); // load the driver
    conn = DriverManager.getConnection ("jdbc:microsoft:sqlserver://213.107.6.45;user=foo;password=foobar");
    // connect to SQL server
    conn.setCatalog("Northwind");
    // choose the database
    Statement stmt = conn.createStatement();
    // create an SQL statement
    String query = "SELECT * FROM Products;";
    table = stmt.executeQuery(query);
    ResultSetMetaData md = table.getMetaData();
    // get the meta data
    final int numberOfColumns = md.getColumnCount();
    // Vector columnNames = new Vector();
    // for(int i = 0; i < numberOfColumns; i++)
    // columnNames.add(md.getColumnName(i+1)); //indexed from 1, not 0
    // Iterator it = columnNames.iterator();
    // int i = 30;
    if(table.next())
    //rowData(table.getObject(1).toString());
    //jTextFieldField2.setText(table.getObject(2).toString());
    Vector rowVector = new Vector();
    for (int currentCol = 1; currentCol < numCols; currentCol++)
    Object obj = table.getObject(currentCol);
    rowVector.addElement(obj);
    //rowVector.add(table.getString (currentCol + 1));
    tableData.addAll(rowVector);
    //tableData.addElement(rowVector);
    //currentRow++;
    for (int currentCol=1; currentCol<= numCols ; currentCol++)
    titles.addElement(md.getColumnLabel(currentCol));
    // Close connection to database
    stmt.close();
    conn.close();
    }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, ex.getMessage());
    }// end catch
    JTable table = new JTable(tableData,titles);
    JScrollPane scrollpane = new JScrollPane(table);
    this.getContentPane().add(scrollpane);
    </code>
    Thanks in advance

    Sorry i long time didn't do java coding alr , so not sure how rite i am
    but in order to pass Vector into the constructor.
    it had to be Vector of Vector
    i.e:
    Vector fieldLabel = new Vector
    Vector row = new Vector();
    Vector data = new Vector();
    //using metadata to get the fieldname
    while(rs.next()){
    data.add(rs.getString("userid"));
    data.add(rs.getString("subject"));
    row.add(data);
    JTable resultTable = new JTable(data,fieldLabel);
    Not sure how useful is this..

  • Need Help with Listener on JInternalFrame

    Below is the code as it is currently.
    public class addCustomer extends JInternalFrame implements ActionListener{
    //Variable declarations here
    private JPanel panel = new JPanel();
    private JLabel label1,label2,label3,label4,label5,label6,label7,label8,label9,icon1;
    private JTextField CustNum,CFName,CSName,Address1,Address2,City,PostCode,Tel,Cell;
    private JButton Cancel, Add;
    private ImageIcon pic,FrmPic;
    addCustomer() {
    super ("Add New Customer",true,true,true,true);
    setSize(350,370);
    setResizable(false);
    On the Frame I have a textfield that I would like to add a listener to. When text is typed into the textfield it should enable a JButton on the frame. My problem is that as soon as I implement KeyListener or EventListener on the above code I get an error of the class is not defined as abstract. If I define it as abstract my main declaration that looks like this gives me an error :
    public static void main(String args[]){
    new Video().show();
    Can anyone help me with a work around.
    Alexander

    Still have an error in the code. I don't know what I am doing wrong. this is the code so far.
    //This class will create the the Panel for Adding new Customers
    package VideoShop;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.io.*;
    import javax.swing.event.*;
    public class addCustomer extends JInternalFrame implements ActionListener{
    //Variable declarations here
    private JPanel panel = new JPanel();
    private JLabel label1,label2,label3,label4,label5,label6,label7,label8,label9,icon1;
    private JTextField CustNum,CFName,CSName,Address1,Address2,City,PostCode,Tel,Cell;
    private JButton Cancel, Add;
    private ImageIcon pic,FrmPic;
    addCustomer() {
    super ("Add New Customer",true,true,true,true);
    setSize(350,370);
    setResizable(false);
    //Sets the layout for the panel
    panel.setLayout(null);
    //Creates the labels
    label1 = new JLabel("Customer Nr");
    label2 = new JLabel("First Name");
    label3 = new JLabel("Surname");
    label4 = new JLabel("Address");
    label5 = new JLabel("Address");
    label6 = new JLabel("City");
    label7 = new JLabel("Postcode");
    label8 = new JLabel("Tel Nr");
    label9 = new JLabel("Cell Nr");
    //Creates the Textfields
    CustNum = new JTextField();
    CustNum.setEditable(false);
    CFName = new JTextField();
    CSName = new JTextField();
    Address1 = new JTextField();
    Address2 = new JTextField();
    City = new JTextField();
    PostCode = new JTextField();
    Tel = new JTextField();
    Cell = new JTextField();
    //Creates the buttons
    Cancel = new JButton("Cancel");
    Add = new JButton("Add");
    //Sets the alignment of the label controls
    label1.setBounds(20, 20, 90, 20);
    label2.setBounds(20, 50, 90, 20);
    label3.setBounds(20, 80, 90, 20);
    label4.setBounds(20, 110, 90, 20);
    label5.setBounds(20, 140, 90, 20);
    label6.setBounds(20, 170, 90, 20);
    label7.setBounds(20, 200, 90, 20);
    label8.setBounds(20, 230, 90, 20);
    label9.setBounds(20,260,90,20);
    //Sets the alignment of the Textfield controls
    CustNum.setBounds(100,20,90,20);
    CFName.setBounds(100, 50, 90, 20);
    CSName.setBounds(100, 80, 90, 20);
    Address1.setBounds(100, 110, 130, 20);
    Address2.setBounds(100, 140, 130, 20);
    City.setBounds(100, 170, 100, 20);
    PostCode.setBounds(100, 200, 65, 20);
    Tel.setBounds(100,230, 90,20);
    Cell.setBounds(100, 260, 90, 20);
    //Sets the alignment of the Button controls
    Add.setBounds(200, 310, 90, 20);
    Cancel.setBounds(85,310,90,20);
    //Creates an icon on the panel
    pic = new ImageIcon("/VideoShop/NotePad.gif");
    icon1 = new JLabel(pic);
    icon1.setBounds(280,10,50,50);
    //Adds Mnemonics
    Cancel.setMnemonic('c');
    Add.setMnemonic('a');
    //Adds listener to the Cell TextField to help with validation
    Cell.getDocument().addDocumentListener(new DocumentListener(){
    public void changeUpdate(DocumentEvent e){
    public void removeUpdate (DocumentEvent e){    
    adjust(e);
    public void insertUpdate(DocumentEvent e){      //ERROR////////////
    adjust(e);
    //Adds listeners to the buttons on the panel
    Cancel.addActionListener(this);
    Add.addActionListener(this);
    //Adds the controls to the panel
    panel.add(label1);
    panel.add(label2);
    panel.add(label3);
    panel.add(label4);
    panel.add(label5);
    panel.add(label6);
    panel.add(label7);
    panel.add(label8);
    panel.add(label9);
    panel.add(CustNum);
    panel.add(CFName);
    panel.add(CSName);
    panel.add(Address1);
    panel.add(Address2);
    panel.add(City);
    panel.add(PostCode);
    panel.add(Tel);
    panel.add(Cell);
    panel.add(Cancel);
    panel.add(Add);
    panel.add(icon1);
    //Gets the next customer number from the database
    //Variables for the database
    String dbuser = "";
    String dbpasswd = "";
    String DriverPrefix = "jdbc:odbc:";
    String DataSource = "Video";
    //Holds the value from the database
    String val1;
    //SQL String for writing data to database
    String SQLstring = "SELECT CustNum FROM Customers";
    //Loads the driver for the database
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Error Loading driver\n"+e,"Driver Load Error",JOptionPane.WARNING_MESSAGE);
    Statement stmt = null;
    Connection con = null;
    //Create a connection to the database.
    try {
    con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);
    stmt = con.createStatement();
    }catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Cannot connect to Database\n"+e,"Connection Error",JOptionPane.WARNING_MESSAGE);
    ResultSet rs = null;
    //Gets data from the database
    try {
    rs = stmt.executeQuery(SQLstring);
    while (rs.next()){
    val1 = rs.getString(1);
    int val2 = Integer.parseInt(val1);
    val2++;
    CustNum.setText(String.valueOf(val2));
    } catch (Exception e){
    JOptionPane.showMessageDialog(null,"Cannot connect to database\n"+e,"Communication Error",JOptionPane.WARNING_MESSAGE);
    try {
    con.close();
    } catch (Exception e){
    JOptionPane.showMessageDialog(null,"Cannot close database\n"+e,"Error",JOptionPane.WARNING_MESSAGE);
    //Adds the panel to the InternalFrame and display it
    getContentPane().add(panel);
    show();
    //Here all action events are processed
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == Cancel){
    dispose();
    if (e.getSource() == Add){
    ToDatabase();
    //Here the document event is processed
    public void adjust(DocumentEvent e){
    Cell.setEnabled(e.getDocument().getLength()>0);
    //Here the data will be sent to the database
    public void ToDatabase() {
    //Variables for the database
    String dbuser = "";
    String dbpasswd = "";
    String DriverPrefix = "jdbc:odbc:";
    String DataSource = "Video";
    //SQL String for writing data to database
    String SQLstring ="INSERT INTO Customers VALUES('"+CustNum.getText()+"', '"+CFName.getText()+"','"+CSName.getText()+"','"+Address1.getText()+"','"+Address2.getText()+"','"+City.getText()+"','"+PostCode.getText()+"','"+Tel.getText()+"','"+Cell.getText()+"')";
    //Loads the driver for the database
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Error Loading driver\n"+e,"Driver Load Error",JOptionPane.WARNING_MESSAGE);
    Statement stmt = null;
    Connection con = null;
    //Create a connection to the database.
    try {
    con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);
    stmt = con.createStatement();
    }catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Cannot connect to Database\n"+e,"Connection Error",JOptionPane.WARNING_MESSAGE);
    //Transfer data to database
    try {
    stmt.executeUpdate(SQLstring);
    con.close();
    } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Cannot update database\n"+e,"Communication Error",JOptionPane.WARNING_MESSAGE);
    dispose();
    The error that I receive is this:
    VideoShop/addCustomer.java [98:1] <anonymous VideoShop.addCustomer$1> is not abstract and does not override abstract method changedUpdate(javax.swing.event.DocumentEvent) in javax.swing.event.DocumentListener
    public void insertUpdate(DocumentEvent e){      //ERROR////////////
    ^
    1 error
    Errors compiling addCustomer.
    Is there a way around this or should I rewrite the whole class.
    Thanks
    Alexander

  • Help with editing a cell in a JTable. DESPERATE

    Hi! Is there someone out there that could help with some source code for editing a cell in my JTable when I run it as an applet??
    It works fine when I run it as an application.
    I manage to select the row and write a number in it, but I can't get out of the cell (it seems that the program stops??). I want to enter an integer in a cell and when I click enter or with the mouse in an other cell the value that I enter should update some other cell( multiply the entered value with some fixed number and update a cell in a second coloumn)
    I am really desperate now..... I have thought about using a MouseListener....
    I am using a tablemodel that is from AbstractTableModel.

    Are you using some cell editors?
    While converting inside them, you might be getting some exceptions (like parseexception)which is stopping you from proceeding further.
    Are you using your own tablemodel with custom datatypes?
    Hope this helps,
    Ramkumar

  • Help with dispatching JTable event to underlying components in a cell.

    Hello..
    I have a JTable in which i show a panel with clickable labels.. I found that jTable by default doesnt dispatch or allow mouseevents to be caught by underlying elements..
    i need help with dispatching an event from jTable to a label on a panel in a jTable cell.. below is the code i have come up with after finding help with some websites. but i couldnt not get it right.. my dispatched event seems to go back to the jtable itself ..
    any help or suggestion is appreciated..
    Thanks
    'Harish.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    * @author  harish
    public class tableDemo extends javax.swing.JFrame {
        JTable jTable1;
        testpane dummyPane;
        /** Creates new form tableDemo */
        public tableDemo() {
            initComponents();
            //table settings
            String[] columnNames = {"Task", "Action"," "};
            Object[][] data = { };
            DefaultTableModel model = new DefaultTableModel(data, columnNames) {
              // This method returns the Class object of the first
              // cell in specified column in the table model.
            public Class getColumnClass(int mColIndex) {
                int rowIndex = 0;
                Object o = getValueAt(rowIndex, mColIndex);
                if (o == null)
                    return Object.class;
                } else
                    return o.getClass();
            jTable1 = new javax.swing.JTable(model);
            jTable1.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("Clicked");
                  handleTableMouseEvents(e);
                 //invokeExternalApp("http://www.pixagogo.com");
              public void mouseEntered(MouseEvent e){
                  System.out.println("Entered");
                  //handleTableMouseEvents(e);
              public void mouseExited(MouseEvent e){
                  System.out.println("Exited");
                  //handleTableMouseEvents(e);
            jTable1.setRowHeight(100);
            jTable1.getTableHeader().setReorderingAllowed(false);
            jTable1.setBackground(new java.awt.Color(255, 255, 255));
            jTable1.setGridColor(new Color(250,250,250));
            jTable1.setShowGrid(true);
            jTable1.setShowVerticalLines(true);
            jTable1.setShowHorizontalLines(false);
            jTable1.setFont(new Font("Arial",0,11));
            jTable1.setMaximumSize(new java.awt.Dimension(32767, 32767));
            jTable1.setMinimumSize(new java.awt.Dimension(630, 255));
            jTable1.setPreferredSize(null);
            jTable1.setBackground(new Color(255,255,255));
            int vColIndex=0;
            TableColumn col = jTable1.getColumnModel().getColumn(vColIndex);
            int width = 100;
            col.setPreferredWidth(width);
            //add item to 2nd cell       
            Vector vec = new Vector();
            vec.addElement(null);
            dummyPane = new testpane();
            vec.addElement(dummyPane);
            ((DefaultTableModel)jTable1.getModel()).addRow(vec);
            jTable1.repaint();
            this.getContentPane().add(jTable1);
            jTable1.getColumn("Action").setCellRenderer(
              new MultiRenderer());
        protected void handleTableMouseEvents(MouseEvent e){
            TableColumnModel columnModel = jTable1.getColumnModel();
            int column = columnModel.getColumnIndexAtX(e.getX());
            int row    = e.getY() / jTable1.getRowHeight();
            testpane contentPane = (testpane)(jTable1.getModel().getValueAt(row, column));
            // get the mouse click point relative to the content pane
            Point containerPoint = SwingUtilities.convertPoint(jTable1, e.getPoint(),contentPane);
            if (column==1 && row==0)
            // so the user clicked on the cell that we are bothered about.         
            MouseEvent ev1 = (MouseEvent)SwingUtilities.convertMouseEvent(jTable1, e, contentPane);
            //once clicked on the cell.. we dispatch event to the object in that cell
         jTable1.dispatchEvent(ev1);
        private void initComponents() {
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-528)/2, (screenSize.height-423)/2, 528, 423);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new tableDemo().show();
        // Variables declaration - do not modify
        // End of variables declaration
        class testpane extends JPanel{
            public testpane(){
            GridBagConstraints gridBagConstraints;
            JPanel testpane = new JPanel(new GridBagLayout());
            testpane.setBackground(Color.CYAN);
            JLabel lblTest = new JLabel("test");
            lblTest.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("panelClicked");
              public void mouseEntered(MouseEvent e){
                  System.out.println("panelEntered");
              public void mouseExited(MouseEvent e){
                  System.out.println("panelExited");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
            testpane.add(lblTest,gridBagConstraints);
            this.add(testpane);
    class MultiRenderer extends DefaultTableCellRenderer {
      JCheckBox checkBox = new JCheckBox();
      public Component getTableCellRendererComponent(
                         JTable table, Object value,
                         boolean isSelected, boolean hasFocus,
                         int row, int column) {
        if (value instanceof Boolean) {                    // Boolean
          checkBox.setSelected(((Boolean)value).booleanValue());
          checkBox.setHorizontalAlignment(JLabel.CENTER);
          return checkBox;
        String str = (value == null) ? "" : value.toString();
        return super.getTableCellRendererComponent(
             table,str,isSelected,hasFocus,row,column);
        return (testpane)value;
    class MultiEditor implements TableCellEditor {
      public MultiEditor() {
      public boolean isCellEditable(EventObject anEvent) {return false;}
      public boolean stopCellEditing() {return true;}
      public Object getCellEditorValue() {return null;} 
      public void cancelCellEditing() {}
      public boolean shouldSelectCell(EventObject anEvent) {return false;}
      public Component getTableCellEditorComponent(JTable table, Object value,
                  boolean isSelected, int row, int column) {
        if (value instanceof testpane) {                       // ComboString
          System.out.println("yes instance");
        return null;
      public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
      public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
    }

    any help on this.. anybody. ?

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • How do i do that? MultiLine in a cell of JTable !!!

    Dear friends,
    I am trying to add multiline in a cell of JTable. For that bellow code i have written, but my statement in cell displays in a line only. Code is given bellow (copy/paste/run), could anyone help me how to do that?
    Regards..
    Jaya.
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class OtL extends JFrame {
        public OtL()
          initComponents();
        private void initComponents() {
            model1 = new DefaultTableModel();
            btnClose  = new javax.swing.JButton();
            tblOt       = new javax.swing.JTable(model1);
            scrOt   = new javax.swing.JScrollPane();
            TableCellRenderer renderer = new TableRenderer();
            tblOt.setDefaultRenderer(Object.class,renderer);
            tblOt.setRowHeight(tblOt.getRowHeight()*3);
            tblOt.setBackground(new java.awt.Color(250,225,162));
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            btnClose.setText("CLOSE");
            btnClose.setToolTipText("Close This Screen");
            btnClose.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
            btnClose.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                  System.exit(0);
            getContentPane().add(btnClose);
            btnClose.setBounds(380, 470, 110, 25);
            tblOt.setToolTipText("Operation Theatre Booking List");
            scrOt.setViewportView(tblOt);
            tableSize();
            scrOt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
            scrOt.setToolTipText("Operation Theatre Booking List");
            getContentPane().add(scrOt);
            scrOt.setBounds(15, 150, 770, 300);
            displayOtList();
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            JFrame j  = new OtL();
            j.setSize(800,560);
            j.show();
    /**********Code for displaying Operation Theater Booking List****Start Here*************/
        public void displayOtList(){
    Here i fire a sql query and i populate data in table.
    Sometime i get more than 1 value for some column e.g Surgery Name and Surgeon Name, so
    i want to display more than 1 value in the same cell. like bellow i have mentiond for
    5th and 6th column. But its displayin in one line only, how can i display that in multiple line!!
    I know that can be taken care with  Renderer, i tried but couldn't go through. I have written TableRenderer
    class for that, please help me what should i do in Renderer class.
          int row1=0;
          tableSize();
          DefaultTableModel model1 = (DefaultTableModel)tblOt.getModel();
          Object[] newRow = new Object[6];
            for(int i=0;i<1;i++){
              row1 = tblOt.getRowCount() + 1;
              newRow[0] = "1";
              newRow[1] = "10:10";
              newRow[2] = "11:30";
              newRow[3] = "Name Here";
              newRow[4] = "Surgery Name1 \n Surgery Name2";
              newRow[5] = "Dr. Amit \n Dr. Johnson";
              model1.addRow(newRow);
    /**********Code for displaying Operation Theater Booking List****End Here*************/
       class TableRenderer extends DefaultTableCellRenderer{
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean
    hasFocus, int row, int column)
           super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
          setOpaque(true);
           return this;
    /******tableSize()*****code for sizing table******start here()********/
      public void tableSize(){
        tblOt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {"Ot No.", "Start Time","End Time", "Patient Name", "Surgery Name","Surgeon Name"}
        TableColumn column = null;
        for (int i = 0; i < 6; i++) {
          column = tblOt.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(5);
          if (i == 1) {
            column.setPreferredWidth(15);
          if (i == 2) {
          column.setPreferredWidth(15);
          if (i == 3) {
            column.setPreferredWidth(130);
          if (i == 4) {
            column.setPreferredWidth(130);
          if (i == 5) {
            column.setPreferredWidth(130);
    /******tableSize()*****code for sizing table******end here()********/
        private javax.swing.JButton btnClose;
        private javax.swing.JScrollPane scrOt;
        private javax.swing.JTable tblOt;
        private DefaultTableModel model1;
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    OK Filne, Thanx .. its displaying data in multiple line now.
    But still there is a problem, whenever i move mouse over the table row it returns error like bellow. I am not able to findout the reason of error. I tried to put code in try{} catch{} block to avoid this error, but still its coming. Help me.....!!!!!!!!
    java.lang.NullPointerException
            at javax.swing.text.View.getViewIndex(View.java:1060)
            at javax.swing.text.View.getToolTipText(View.java:1031)
            at javax.swing.plaf.basic.BasicTextUI.getToolTipText(BasicTextUI.java:1057)
            at javax.swing.text.JTextComponent.getToolTipText(JTextComponent.java:1533)
            at javax.swing.JTable.getToolTipText(JTable.java:2380)
            at javax.swing.ToolTipManager$insideTimerAction.actionPerformed(ToolTipManager.java:669)
            at javax.swing.Timer.fireActionPerformed(Timer.java:256)
            at javax.swing.Timer$DoPostEvent.run(Timer.java:190)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:167)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:437)
            at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)my latest programe code is here :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class OtL extends JFrame {
        public OtL()
          initComponents();
        private void initComponents() {
            model1 = new DefaultTableModel();
            btnClose  = new javax.swing.JButton();
            tblOt       = new javax.swing.JTable(model1);
            scrOt   = new javax.swing.JScrollPane();
            TableCellRenderer renderer = new TableRenderer();
            tblOt.setDefaultRenderer(Object.class,renderer);
            tblOt.setRowHeight(tblOt.getRowHeight()*3);
            tblOt.setBackground(new java.awt.Color(250,225,162));
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            btnClose.setText("CLOSE");
            btnClose.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED));
            btnClose.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                  System.exit(0);
            getContentPane().add(btnClose);
            btnClose.setBounds(380, 470, 110, 25);
            scrOt.setViewportView(tblOt);
            tableSize();
            scrOt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
            getContentPane().add(scrOt);
            scrOt.setBounds(15, 150, 770, 300);
            displayOtList();
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
        public static void main(String args[]) {
            JFrame j  = new OtL();
            j.setSize(800,560);
            j.show();
        public void displayOtList(){
          int row1=0;
          tableSize();
          DefaultTableModel model1 = (DefaultTableModel)tblOt.getModel();
          Object[] newRow = new Object[6];
            for(int i=0;i<1;i++){
              row1 = tblOt.getRowCount() + 1;
              newRow[0] = "1";
              newRow[1] = "10:10";
              newRow[2] = "11:30";
              newRow[3] = "Name Here";
              newRow[4] = "Surgery Name1 \n Surgery Name2";
              newRow[5] = "Dr. Amit \n Dr. Johnson";
              model1.addRow(newRow);
       class TableRenderer extends JTextArea implements TableCellRenderer{
          public TableRenderer(){
            setLineWrap(true);
            setWrapStyleWord(true);
            setOpaque(true);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean
    hasFocus, int row, int column)
          if (isSelected) {
            setForeground(tblOt.getSelectionForeground());
            setBackground(tblOt.getSelectionBackground());
          } else {
            setForeground(tblOt.getForeground());
          setFont(tblOt.getFont());
          if (hasFocus) {
            setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
              if (tblOt.isCellEditable(row, column)) {
                setForeground( UIManager.getColor("Table.focusCellForeground") );
                setBackground( UIManager.getColor("Table.focusCellBackground") );
              } else {
            setBorder(new EmptyBorder(1, 2, 1, 2));
          setText((value == null) ? "" : value.toString());
          return this;
    /******tableSize()*****code for sizing table******start here()********/
      public void tableSize(){
        tblOt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {"Ot No.", "Start Time","End Time", "Patient Name", "Surgery Name","Surgeon Name"}
        TableColumn column = null;
        for (int i = 0; i < 6; i++) {
          column = tblOt.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(5);
          if (i == 1) {
            column.setPreferredWidth(15);
          if (i == 2) {
          column.setPreferredWidth(15);
          if (i == 3) {
            column.setPreferredWidth(130);
          if (i == 4) {
            column.setPreferredWidth(130);
          if (i == 5) {
            column.setPreferredWidth(130);
    /******tableSize()*****code for sizing table******end here()********/
        private javax.swing.JButton btnClose;
        private javax.swing.JScrollPane scrOt;
        private javax.swing.JTable tblOt;
        private DefaultTableModel model1;
    }

Maybe you are looking for

  • Resoring prodution database into new installed sap system

    have installed ecc 6.0 with sql server 2008 (sp 1) on windows 2003 server with 64 bit. My installtion was done sussfully and also i started sap system.It was working fine. then i took backup from my standalone system . I restored prodution server dat

  • Rendering a 3D scene in photoshop CC 2014

    I must have changed something or my file has gone bad, because suddenly photoshop will render my 3D scene clear; when it had no problem rendering the image many times before. I'm guessing it has something to do with certain layers being greyed out, I

  • PS CC not compatible with Yosemite?

    I just have installed PS CC. But it cannot start. Doesn´t it work with Mac OS Yosemite?? Regards, Michaela

  • Redirect subdomain to tomcat

    Hi, I'm getting confused. I want to forward requests of a subdomain (cms.klimtoren.be) to tomcat. Tomcat is installed and working at http://localhost:8080/cms (located at /Library/Tomcat/) I also use the webserver of mac for static content at www.kli

  • Function module to replace CSAP_MAT_BOM_READ

    Hi    I have a requirement in which I use the function module CSAP_MAT_BOM_READ to read the material BOM. The problem is that there is a huge chunk of data and for each record it calls the function module which is causing a performance issue.    I tr