JTable problem...can anybody help me...

hi i have try out some jtable program. I have done some alteration to the table that it can resize row and column via the gridline. but it seems that when i'm resizing through the gridline, the row header did not resize. I sense that the row header not syncronizing with the main table. So when i'm tried to resize, the row header didn't
can you solve my problem...
//the main program
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Test {     public static void main(String[] args)
     //row headers:     
     String[][] rowHeaders = {{"Alpha"},{"Beta"}, {"Gamma"}};
     JTable leftTable = new JTable(rowHeaders, new Object[]{""});
     leftTable.setDefaultRenderer(
          Object.class, leftTable.getTableHeader().getDefaultRenderer());
     leftTable.setPreferredScrollableViewportSize(new Dimension(50,100));      
     //main table:
     Object[][] sampleData = {{"Homer", "Simpson"},{"Seymour","Skinner"},{"Ned","Flanders"}};
     JTable mainTable = new JTable(sampleData, new Object[]{"",""});
     //scroll pane:
     JScrollPane sp = new JScrollPane(
          mainTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);     
          sp.setRowHeaderView(leftTable);          
          sp.setColumnHeaderView(null);      
     new TableColumnResizer(mainTable);
     new TableRowResizer(mainTable); 
     //frame:
     final JFrame f = new JFrame("Test");
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     f.getContentPane().add(sp);     
     f.pack();
     SwingUtilities.invokeLater(new Runnable(){
               public void run(){     f.setLocationRelativeTo(null);
                                   f.setVisible(true);               }          });     
}This the TableColumnResizer.java
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.*;
public class TableColumnResizer extends MouseInputAdapter
    public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
    private int mouseXOffset;
    private Cursor otherCursor = resizeCursor;
    private JTable table;
    public TableColumnResizer(JTable table){
        this.table = table;
        table.addMouseListener(this);
        table.addMouseMotionListener(this);
    private boolean canResize(TableColumn column){
        return column != null
                && table.getTableHeader().getResizingAllowed()
                && column.getResizable();
    private TableColumn getResizingColumn(Point p){
        return getResizingColumn(p, table.columnAtPoint(p));
    private TableColumn getResizingColumn(Point p, int column){
        if(column == -1){
            return null;
        int row = table.rowAtPoint(p);
        if(row==-1)
            return null;
        Rectangle r = table.getCellRect(row, column, true);
        r.grow( -3, 0);
        if(r.contains(p))
            return null;
        int midPoint = r.x + r.width / 2;
        int columnIndex;
        if(table.getTableHeader().getComponentOrientation().isLeftToRight())
            columnIndex = (p.x < midPoint) ? column - 1 : column;
        else
            columnIndex = (p.x < midPoint) ? column : column - 1;
        if(columnIndex == -1)
            return null;
        return table.getTableHeader().getColumnModel().getColumn(columnIndex);
    public void mousePressed(MouseEvent e){
        table.getTableHeader().setDraggedColumn(null);
        table.getTableHeader().setResizingColumn(null);
        table.getTableHeader().setDraggedDistance(0);
        Point p = e.getPoint();
        // First find which header cell was hit
        int index = table.columnAtPoint(p);
        if(index==-1)
            return;
        // The last 3 pixels + 3 pixels of next column are for resizing
        TableColumn resizingColumn = getResizingColumn(p, index);
        if(!canResize(resizingColumn))
            return;
        table.getTableHeader().setResizingColumn(resizingColumn);
        if(table.getTableHeader().getComponentOrientation().isLeftToRight())
            mouseXOffset = p.x - resizingColumn.getWidth();
        else
            mouseXOffset = p.x + resizingColumn.getWidth();
    private void swapCursor(){
        Cursor tmp = table.getCursor();
        table.setCursor(otherCursor);
        otherCursor = tmp;
    public void mouseMoved(MouseEvent e){
        if(canResize(getResizingColumn(e.getPoint()))
           != (table.getCursor() == resizeCursor)){
            swapCursor();
    public void mouseDragged(MouseEvent e){
        int mouseX = e.getX();
        TableColumn resizingColumn = table.getTableHeader().getResizingColumn();
        boolean headerLeftToRight =
                table.getTableHeader().getComponentOrientation().isLeftToRight();
        if(resizingColumn != null){
            int oldWidth = resizingColumn.getWidth();
            int newWidth;
            if(headerLeftToRight){
                newWidth = mouseX - mouseXOffset;
            } else{
                newWidth = mouseXOffset - mouseX;
            resizingColumn.setWidth(newWidth);
            Container container;
            if((table.getTableHeader().getParent() == null)
               || ((container = table.getTableHeader().getParent().getParent()) == null)
                                || !(container instanceof JScrollPane)){
                return;
            if(!container.getComponentOrientation().isLeftToRight()
               && !headerLeftToRight){
                if(table != null){
                    JViewport viewport = ((JScrollPane)container).getViewport();
                    int viewportWidth = viewport.getWidth();
                    int diff = newWidth - oldWidth;
                    int newHeaderWidth = table.getWidth() + diff;
                    /* Resize a table */
                    Dimension tableSize = table.getSize();
                    tableSize.width += diff;
                    table.setSize(tableSize);
                     * If this table is in AUTO_RESIZE_OFF mode and has a horizontal
                     * scrollbar, we need to update a view's position.
                    if((newHeaderWidth >= viewportWidth)
                       && (table.getAutoResizeMode() == JTable.AUTO_RESIZE_OFF)){
                        Point p = viewport.getViewPosition();
                        p.x =
                                Math.max(0, Math.min(newHeaderWidth - viewportWidth, p.x + diff));
                        viewport.setViewPosition(p);
                        /* Update the original X offset value. */
                        mouseXOffset += diff;
    public void mouseReleased(MouseEvent e){
        table.getTableHeader().setResizingColumn(null);
        table.getTableHeader().setDraggedColumn(null);
} This is TableRowResizer.java
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
public class TableRowResizer extends MouseInputAdapter
    public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
    private int mouseYOffset, resizingRow;
    private Cursor otherCursor = resizeCursor;
    private JTable table;
    public TableRowResizer(JTable table){
        this.table = table;
        table.addMouseListener(this);
        table.addMouseMotionListener(this);
    private int getResizingRow(Point p){
        return getResizingRow(p, table.rowAtPoint(p));
    private int getResizingRow(Point p, int row){
        if(row == -1){
            return -1;
        int col = table.columnAtPoint(p);
        if(col==-1)
            return -1;
        Rectangle r = table.getCellRect(row, col, true);
        r.grow(0, -3);
        if(r.contains(p))
            return -1;
        int midPoint = r.y + r.height / 2;
        int rowIndex = (p.y < midPoint) ? row - 1 : row;
        return rowIndex;
    public void mousePressed(MouseEvent e){
        Point p = e.getPoint();
        resizingRow = getResizingRow(p);
        mouseYOffset = p.y - table.getRowHeight(resizingRow);
    private void swapCursor(){
        Cursor tmp = table.getCursor();
        table.setCursor(otherCursor);
        otherCursor = tmp;
    public void mouseMoved(MouseEvent e){
        if((getResizingRow(e.getPoint())>=0)
           != (table.getCursor() == resizeCursor)){
            swapCursor();
    public void mouseDragged(MouseEvent e){
        int mouseY = e.getY();
        if(resizingRow >= 0){
            int newHeight = mouseY - mouseYOffset;
            if(newHeight > 0)
                table.setRowHeight(resizingRow, newHeight);
}

cross-post: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=755250

Similar Messages

  • JTable Problem Can any1 help??

    Hi there,
    I am pretty new to java so please forgive me if this is a silly question but I can not fix this.
    I have a JTable which when I enter a code a new line is added to the table describing the code entered. But when I press a button I basically want to delete everything in the jTable and start a fresh.
    Can anyone help me please :)

    Hi,
    I am not sure as to how you are constructing the JTable.
    But this is one of the way.
    DefaultTableModel tm = new DefaultTableModel(....see definitions to get one that suits);
    JTable myTable = new JTable(tm);
    Now in your actionPerformed method for the clear button-
    int rowcount = getRowCount();
    for(int i = rowcount - 1; i>=0; i-- ){
    tm.removeRow(i);
    Hope it helps
    Best of Luck
    Vignesh

  • Photo could not be found Problems - can anybody help

    On opening iPhoto I get  an error message saying 'The photo .... could not be opened because the original could not be found'. When I cancel another pops up and there appears to be hundreds of them. iPhoto is frozen and the only way to get out is Force Quitting.
    The library I use is an Aperture library and the sharing with Aperture used to be OK. What is particularly puzzling is that when I open the library in Aperture there are no problems and all photos appear to be there. I can work quite happily in Aperture with no apparent difficulties.
    However I do like to use IPhoto as well. I have tried rebuilding the iphoto library. I have uninstalled iPhoto and supporting files using App Zapper and I have reinstalled. However the problem is still there.
    Anybody got any advice as to how I can resolve this problem?
    I am using latest versions of all software.

    The library I use is an Aperture library and the sharing with Aperture used to be OK. What is particularly puzzling is that when I open the library in Aperture there are no problems and all photos appear to be there. I can work quite happily in Aperture with no apparent difficulties.
    Have you checked the original master image files in Aperture? Are the original master image files in Aperture  referenced or managed? Do you see the originals, when you toggle between original and version by pressing the "M" key?
    I'd suggest to use the Aperture Library Firts Aid Tools to repair the Database and to reair the permissions, since it is an Aperture Library, see: Repairing and Rebuilding Your Aperture Library: Aperture 3 User Manual
    What are your Aperture and iPhoto versions? Have you upgraded recently?
    Regards
    Léonie

  • Installing XP on a macbook - I have a problem can anybody help me?

    I have a macbook running Snow Leopard and I tried to use Bootcamp to install Windows XP.
    Bootcamp runs ok and I was taken through the partitioning but when I get to the "Welcome to Setup" screen with the following options ....
    To Set up Windows XP now, press ENTER
    To repair a Windows XP installation using Recovery Console, press R
    To quit setup without installing Windows XP. press F3
    the keyboard won't allow me to do anything - I can't press enter, R or F3 and I have to turn the computer off at the power button.
    Does anybody have any idea where I am going wrong?
    Thanks, Angela

    Are you installing Windows XP (32-bit) SP2 or higher? SP1 is not supported; wondering if you've been trying to install Sp1?
    Also if you're using a wireless keyboard and mouse, try connecting a USB keyboard before powering up and hopefully WinXP installation can be repaired.

  • Concurrent transactions problem- Can anybody help?- very urgent

    I have tested our application for multiple transactions i.e. concurrent transactions between two servers with IIS and Tomcat environment. We found some unexpected result and which is irrespective of the data (size ranging from 10 bytes to 10 kb, 50kb 70kb etc) sending across the servers on
    I was testing with 5 transactions (with data size of 13 bytes) from one machine (server1) i.e 5 windows of internet explorer. When I clicked on all the five, one after another quickly, I found that 4 transactions got success and one browser went to hang mode.
    Second time when I clicked on it, I found that 3 transactions got success, 1 in hang mode and 1 failed.
    We traced the exception at the point where it fails. Everytime it fails while reading the response back from the other end through InputStreamBuffer. The block in which it fails is
    Please follow the piece of code which i have written
    //reading response from the destination decrypt url,
    //which is also encrypted and signed
    //sending the same to caller of encrypt
    String data="";
    int end=0;
    char c[]=new char[4*1024];
    BufferedReader buf=null;
    //reading data in a chunks of data
    try
    inr=new InputStreamReader(connection.getInputStream());
    buf=new BufferedReader(inr,12*1024);
    while ((end=buf.read(c))!=-1)
    data=new StringBuffer(data).append(c,0,end).toString();
    catch(OutOfMemoryError e)
    System.out.println("Out of memory errror"+e.getMessage());
    try
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
    catch(Exception e1)
    return;
    catch(Exception e1)
    System.out.println("Failure in reading response"+e1.getMessage());
    try
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
    catch(Exception e2)
    return;
    finally
    try
    if(inr!=null)
    inr.close();
    if(buf!=null)
    buf.close();
    if (connection != null)
    connection.disconnect();
    catch(Exception e)
    System.out.println("Error in closing connection"+e.getMessage());
    Here the connection get disconnected and throws the following exceptions at difterent time of testing in failure case.
    1. Failure in reading response JVM_recv in socket input stream read (code=10004)
    Error in closing connection Socket closed
    2. Null pointer exception.
    Could you please tell us what would be the reasons for the above exceptions or failure and how to rectify or handle it.
    Thanks & Regards
    Gabriel

    - First, do not use BufferedReader.
    Use InputStream.read(byte[]) and make them to an String.
    If does not help use another stable version of TOMCAT
    on the same way.
    Also it is better to read the data over the Servlet API
    methods not over the IO streams.
    e.g. request.getParameter("XXX")
    - Do not close the socket connection in TOMCAT.
    TOMCAT themselves close the connection for you.
    Use the flush() method for getting the data faster.

  • I cannot open iCal because of a problem. Can anybody help me? The computer will not allow it to open and sends a message to apple each time. The icon has gone from the dock, but ical works on my iPad and I am afraid to sync it with my computer.?

    I cannot open iCal because of a problem. Can anybody help me? The computer will not allow it to open and sends a message to apple each time. The icon has gone from the dock, but ical works on my iPad and I am afraid to sync it with my computer in case it wipes everything .

    I have the exact same problem. I have not changed anything. This is probably a bug or something that has gone bad with Mac OS X (10.7.2). I have not found any solution for this on the web.
    MacBook Pro, Mac OS X (10.7.2).

  • Hi can anybody help please. I am having terrible problems trying to use my Nikon D7100 to tether. I have downloaded the latest Lightroom updates and also checked my firmware which is also the latest avaiable and still Lightroom wont detect my camera!

    Hi can anybody help please. I am having terrible problems trying to use my Nikon D7100 to tether. I have downloaded the latest Lightroom updates and also checked my firmware which is also the latest avaiable and still Lightroom wont detect my camera!. When I use a friends Canon camera it works every time!

    Hi Keith thanks for your reply I have Lightroom 5.7.1 64 bit and my Nikon's firmware is version 1.02

  • Having big problems with my new Mac Pro, when I launch Photoshop CC, I get an error message, can carry on but after a few tasks it starts going gar... menus go blank, when you try to save it shows a blank box.... can anybody help?

    Having big problems with my new Mac Pro, when I launch Photoshop CC, I get an error message, can carry on but after a few tasks it starts going gar... menus go blank, when you try to save it shows a blank box.... can anybody help?

    when I launch Photoshop CC, I get an error message
    and what exactly is the text of that error message?

  • Hello friends, my itunes has stopped working. and the problem report stated the following: Fault Module Name:     KERNELBASE.dll   Fault Module Version:     6.1.7601.17514.................. please can anybody help me?hello friends, my itunes has stopped w

    Hello everybody> my itunes has stopped working and the problem report stated the following:
    Problem signature:
      Problem Event Name:    APPCRASH
      Application Name:    iTunes.exe
      Application Version:    10.5.3.3
      Application Timestamp:    4f14cc3d
      Fault Module Name:    KERNELBASE.dll
      Fault Module Version:    6.1.7601.17514
      Fault Module Timestamp:    4ce7b8f0
      Exception Code:    80000003
      Exception Offset:    0003381b
      OS Version:    6.1.7601.2.1.0.256.1
      Locale ID:    1033
      Additional Information 1:    0a9e
      Additional Information 2:    0a9e372d3b4ad19135b953a78882e789
      Additional Information 3:    0a9e
      Additional Information 4:    0a9e372d3b4ad19135b953a78882e789
    can anybody help me?

    Are you seeing a similar message when launching QuickTime Player?
    What security software is installed on the computer? Have you tried testing in an admin account or after uninstalling tthe security software?
    Use one of the following articles to guide you through removing iTunes and the related QuickTime files.
    Removing and Reinstalling iTunes, QuickTime, and other software components for Windows XP
    Removing and reinstalling iTunes, QuickTime, and other software components for Windows Vista or Windows 7

  • TS1559 After performing a software restore in iTunes, the problems remains... I still cannot turn Wifi on as it is still greyed out??? Can anybody help please?

    Have performed software restore and still I am unable to turn my wifi on as the option to turn on is greyed out???
    Can anybody help?.

    If no change after restoring the iPhone with iTunes as a new iPhone or not from the backup, make an appointment at an Apple Store if there is one nearby since this is a hardware problem.

  • I bought an new ipad 3rd gen 16 gb wifi cellular in may 2012. I hv a unique problem wherein the screen of ipad is not as smooth as what is general experience. Its not buggy but lacks smoothness and finger doesnot glide as smoothly . Can anybody help.

    i bought an new ipad 3rd gen 16 gb wifi cellular in may 2012. I hv a unique problem wherein the screen of ipad is not as smooth as what is general experience. Its not buggy but lacks smoothness and finger doesnot glide as smoothly .Can anybody help.

    Do you clean your iPad screen?  Do not use standard window cleaners, with ammonia or alcohol, like Windex, but a damp towel, followed by a micro-fibre cloth is recommended.  There are also cleaners you can buy which are specifically designed for iPad/iPhone devices, such as iClean from Monster.

  • My Numbers file sent to somebody is not able to open in Excel can anybody help to solve this problem?

    my Numbers file sent to somebody. He is not able to open in Excel can anybody help to solve this problem?

    Numbers files are not compatible with MS Excel.  To share a Numbers file with Excel you need to export you Numbers file in MS Excel format.  To do this:
    1) Open you Numbers document
    2) select the menu item "File > Export..."
    3) select "Excel" for the target output
    4) click next and select where to save the file.
    5) email the file you saved

  • I'm still having problems downloading. Can anybody help? Everytime I try yo download, it's saying my Adobe Flash CS4 won't download.

    I'm still having problems downloading. Can anybody help? Everytime I try yo download, it's saying my Adobe Flash CS4 won't download.

    UP%20%26 COMIN' what specific error message do you receive when you try to download the Creative Suite 4 installation files?  Which Creative Suite 4 title are you downloading?  Are you downloading the installation files from https://helpx.adobe.com/creative-suite/kb/cs4-product-downloads.html?

  • Here is my problem: "To open "Adobe Photoshop CS5.1" you need to install the legacy Java SE 6 RUNTIME" after upgrading iMac to Yosemite, can anybody help?

    Here is my problem: "To open "Adobe Photoshop CS5.1" you need to install the legacy Java SE 6 RUNTIME" after upgrading iMac to Yosemite, can anybody help?

    This answer may be somewhat late, but just in case other have the same issues, I went to site listed below and it solved the problem.  No need to reinstall CS5 product.  I hope this works for you.
    http://support.apple.com/kb/DL1572

  • I try to restore my ipod mini 4gb  but i get the 1437 error? can anybody help me with this problem?

    ok i have had the ipod fr a while and when i try and restore it gives me the 1437 error? i have no clue what this mean, can anybody help me? when is specifys the ipods components like the name and capacity etc.. under capacity it says N/A?  get back to me please i miss having an ipod:((

    I wish I could offer a solution, because I too am about to go crazy trying to fix the same problem. I have tried everything in the support section, sometimes twice, to no avail. Now I have an empty ipod that won't connect to my computer much less iTunes.
    Any suggestions?

  • I am facing problem regarding graphical user interface. I am using text box for editing files. I want to show the line numbers and graphical breakpoint​s along with text box. Can anybody help me in this? Thanks.

    I am facing problem regarding graphical user interface. I am using text box for editing files. I want to show the line numbers and graphical breakpoints along with text box. Can anybody help me in this? Thanks.

    Thanks for you reply.
    But actually I don't want to show the \ (backslashes) to the user in my text box. 
    Ok let me elaborate this problem little more. 
    I want to show my text box as it is in normal editors e.g. In Matlab editor. There is a text box and on left side the gray bar shows the line numbers corresponding to the text. Further more i want that the user should be able to click on any line number to mark specific line as breakpoint (red circle or any graphical indication for mark). 
    Regards,
    Waqas Ahmad

Maybe you are looking for

  • Problem with TO_WKTGEOMETRY/FROM_WKTGEOMETRY

    Hello everyone I've installed Oracle 10g XE and I'm trying to use the geometry functions as described in OGC's Simple Features for SQL Spec. (see http://www.opengis.org/docs/99-049.pdf ), but they don't seem work. Is this a bug or is there a mistake

  • IFPM (Floor Plan Manager) method getCopyOfAllMessages()

    Hi All, this might not be the right forum to post this question, but I'm guessing more ESS WD developers look here than elsewhere. I'm currently trying to change the standard ESS travel application (ess-tra-tre) as per some customer requirements. The

  • Cant burn

    Hello, took me forever to find page that showed "post new topic" option. Posted this question previously in "can't burn a cd" thread but no answer, maybe not noticed. When I put in a new CD-RW sony 650 MB, or DVD-RAM 2.6 0r 5.2 GB hotan and others dr

  • Missing plugin for Sequence

    Im happy with the program yet i try to pick my sequence and GET THIS Please Respond as soo as possible THANK YOU!!

  • Anchor Links, Need Help!

    I've read anchor links can be done in iWeb by doing my own html; but how, exactly, to I do that? I would like to create alphabetical anchor links on a list I've published. (Click on "b" or "c" and it takes you to the "b's" or "C's" on the list. Thank