JTable Problems - JDK 1.2.2_05a & JDK 1.3.0

Hi,
I have a JTable program that works in JDK 1.2.2_05a but it no longer works when I run the 1.2.2 compiled version in a 1.3.0 environment or compiled and run in a 1.3.0 environment. The problem is that the JTable doesn't accept any keyboard inputs. Is there a known issue about this? If not, has anyone else run into this problem before? Any help is greatly appreciated. Many Thanks In Advance!
Juivette

I too face a similar problem. I had a JTable code which worked perfectly in 1.3.0. But when I recompiled it in 1.2.2_09 and ran it., I get square boxes when I try to set value to a cell.
I think., the square box is the Enter Key I press for setting value. Has any one faced this problem before ?
and suggest how to overcome ??
regards
Sriram

Similar Messages

  • Lower case q in jtables in JDK 1.3/JDev 3.2

    Has anyone gotten the lower case "q"
    to be accepted on a tab into a jtable column (as in a gridcontrol), under JDev 3.2/JDK 1.3?
    I am still not getting this to work, although Sun claims it fixed in 1.3?
    (The JDev "About" box says I'm using 1.3)

    Resolved. sigh.
    Lower case "q" is now accepted correctly in jtables.
    Reason ( embarassment ) for the original post: I changed the Default Project Properties to JDK 1.3, per instructions in the JDev 3.2 readme.
    Uh, when one brings in an existing project into your JDev 3.2 workspace, one must explicitly change the Project Properties for THAT Project from the 1.2 it was created under to 1.3( of course ).
    null

  • Installation problem - JDK 6 on Ubuntu 9.04

    Hello, I'm an old programmer (60+!) but new to Unix/Java/OE. I've bought 'Teach yourself Java 6 in 21 days', which recommends using the Java Development Kit for initial learning. Following the instructions on the Sun site, I downloaded the file 'jdk-6u13-nb-6_5_1-linux-ml.sh' onto my ubuntu 9.04 system and installed it. The install completed, but gave some error messages, viz:
    Configuring the installer...
    Searching for JVM on the system...
    Preparing bundled JVM ...
    Extracting installation data...
    Running the installer wizard...
    (<unknown>:9222): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:9222): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:9222): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9222): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    Can anyone tell me WIHIH, and what to do about it ?
    Bob Unitt
    Edited by: Bob_Unitt on May 29, 2009 8:14 AM
    Corrected typo in Subject

    I just recently installed the new jdk1.6.0_14 via the .bin file provided on the java.sun.com site. Pretty straight forward..
    just placed the .bin file in a comfortable spot and ran /bin/sh on it.
    From there I just needed to add its path enviroment script's PATH declaration.
    To hook it up to firefox, just create the "plugin" folder for .mozilla (i.e. ~/.mozilla/plugin)
    then create a symbolic link to libjavaplugin_oji.so (i.e. ln -s .../jdk1.6.0_14/jre/plugin/i386/ns7/libjavaplugin_oji.so ~/.mozilla/plugin/),
    then rename the link to "javaplugin.so" in the ~/.mozilla/plugin directory. (something I had to do for Ubuntu 9.04 Jaunty Jackalope and Firefox 3, says the Ubuntu forums)
    By the way Ubuntu 9.04 comes with jdk1.6.0_13 if you install it from the repositories via sabre150's methods so you're better off doing it his way ;).

  • Installation problem JDK 1.5 on Windows 2000 server

    I am trying to install the new J2SE Development Kit 5.0 for Windows 32 bit on a windows server 2000 computer with sp4. When I attempt to execute the file
    I get the following result
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x036eb514, pid=1872, tid=1592
    # Java VM: Java HotSpot(TM) Client VM (1.4.2_10-b03 mixed mode)
    # Problematic frame:
    # C [awt.dll+0xb514]
    I see that the log file refers to Hot spot client 1.4.2 - I'll post the rest of log if necessary but thought I would try asking in case the solution is clear without the full log.
    I understand JDK 5.0 can be installed on windows 2000 server with service pack 3 or 4. Any help would be appreciated.
    Thank you.

    I've checked all these possibilities:
    (1) DLL's associated with JAVA - none other than 1.5
    (2) Path makes no reference to 1.4 anywhere
    (3) No othe java programs are listed in add/remove programs
    (4) no oracle product is installed
    (5) windows 2000 registry does not contain anything obviously associated with 1.4.2
    IS any Java product included automatically with Windows 2000 Service pack 4?
    Here is the full log file text:
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x036eb514, pid=928, tid=1916
    # Java VM: Java HotSpot(TM) Client VM (1.4.2_10-b03 mixed mode)
    # Problematic frame:
    # C [awt.dll+0xb514]
    --------------- T H R E A D ---------------
    Current thread (0x02c0a160): JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1916]
    siginfo: ExceptionCode=0xc0000005, reading address 0x00006ffd
    Registers:
    EAX=0x00001bf8, EBX=0x037bf638, ECX=0x0000001d, EDX=0x0000001d
    ESP=0x03a5f460, EBP=0x081471cd, ESI=0x000000f8, EDI=0x00000004
    EIP=0x036eb514, EFLAGS=0x00010202
    Top of Stack: (sp=0x03a5f460)
    0x03a5f460: fffffffc 02c0a1fc 037ae360 00000004
    0x03a5f470: 086c0e44 ffccffff 037bf5f8 037bf5b8
    0x03a5f480: 00000000 00000000 00000000 036e1a43
    0x03a5f490: 03a60000 00000038 00000278 00000189
    0x03a5f4a0: 00000278 03a5f514 037ae360 03a5f508
    0x03a5f4b0: 02c0a160 0c14c8f8 03a5f654 0c14c8b0
    0x03a5f4c0: 02b30a48 00000004 037ae360 00000000
    0x03a5f4d0: 02bdaf98 00000004 00000017 0000027c
    Instructions: (pc=0x036eb514)
    0x036eb504: 00 00 83 e6 f8 c1 e0 05 c1 e9 03 03 c6 03 d1 45
    0x036eb514: 8a 0c 82 8b 44 24 30 88 08 40 89 44 24 30 8b 44
    Stack: [0x03a20000,0x03a60000), sp=0x03a5f460, free space=253k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    C [awt.dll+0xb514]
    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j sun.java2d.loops.Blit.Blit(Lsun/java2d/SurfaceData;Lsun/java2d/SurfaceData;Ljava/awt/Composite;Lsun/java2d/pipe/Region;IIIIII)V+0
    j sun.java2d.pipe.DrawImage.blitSurfaceData(Lsun/java2d/SunGraphics2D;Lsun/java2d/SurfaceData;Lsun/java2d/SurfaceData;Lsun/java2d/loops/SurfaceType;Lsun/java2d/loops/SurfaceType;IIIIIILjava/awt/Color;)V+89
    j sun.java2d.pipe.DrawImage.renderSurfaceData(Lsun/java2d/SunGraphics2D;Lsun/java2d/SurfaceData;Ljava/awt/Color;IIIIII)V+40
    j sun.java2d.pipe.DrawImage.copyImage(Lsun/java2d/SunGraphics2D;Ljava/awt/Image;IIIIIILjava/awt/Color;)Z+58
    j sun.java2d.pipe.DrawImage.copyImage(Lsun/java2d/SunGraphics2D;Ljava/awt/Image;IILjava/awt/Color;)Z+30
    j sun.java2d.pipe.DrawImage.copyImage(Lsun/java2d/SunGraphics2D;Ljava/awt/Image;IILjava/awt/Color;Ljava/awt/image/ImageObserver;)Z+15
    j sun.java2d.SunGraphics2D.drawImage(Ljava/awt/Image;IILjava/awt/Color;Ljava/awt/image/ImageObserver;)Z+12
    j sun.java2d.SunGraphics2D.drawImage(Ljava/awt/Image;IILjava/awt/image/ImageObserver;)Z+7
    j javax.swing.JComponent.paintWithOffscreenBuffer(Ljavax/swing/JComponent;Ljava/awt/Graphics;IIIILjava/awt/Image;)V+223
    j javax.swing.JComponent.paintDoubleBuffered(Ljavax/swing/JComponent;Ljava/awt/Component;Ljava/awt/Graphics;IIII)Z+131
    j javax.swing.JComponent.paint(Ljava/awt/Graphics;)V+208
    j java.awt.GraphicsCallback$PaintCallback.run(Ljava/awt/Component;Ljava/awt/Graphics;)V+2
    j sun.awt.SunGraphicsCallback.runOneComponent(Ljava/awt/Component;Ljava/awt/Rectangle;Ljava/awt/Graphics;Ljava/awt/Shape;I)V+155
    j sun.awt.SunGraphicsCallback.runComponents([Ljava/awt/Component;Ljava/awt/Graphics;I)V+101
    j java.awt.Container.paint(Ljava/awt/Graphics;)V+62
    j sun.awt.RepaintArea.paint(Ljava/lang/Object;Z)V+324
    j sun.awt.windows.WComponentPeer.handleEvent(Ljava/awt/AWTEvent;)V+63
    j java.awt.Component.dispatchEventImpl(Ljava/awt/AWTEvent;)V+552
    j java.awt.Container.dispatchEventImpl(Ljava/awt/AWTEvent;)V+42
    j java.awt.Window.dispatchEventImpl(Ljava/awt/AWTEvent;)V+19
    j java.awt.Component.dispatchEvent(Ljava/awt/AWTEvent;)V+2
    j java.awt.EventQueue.dispatchEvent(Ljava/awt/AWTEvent;)V+41
    j java.awt.EventDispatchThread.pumpOneEventForHierarchy(ILjava/awt/Component;)Z+169
    j java.awt.EventDispatchThread.pumpEventsForHierarchy(ILjava/awt/Conditional;Ljava/awt/Component;)V+26
    j java.awt.EventDispatchThread.pumpEvents(ILjava/awt/Conditional;)V+4
    j java.awt.EventDispatchThread.pumpEvents(Ljava/awt/Conditional;)V+3
    j java.awt.EventDispatchThread.run()V+9
    v ~StubRoutines::call_stub
    --------------- P R O C E S S ---------------
    Java Threads: ( => current thread )
    =>0x02c0a160 JavaThread "AWT-EventQueue-0" [_thread_in_native, id=1916]
    0x02ca9fc0 JavaThread "AWT-Shutdown" [_thread_blocked, id=1924]
    0x02b2e4a8 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=1944]
    0x02b153e0 JavaThread "Image Fetcher 2" daemon [_thread_blocked, id=1984]
    0x02a94bd8 JavaThread "Image Fetcher 1" daemon [_thread_blocked, id=1776]
    0x02aa9da8 JavaThread "Image Fetcher 0" daemon [_thread_blocked, id=568]
    0x02a8d0d0 JavaThread "AWT-Windows" daemon [_thread_in_native, id=1276]
    0x009b9240 JavaThread "Thread-0" [_thread_in_native, id=1812]
    0x02b83db8 JavaThread "wizard.main" [_thread_blocked, id=1708]
    0x0023e378 JavaThread "CompilerThread0" daemon [_thread_blocked, id=2056]
    0x0091e130 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=2052]
    0x0091bb58 JavaThread "Finalizer" daemon [_thread_blocked, id=936]
    0x0091a780 JavaThread "Reference Handler" daemon [_thread_blocked, id=932]
    0x00236898 JavaThread "main" [_thread_blocked, id=1816]
    Other Threads:
    0x00959358 VMThread [id=1460]
    0x0095a008 WatcherThread [id=2044]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 1408K, used 474K [0x08140000, 0x082c0000, 0x085d0000)
    eden space 1280K, 29% used [0x08140000, 0x0819f868, 0x08280000)
    from space 128K, 71% used [0x082a0000, 0x082b6fb0, 0x082c0000)
    to space 128K, 0% used [0x08280000, 0x08280000, 0x082a0000)
    tenured generation total 18944K, used 3398K [0x085d0000, 0x09850000, 0x0bd40000)
    the space 18944K, 17% used [0x085d0000, 0x08921ab8, 0x08921c00, 0x09850000)
    compacting perm gen total 6144K, used 6083K [0x0bd40000, 0x0c340000, 0x0fd40000)
    the space 6144K, 99% used [0x0bd40000, 0x0c330c48, 0x0c330e00, 0x0c340000)
    Dynamic libraries:
    0x00400000 - 0x0040b000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\java.exe
    0x77f80000 - 0x77ffc000      C:\WINNT\system32\ntdll.dll
    0x7c2d0000 - 0x7c335000      C:\WINNT\system32\ADVAPI32.dll
    0x7c570000 - 0x7c623000      C:\WINNT\system32\KERNEL32.dll
    0x77d30000 - 0x77da8000      C:\WINNT\system32\RPCRT4.dll
    0x78000000 - 0x78045000      C:\WINNT\system32\MSVCRT.dll
    0x08000000 - 0x0813e000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\client\jvm.dll
    0x77e10000 - 0x77e79000      C:\WINNT\system32\USER32.dll
    0x77f40000 - 0x77f7c000      C:\WINNT\system32\GDI32.dll
    0x77570000 - 0x775a0000      C:\WINNT\system32\WINMM.dll
    0x10000000 - 0x10007000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\hpi.dll
    0x690a0000 - 0x690ab000      C:\WINNT\system32\PSAPI.DLL
    0x007c0000 - 0x007ce000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\verify.dll
    0x007d0000 - 0x007e9000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\java.dll
    0x007f0000 - 0x007fe000      C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\bin\zip.dll
    0x03050000 - 0x0305f000      C:\Documents and Settings\Administrator\Local Settings\Temp\LRE4.tmp\bin\net.dll
    0x75030000 - 0x75044000      C:\WINNT\system32\WS2_32.dll
    0x75020000 - 0x75028000      C:\WINNT\system32\WS2HELP.DLL
    0x782c0000 - 0x782cc000      C:\WINNT\System32\rnr20.dll
    0x77980000 - 0x779a4000      C:\WINNT\system32\DNSAPI.DLL
    0x75050000 - 0x75058000      C:\WINNT\system32\WSOCK32.dll
    0x77340000 - 0x77353000      C:\WINNT\system32\iphlpapi.dll
    0x77520000 - 0x77525000      C:\WINNT\system32\ICMP.DLL
    0x77320000 - 0x77337000      C:\WINNT\system32\MPRAPI.DLL
    0x75150000 - 0x75160000      C:\WINNT\system32\SAMLIB.DLL
    0x7cdc0000 - 0x7ce13000      C:\WINNT\system32\NETAPI32.DLL
    0x751c0000 - 0x751c6000      C:\WINNT\system32\NETRAP.dll
    0x77bf0000 - 0x77c01000      C:\WINNT\system32\NTDSAPI.dll
    0x77950000 - 0x7797b000      C:\WINNT\system32\WLDAP32.DLL
    0x7c340000 - 0x7c34f000      C:\WINNT\system32\SECUR32.DLL
    0x7ce20000 - 0x7cf0f000      C:\WINNT\system32\OLE32.DLL
    0x779b0000 - 0x77a4b000      C:\WINNT\system32\OLEAUT32.DLL
    0x773b0000 - 0x773df000      C:\WINNT\system32\ACTIVEDS.DLL
    0x77380000 - 0x773a3000      C:\WINNT\system32\ADSLDPC.DLL
    0x77830000 - 0x7783e000      C:\WINNT\system32\RTUTILS.DLL
    0x77880000 - 0x7790e000      C:\WINNT\system32\SETUPAPI.DLL
    0x7c0f0000 - 0x7c154000      C:\WINNT\system32\USERENV.DLL
    0x774e0000 - 0x77514000      C:\WINNT\system32\RASAPI32.DLL
    0x774c0000 - 0x774d1000      C:\WINNT\system32\rasman.dll
    0x77530000 - 0x77552000      C:\WINNT\system32\TAPI32.dll
    0x71710000 - 0x71794000      C:\WINNT\system32\COMCTL32.DLL
    0x70a70000 - 0x70ad6000      C:\WINNT\system32\SHLWAPI.DLL
    0x77360000 - 0x77379000      C:\WINNT\system32\DHCPCSVC.DLL
    0x777e0000 - 0x777e8000      C:\WINNT\System32\winrnr.dll
    0x777f0000 - 0x777f5000      C:\WINNT\system32\rasadhlp.dll
    0x03560000 - 0x0358d000      C:\Documents and Settings\Administrator\Local Settings\Temp\ismp001\win32ppk.dll
    0x7cf30000 - 0x7d175000      C:\WINNT\system32\SHELL32.dll
    0x75e60000 - 0x75e7a000      C:\WINNT\system32\IMM32.dll
    0x77820000 - 0x77827000      C:\WINNT\system32\VERSION.dll
    0x759b0000 - 0x759b6000      C:\WINNT\system32\LZ32.DLL
    0x036e0000 - 0x037f3000      C:\Documents and Settings\Administrator\Local Settings\Temp\LRE4.tmp\bin\awt.dll
    0x77800000 - 0x7781e000      C:\WINNT\system32\WINSPOOL.DRV
    0x76620000 - 0x76631000      C:\WINNT\system32\MPR.DLL
    0x03800000 - 0x03851000      C:\Documents and Settings\Administrator\Local Settings\Temp\LRE4.tmp\bin\fontmanager.dll
    VM Arguments:
    jvm_args: -Dsun.java2d.noddraw=true -Dtemp.dir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp -Dis.jvm.home=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp -Dis.jvm.temp=1 -Dis.media.home=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE5.tmp\setup.jar -Dis.launcher.file=C:\Downloads\JDK 1.5 Update 6\jdk-1_5_0_06-nb-4_1-win-ml.exe -Dis.jvm.file=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp\jvm -Dis.external.home=C:\Downloads\JDK 1.5 Update 6 -Xms20m -Xmx60m
    java_command: run
    Launcher Type: SUN_STANDARD
    Environment Variables:
    JAVA_HOME=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\LRE4.tmp
    PATH=C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;
    USERNAME=Administrator
    OS=Windows_NT
    PROCESSOR_IDENTIFIER=x86 Family 6 Model 7 Stepping 3, GenuineIntel
    --------------- S Y S T E M ---------------
    OS: Windows 2000 Build 2195 Service Pack 4
    CPU:total 1 family 6, cmov, cx8, fxsr, mmx, sse
    Memory: 4k page, physical 261668k(84712k free), swap 436140k(257692k free)
    vm_info: Java HotSpot(TM) Client VM (1.4.2_10-b03) for windows-x86, built on Oct 10 2005 14:53:46 by "java_re" with MS VC++ 6.0

  • JTable woes (JDK 1.5): Sorting and updating data

    So I've been working on this project for a while here that is essentially the front-end to a database system. The data itself is displayed in a JTable derivative. Column 1 is a JComboBox containing a list of companies, Column 2 is a JComboBox containing a list of employees, and the rest of the columns contain information specific to that employee.
    The data for each row is actually contained within a custom TableRowData object, which is used to assign listeners and such:
        private void initComponents() {
            this.organizations.setSelectedEnum(this.data.getOrganizationNumber());
            organizations.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        clearData();
                        try {                 
                            updateEmployees();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
            pocs.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {               
                    if("comboBoxChanged".equals(e.getActionCommand())) {
                        try {
                            data = getEmployeeInformation();
                            fireRowDataChanged();
                        } catch (SQLException ex) {
                            Logger.getLogger(VenosTeammateRow.class.getName()).log(Level.SEVERE, null, ex);
        }Ideally, I would like a change in Column 1 to load the employees for the selected company into Column 2. This is working as expected.
    I would also like a change in Column 2 to load the information specific to the selected employee into the rest of the columns. This is also working as expected.
    The problem I am having arises when the data is sorted and THEN a change is made to either column.
    To sort, I am using a custom comparator that keeps track of the sort direction and current sort column.
    In the JTable derivative class, I have a method, sortByColumn(int col):
    public void sortByColumn(int col) {
            this.getColumnModel().getColumn(col).getCellEditor().cancelCellEditing();
            if(this.getSelectedRow() > 0 && this.getSelectedRow() < this.getRowCount())
                this.removeRowSelectionInterval(this.getSelectedRow(), this.getSelectedRow());
            DefaultTableModel mdl = (DefaultTableModel)this.getModel();
            comp.setSortColumn(col);
            Collections.sort(mdl.getDataVector(), comp);
            // Declare and initialize the header
            JTableHeader header = this.getTableHeader();
            // Reset all headers to their identifier values
            for(int i = 0; i < mdl.getColumnCount(); i++) {
                String identifier = header.getColumnModel().getColumn(i).getIdentifier().toString();
                header.getColumnModel().getColumn(i).setHeaderValue(identifier);
            // Find the sort order (for the sorting indicator)
            int sortOrder = comp.getSortOrder(col);
            // Store the identifier text temporarily
            String headerText = header.getColumnModel().getColumn(col).getIdentifier().toString();
            // Declare and initialize the sort indicator based on the sort order
            String sortIndicator;
            switch(sortOrder) {
                case TableRowComparator.ASCENDING:
                    sortIndicator = "  \u2191";
                    break;
                case TableRowComparator.DECENDING:
                    sortIndicator = "  \u2193";
                    break;
                case TableRowComparator.UNSORTED:
                    sortIndicator = "";
                    break;
                default:
                    sortIndicator = "  \u2193";
                    break;
            /* Set the Header to display the text with the indicator. Since
             * this will automatically set the Identifier to the same value,
             * reset it to the value we stored previously.
            header.getColumnModel().getColumn(col).setHeaderValue(headerText+sortIndicator);
            header.getColumnModel().getColumn(col).setIdentifier(headerText);
            // Make sure all the changes are painted
            header.repaint();
            this.repaint();
        }After the sort, the rows are updated and displayed correctly. However, for example with three rows, if by sorting row 1 and row 3 swap, changing the JComboBox in row 3 also updates the data in row 1.
    I'll be converting my code into a short self-contained program momentarily to post on here for a better understanding of what's going on. However, I decided I would post this just in case there were something painfully obvious I missed.
    Thanks.

    Thanks, you've been really helpful :) However, I realized while trying to copy my code to a smaller, self-contained form to illustrate my problems... I never changed the row number in my TableDataRow! So of course the update information, which was relying on the row number stored in the TableDataRow object (and not the actual row number in the model's data vector) updated according to the old row numbers.
    Basically, I coded myself into a corner :P
    Fixed it by making a new comparator to compare TableDataRow objects, and I stored an array of those objects in my custom table model. So the hard work is done on the TableDataRow objects, the data vector is cleared, and then each TableDataRow is added back as a vector.
    Not sure if this is the most elegant solution, but... it works.
    Edited by: GranoblasticMan on Oct 21, 2008 1:11 PM

  • JTable problem in master detail form

    I've created a master detail form. There is only one Navigation bar for both master and detail. Detail has a JTable component. JTable doesn't get focus when it doesn't have any row and I am uanble to insert new rows. To cope with this problem I've added two new buttons in Navigation Bar to travers to the next and previous iterBinding.
    When I start my form cursor apperas in the first field of master view when I press Next Button nothing happens ( Status Bar should show the next iterbinding/view). I've addes some debug mesgs in iterBindingChanged method of NavitaionBar class and it seems by looking the mesgs that detail/Jtable's iterBinding get focus two times but at last focus has been returned to the master iterBinding.
    Is there any suggestion to solve this problem.
    Regards
    Aamir

    Hi,
    I'm using 1.4.0 for my JClient and, due to the improved focus management provided in the new JDK, I am able to properly manage master-details configuration with only one navigation bar (of course, the JTable must be able to receive the focus, but this also is much easier in 1.4.0...)
    Nevertheless, the solution I found is quite complex and I would happily discard it.
    If you could find a solution that works "naturally" on frames with only one navigation bar, it would be great! I think that the buttons in the nav bar should apply to the "current" iterator binding (the iterator binding for the control having the focus).
    Thanks,
    Adrian

  • JTable problem plz help me

    sir
    some one who is kind prson send link on rendering the table
    and how to use JTable but i am not sucessfull to draw image
    on the table.and set the background color of table column header and insert the icon on table header.
    plz guide me with sample of code
    i am very thankful to u.

    The examples at the link shown below were written over 5 years ago and have never been updated. Some examples will not compile using the latest JDK but they should give you a hint on what needs to be done:
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    ;o)
    V.V.

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • 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

  • JTable problem

    I'm writing an application that will display info in multiple tables. I thought it would be a good idea to write my own table class. The problem is that only the table data appears, but not the table headers.
    Layout.java creates an object of MyTable.java. The "createTable" constructor returns a JPanel wich in turn contains a JTable.
    Layout.java (creates the GUI, extends JFrame)
        String[] headers = {"1","2","3","4","5","6"};
        String[][] data = {{"one","two","three","four","five","six"},{"seven","eight","nine","ten","eleven","twelve"}};
        MyTable jt = new MyTable();
        Component table = jt.createTable(data, headers);
        JScrollPane jsp = new JScrollPane(table);
        getContentPane().add(jsp, BorderLayout.CENTER);
    MyTable.javapublic Component createTable(String[][] d, String[] h)
        data = d;
        headers = h;
        JPanel contentPane = new JPanel();
        TableModel tm = new AbstractTableModel(){
         public int getRowCount(){return data.length;}
         public int getColumnCount() {return headers.length;}
         public Object getValueAt(int r, int c) {return data[r][c];}
              public String getColumnName(int c) {return headers[c];}
        JTable jt = new JTable(tm);
        jt.setMaximumSize(new Dimension(700,40));
        jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        contentPane.add(jt);
        return contentPane;
    }

    The table headers are not really part of the table, they are a separate component.
    Normally a JTable is added directly to a JScrollPane. The JScrollPane is smart enough to take the column information create a component and add this component to the JScrollPane using the setColumnHeaderView() method of JScrollPane.
    In your example you are adding the JTable to a Component and then adding the Component to a JScrollPane so the headers don't get created.
    I suggest you add your table to the scrollpane in your createTable() method.

  • JTable problem - cannot edit the cells (only happens in Linux)

    I have a JFrame that contains a JScrollPane, and this JScrollPane contains a JTable, the code is:aPanel = new JScrollPane(myTable);The program is done, runs fine in PC & Unix, but when I run it in Linux the problem occurs. Somehow I just cannot type anything into the cells. There is a workaround, if I minimize and later restore the Frame, then I can start type the cells.
    I run out ideas what to do. Is this a bug in Java itself? Anybody has any idea why this happens or suggestions what I should do?
    Thanks,
    shyo

    Hi,
    This very well could be a bug in Java's focus system (by the way, what version are you using?). Another possibility is that this could be a threading issue. Can you try and see if this works? Re-write the main method of your application like this so that all GUI construction happens on the event dispatch thread:
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
    private createAndShowGUI() {
        // move construction of GUI and
        // pack(), setVisible(), etc. here.
    }Does that help?
    Shannon Hickey (Swing Team)

  • Jtable problem in changing the row selected

    hi,
    I am displaying the oracle database information in JTable...user can make changes to a row...once he presses either ENTER,UP OR DOWN ARROW...the changes should be updated into the database...if there is some SQL exception,i am displaying JOptionPane to show the exception message ...i need to keep the selected row to be the one with errors...
    my problems are:
    i have written a function to update the change to the database...
    when should i call that...right now i am calling that in tableChanged method... is there any method to dissable the predefined keys and actions? becaz once user makes changes to a row and presses some key like up/down or enter,the control is getting transfered to the next row...
    plz give me the solution...
    here is part of my code....
    I am adding data later....
         model= new DefaultTableModel((Vector)null,columnNames);
         table = new JTable(model)
         public void tableChanged(TableModelEvent e)
              int firstRow = e.getFirstRow();
         if (e.getType()==TableModelEvent.UPDATE &&(firstRow!=TableModelEvent.HEADER_ROW))
              updateChangesToDatabase(row);
    /********in my update method i am setting the focus to the same row
    if i get exception....like this....
    JOptionPane.showMessageDialog (thisPanel,sb,"Error in UPDATING...",JOptionPane.ERROR_MESSAGE);
    table.requestFocusInWindow();
    table.setRowSelectionInterval(currentRow,currentRow);
         super.tableChanged(e);
              setUpTableData(); // method to add data...to table..
              table.setDragEnabled(false);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              add(scrollPane,BorderLayout.CENTER);
    // this i am doing to reset keyboard action but not working....
              table.resetKeyboardActions();

    ye rammohan,
    you can change the data-element of the field or char of the data-element.
    if you try to change the name of the field, it deletes.
    so what you can do is, keep the field unchanged, add another field of your choice, using ABAP program, move the data from old field to new field, and then you can delete your old field.
    thx
    rams

  • Printing JTable problem

    hi
    i have a problem in printing jtable
    after printing the box around the table only printed and the content of the table isn't
    instead there is a wight space in the box
    can any one help me

    In fact the program i'm making is for printing preview
    it's three classes i found in one of the topics , then i modified them to preview a table
    here is my code : \\ the class "TPrintPreview" needs a JTable object as an argument
    ********************************TPrintPreview.java************************************************************
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.print.PageFormat;
    import java.awt.print.Paper;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import java.text.MessageFormat;
    import javax.swing.JTable;
    import javax.swing.JTable.PrintMode;
    * @author  TAREQ145
    public class TPrintPreview extends javax.swing.JFrame {
       int m_wPage;
       int m_hPage;
        /** Creates new form TPrintPreview */
        public TPrintPreview(JTable table) {
            initComponents();
            PageFormat m_pageFormat = PrinterJob.getPrinterJob().defaultPage();//use PageDialog
            m_wPage = (int)(m_pageFormat.getWidth());
            m_hPage = (int)(m_pageFormat.getHeight());
            int scale = getScale(5);  //Scale Index = 100
            jComboBox1.setSelectedIndex(5);
            int w = (int)(m_wPage*scale/100);
            int h = (int)(m_hPage*scale/100);   
            int pageIndex = 0;
            try{
            while (true) {
                int theFirstImageWidth = table.getColumnModel().getTotalColumnWidth()+1;
                BufferedImage img = new BufferedImage(theFirstImageWidth, theFirstImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g = img.getGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, theFirstImageWidth , theFirstImageWidth+180);//180 = height - width
                Paper p = new Paper();
                p.setImageableArea(0,0,theFirstImageWidth,theFirstImageWidth+180);
                m_pageFormat.setPaper(p);
                Printable  m_target = table.getPrintable(PrintMode.FIT_WIDTH,null,new MessageFormat("- {0} -"));
               if (m_target.print(g, m_pageFormat, pageIndex) != Printable.PAGE_EXISTS) {
                   img = null;
                   break;
                int rightOrLeftSpace = 25;
                int upOrDownSpace = 25;
                int theSecondImageWidth = theFirstImageWidth + (rightOrLeftSpace*2);
                BufferedImage img2 = new BufferedImage(theSecondImageWidth, theSecondImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g2 = img2.getGraphics();
                g2.setColor(Color.white);
                g2.fillRect(0, 0, theSecondImageWidth, theSecondImageWidth+180);
                g2.drawImage(img,rightOrLeftSpace,upOrDownSpace,null); 
                Image img3 = img2.getScaledInstance(m_wPage,m_hPage,Image.SCALE_SMOOTH);
                PagePreview pp = new PagePreview(w, h, img3);
                previewContainer1.add(pp);
                //pp = null;
                pageIndex++;
                img = null;
                g = null;
            } catch (PrinterException e)   {
              e.printStackTrace();
             System.err.println("Printing error: "+e.toString());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            previewContainer1 = new PreviewContainer();
            jButton1 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Print Preview");
            jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24));
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jLabel1.setText("Print Preview");
            jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            javax.swing.GroupLayout previewContainer1Layout = new javax.swing.GroupLayout(previewContainer1);
            previewContainer1.setLayout(previewContainer1Layout);
            previewContainer1Layout.setHorizontalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 752, Short.MAX_VALUE)
            previewContainer1Layout.setVerticalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 511, Short.MAX_VALUE)
            jScrollPane1.setViewportView(previewContainer1);
            jButton1.setText("EXIT");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %", "125 %", "150 %", "175 %", "200 %" }));
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 754, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(183, 183, 183)
                            .addComponent(jButton1)
                            .addGap(74, 74, 74))))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(40, 40, 40)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(80, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            this.dispose();
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int scale = getScale(jComboBox1.getSelectedIndex());
                      int w = (int)(m_wPage*scale/100);
                      int h = (int)(m_hPage*scale/100);
                      Component[] comps = previewContainer1.getComponents();
                      for (int k=0; k<comps.length; k++) {
                         if (!(comps[k] instanceof PagePreview)) continue;
                         PagePreview pp = (PagePreview)comps[k];
                         pp.setScaledSize(w, h);
                      previewContainer1.doLayout();
                      getContentPane().validate();
        private int getScale(int scaleIndex) {
          int scale = 10;
          String[] scales = { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %" , "125 %","150 %","175 %","200 %"};
          if (scaleIndex>-1 && scaleIndex<scales.length) {
             String str = scales[scaleIndex];
             if (str.endsWith("%"))str = str.substring(0, str.length()-1);
             str = str.trim();
             try { scale = Integer.parseInt(str); }
             catch (NumberFormatException ex) { ex.printStackTrace();}
          return scale;
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private PreviewContainer previewContainer1;
        // End of variables declaration                  
    ********************************PreviewContainer.java************************************************************
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PreviewContainer.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:20 &#1605;
    * @author  TAREQ145
    public class PreviewContainer extends JPanel {
        protected int H_GAP = 16;
        protected int V_GAP = 10;
        /** Creates new form BeanForm */
        public PreviewContainer() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
          public Dimension getPreferredSize() {
             int n = getComponentCount();
             if (n == 0) return new Dimension(H_GAP, V_GAP);
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width - H_GAP) / (dc.width + H_GAP), 1);
             int nRow = n / nCol;
             if ((nRow * nCol) < n) nRow++;
             int ww = nCol * (dc.width + H_GAP) + H_GAP;
             int hh = nRow * (dc.height + V_GAP) + V_GAP;
             Insets ins = getInsets();
             return new Dimension(ww+ins.left+ins.right, hh+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void doLayout() {
             Insets ins = getInsets();
             int x = ins.left + H_GAP;
             int y = ins.top + V_GAP;
             int n = getComponentCount();
             if (n == 0) return;
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             int w = dc.width;
             int h = dc.height;
    //fl+ 03.09.2003
             if (getParent() == null) return;
    //fl-        
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
             int nRow = n/nCol;
             if (nRow*nCol < n) nRow++;
             int index = 0;
             for (int k = 0; k<nRow; k++) {
                for (int m = 0; m<nCol; m++) {
                   if (index >= n) return;
                   comp = getComponent(index++);
                   comp.setBounds(x, y, w, h);
                   x += w+H_GAP;
                y += h+V_GAP;
                x = ins.left + H_GAP;
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    ******************************PagePreview.java***********************************************************************************
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PagePreview.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:25 &#1605;
    import javax.swing.border.MatteBorder;
    * @author  TAREQ145
    public class PagePreview extends JPanel {
         protected int m_w;
         protected int m_h;
         protected Image m_source;
         protected Image m_img;
        /** Creates new form BeanForm */
        public PagePreview() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
        public PagePreview(int w, int h, Image source) {
             m_w = w;
             m_h = h;
             m_source = source;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             m_img.flush();
             setBackground(Color.white);
             setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
          public void setScaledSize(int w, int h) {
             m_w = w;
             m_h = h;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             repaint();
          public Dimension getPreferredSize() {
             Insets ins = getInsets();
             return new Dimension(m_w+ins.left+ins.right,
                m_h+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void paint(Graphics g) {
             g.setColor(getBackground());
             g.fillRect(0, 0, getWidth(), getHeight());
             g.drawImage(m_img, 0, 0, this);
             paintBorder(g);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }please help me
    thankz

  • JTable problem : how to get the last value entered by user + event lost

    Hi all,
    I have 2 problems with Jtable class.
    1 => To get the last value entered by user in a cell,
    it seems that we must change the selected cell.
    That is to say we can only have the previous cell's value.
    Is there a simple way to get the current value of any cell ?
    2 => To resolve the problem i store the values of each cell in a vector and i intercept keyboard event (!)
    BUT, when i do a double click with the mouse on the Jtable, i loose keyboard events. Then, i can't intercept them.
    Is it a bug of swing or am i following a wrong way ?
    Thanks by anticipation for your help.

    You have to fire the "TableCellUpdatedEvent"
    and override the getCellEditorValue in TableCellEditor to return the current value

  • Need help .. JTable problem!!!!!

    Is there any way to provide drag n drop feature within Jtable cells ....
    What I want to do is that ... I shud be able to drag a JTable cell to another JTable cell and the values of those two cell should interchange ....
    Is this even possible ??? Please help me as I m new to Java
    Thanx alot....

    Plus I have one more problem the column headers arnt appearing ..... So please help me ..... I need two things to be done ....
    1) Populate the tables using vectors, so that only that no of rows appear which are in table of my database ..
    2) Column headers shud show up...
    Here's my code ...
    * Drag.java
    package test;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    public class Drag extends javax.swing.JFrame {
         private String url = "jdbc:odbc:FAMS";
        private Connection con;
        private Statement stmt;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        public void populate()
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
               String query = "SELECT * FROM SubAllot";
            /* First clear the JTable */
            clearTable();
            /* get a handle for the JTable */
            javax.swing.table.TableModel model = table.getModel();
            int r = 0;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) ) {
                        /* for each row get the fields
                           note the use of Object - necessary
                           to put the values into the JTable */
                       Object nm = rs.getObject(1);
                       Object sup = rs.getObject(2);
                       Object pri = rs.getObject(3);
                       Object sal = rs.getObject(4);
                       Object tot = rs.getObject(5);
                       model.setValueAt(nm, r, 0);
                       model.setValueAt(sup, r, 1);
                       model.setValueAt(pri, r, 2);
                       model.setValueAt(sal, r, 3);
                       model.setValueAt(tot, r, 4);
                       r++;
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           private void clearTable(){
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            for (int i=0; i < numRows; i++) {
                for (int j=0; j < numCols; j++) {
                    model.setValueAt(null, i, j);
              private void writeTable(){
             /* First clear the table */
             emptyTable();
             Statement insertRow;// = con.prepareStatement(
             String baseString = "INSERT INTO SubAllot " +
                                        "VALUES ('";
             String insertString;
            int numRows = table.getRowCount();
            javax.swing.table.TableModel model = table.getModel();
           /* Integer sup, sal, tot;
            Double pri;
            Object o;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                 for (int r=0; r < numRows; r++) {
                      if (model.getValueAt(r, 0) != null){
                           insertString = baseString + model.getValueAt(r, 0)+"','";
                           insertString = insertString + model.getValueAt(r, 1)+"','";
                           insertString = insertString + model.getValueAt(r, 2)+"','";
                           insertString = insertString + model.getValueAt(r, 3)+"','";
                           insertString = insertString + model.getValueAt(r, 4)+"');";
                           System.out.println(insertString);
                          insertRow = con.createStatement();
                           insertRow.executeUpdate(insertString);
                           System.out.println("Writing Row " + r);
                insertRow.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           // clearTable();
           private void emptyTable(){
             /* Define the SQL Query to get all data from the database table */
            String query = "DELETE * FROM SubAllot";
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query */
                   stmt.executeUpdate(query);
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
               abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    String val = (String) model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** Creates new form Drag */
    public Drag() {
    initComponents();
    populate();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
    Class[] types = new Class [] {
    java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
    public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(table);
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setRowHeight(23);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    table.setTableHeader(null);
    jButton1.setText("UPDATE");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(18, 18, 18)
    .addComponent(jButton1)
    .addContainerGap(15, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(80, 80, 80)
    .addComponent(jButton1)))
    .addContainerGap(14, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    writeTable(); // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Drag().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

Maybe you are looking for

  • How do I install Photo Elements on a mac that does not have a DVD/CD drive?

    How do I install Photo Elements on a mac that does not have a DVD/CD drive?

  • Safari not showing recent history

    The newest item showing in the history folder is from 9 days ago. Other programs (email) are also not filing sent and received items in chronological order. Some items are being buried as far as two years back. I have reset PRAM. It seems that the co

  • Authorizations for planning

    Hi, We are facing the following issue concerning authorizations for integrated planning. An employee 'X' should be authorized to change its own planning and display the planning of other employees. Furthermore the employee should see WBS elements 1 &

  • How to block popup windows that opens up on clicking a link?

    Hi, How to block pop-up windows that opens up when a link is clicked? The feature in IE is to set the Blocking level as 'High: Block all pop-ups (Ctrl + Alt to override)' in Pop-up Blocker settings. Is there a similar feature in Mac? Thanks & appreci

  • General Error message when rendering after opening FCP4 project in FCP5

    Hi, we're are having trouble with our FCP 4.5 project after opeining it in FCP5. When trying to render it comes up with "General Error" message and won't render the sequence. It also sometimes simply stops rendering without the message. Can anyone he