Help! Multi-Thread in Java Swing!

Hi,
I have a java swing application. The basic logic for the application is, I will input some data and click the "Process" Button.
The application will perform some operation. Currently I can perform one operation at a time.
I have to extend the scope of this application to multiple process at the same time.
like, I will add a table in the application. Whenever I give input and press the "Process" button, the process should be added in the table at the same time I should be able to input and initiate the next operation.
I am not very much experienced in java swing.
Is it possible to do in swing? Can somebody give me some input on this?
Thanks,
Raja.

Check out SwingWorker http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

Similar Messages

  • The problem about multi-thread in java application

    i have problem with the multi-thread in java application, i don't know how to stop and restart a thread safely, because the function thread.stop(),thread.suspend() are both deprecated.
    now what i can only do is making the thread check a flag(true or false) to determine whether to start or to stop, but i think this thread will always be in the memory and maybe it will lower the performance of the system, as the program i am developping is working under realtime enviorement.
    please help me about it. thanks !

    hi,
    you can stop a thread by exiting it's run()-method which in terms can be done by checking the interrupted-flag:
    public void run(){
    while(interrupted()){ //if the thread consists of a loop
    or
    public void run(){
    if(interrupted())return;
    if(interrupted())return;
    or by the use of the return-statement anywhere withing the run-method. Afterwards, that is when the thread is no longer needed, you clear all the references to the specific thread object by setting them to null:
    Thread t;
    ... //working
    t.interrupt(); //interrupting
    while(t.isAlive()){
    Thread.yield(); //wait till thread t has stopped
    t=null;
    best regards, Michael

  • Help on Threads in Java

    I need some basic help in regards to threading in Java.
    I have no history of writing threaded applications in any programming language.
    I'm working on a kind of web bot, for a bunch of XML sources. There are 10's of thousands of sources and the timestamp difference between the lastest and last updated item is growing to almost a full day! This is not good enough really.
    Here's the basic layout of the main class:
    public class filer {
        private static class bot implements Runnable {
            private mysql db;
            private int botID;
            public bot(final int ID) {
                botID = ID;
                try {
                    // Some prepared statements here...
                catch (SQLException ex) {System.exit(0);}
                catch (NoSuchAlgorithmException ex) {System.exit(0);}
            public void run() {
                db = new mysql("localhost", "xxx", "xxx", "xxx");
                if (db.connected == true) spider();
                else System.exit(0);
            final void spider() {
                // Spider logic here using botID...
                spider(); // Recursion...
        public static void main(String[] args) {
            for (int i = 0; i < 51; i++) (new Thread(new bot(i))).start();
    }I'm trying to run 50 threads, each doing their task of downloading data, parsing it and inserting where applicable into the MySQL database. 50 should reduce difference in last and latest crawled to 1 hour, which would be great!
    Am I missing something? Is there anything special that needs to be taken into consideration when using MySQL?
    Any help much appreciated!

    Wow, that's a bummer :-(
    I managed to get this working, showing 50 simultaneous connections to MySQL, but the connections appear to be "sleeping" most of the time which leads me to believe it's the problem you're suggesting.
    Thanks for the heads up, could save me a lot of headaches!

  • Help with Threads in java...

    Hi all,
    the problem it's the following:
    i got a program that update a sql server table. So i want, at the same time, run this program many times, say 10 for example, to do it that faster.
    But i only want 10 subprograms at the same time. So i got to use wait() and others method's, rigth?
    I'm not shure about this, because a never use threads.
    So any help, code or "pseudocode" will be very appreciated.
    Thanks in advance
    A. Santos

    Hi santhos,
    If u use 10 threads to read the sql table, then
    ur program will lose the sequence. If u have a idea
    to split the program then u can use threads.
    Regards,
    Palaniyappan

  • Help regarding JTable in Java Swing

    hi,
    i m confused regarding JTable in Swing. i hav added a JTextField in a cell of a JTable. i hav attached a kay listener with that textfield . But when i m selecting that cell ,where i hav added that textfield with a single click and typeing any key i m not getting that keyevent. But when i m selecting the same with a doulbe click and typing any thing i m getting that event .
    can any one tell me why the discrepency taking place. that textfield is
    there in that cell .then how it does make any difference with a single and double click.
    regards

    i hav added a JTextField in a cell of a JTableYou don't add a text field to a cell in a table. You add a text String to the TableModel. When the user double clicks on the cell an 'editor' is invoked and the text is copied to the editor (which by default is a JTextField). So the KeyStrokes go to the editor text field.
    When you just single click on a cell the table still has focus, not the editor, to the KeyStroke character is passed directly to the text field without the text field actually getting focus.

  • Java Swing frame for modification Excel file or Word file with All menu...

    Hello All,
    Can Any one help me for making java Swing frame for modification Excel Data or word file with all Menu.. Plz send me java Code for that.. I am bit new in Swing.
    i am waiting for ur help..
    Thanks
    Samir

    hi pbrockway2 ,
    Can you go through this program Sir, i am trying to call Excel content below of menu. when i will press Edit button then excel content should come below with Cut, copy, paste , Save Button..
    Plz help me sir...
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    public class TestReader
    private static void createAndShowUI()
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame=new JFrame("Test Reader");
    JButton button=new JButton("Edit");
    button.addActionListener(new ButtonListener());
    frame.getContentPane().add(button);
    frame.setVisible(true);
    frame.pack();
    static class ButtonListener implements ActionListener
    public void actionPerformed(ActionEvent event)
    openTheFile();
    private static void openTheFile()
    try
    String commands[]=new String[3];
    commands[0]="cmd.exe";
    commands[1]="/C";
    commands[2]="INSTALL.LOG"; // here file name is supposed to be in the working dir
    Runtime rt=Runtime.getRuntime();
    Process proc=rt.exec(commands);
    StreamGobbler errorGobbler=new StreamGobbler(proc.getErrorStream(),"ERROR");
    StreamGobbler outputGobbler=new StreamGobbler(proc.getInputStream(),"OUTPUT");
    errorGobbler.start();
    outputGobbler.start();
    catch (Exception e){}
    public static void main(String args[])
    SwingUtilities.invokeLater(new Runnable()
         public void run()
         createAndShowUI();
    static class StreamGobbler extends Thread
    InputStream is;
    String type,root;
    StreamGobbler(InputStream is,String type)
    this.is=is;
    this.type=type;
    public void run()
    try
    InputStreamReader isr=new InputStreamReader(is);
         BufferedReader breader=new BufferedReader(isr);
         String line=null;
         while ((line=breader.readLine())!=null)
         System.out.println(type+">"+line);
    catch (Exception e)
         System.out.println(e);
    Thanks
    SamiR

  • How should implement multi-thread in single-threaded Operating system using

    How should implement multi-thread in single-threaded Operating system using java?
    Java supports "Multi-threading".Is there is any way run the multiple threads (Implementing multi threading) using java in a Single-threaded Operating system (That is the operating system does not support for multi-threading).

    Previous questions from OP suggest they are using J2ME, so the question might be possible.
    806437 wrote:
    How should implement multi-thread in single-threaded Operating system using java?
    What is the actual question/problem?
    A java app doesn't do threads or not do threads. It uses classes. The VM does threads.
    So if you have a platform that does not have threads and you want to support the thread class then the VM, not a java app, must provide some pseudo mechanism, such as green threads, to support that.
    If your question is about java code and not the VM then you must build a task engine and insure that the tasks are of short enough duration that it is an effective use for your system.

  • Java multi-thread Applet and Multi-processor

    Hello,
    I have a JAVA applet which work fine on a mono-processeur machine and not fine at all on multi-processors.
    It use multi thread (for reading on socket) and some times, request are lost.
    Is that a matter of programming or a JVM bug ?
    This happens on Linux and Windows NT bi-processors.
    We hare using JAVA 1.3.0_02
    Thanks for your help
    [email protected]

    I have already have a look to javax.swing.SwingUtilities.invokeLater() but (I think) it don't work for my need.
    A graphic applet which create 2 threads : one for reading and one for writing on a socket.
    Request sent to the server are memorized in a vector, and once answer is received, the request is remove from vector and treated. Access to the list is protected by synchronize.
    Everything works fine one several plateforme (linux, windows 98/2000/NT, Solaris). The only problem is on multi-processor : request are lost !

  • Chess: java swing help need

    Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.
    Any suggestion would be very helpful. Thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
    Object currentPosition;
    Color currentColor;
    Dimension boardSize = new Dimension(600, 600);
    JLayeredPane layeredPane;
    JPanel board;
    JPanel box;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;
    public ChessBoard()
    // Use a Layered Pane for this this application
    layeredPane = new JLayeredPane();
    getContentPane().add(layeredPane);
    layeredPane.setPreferredSize( boardSize );
         layeredPane.addMouseListener( this );
    layeredPane.addMouseMotionListener( this );
    // Add a chess board to the Layered Pane
    board = new JPanel();
         // set "board" to the lowest layer (default_layer)
    layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
    board.setLayout( new GridLayout(8, 8) );
    board.setPreferredSize( boardSize );
    board.setBounds(0, 0, boardSize.width, boardSize.height);
         addShade();
         addPiece();
    public void addShade()
         for (int i = 0; i < 64; i++)
    box = new JPanel( new BorderLayout() );
    board.add( box, BorderLayout.CENTER );
         if( ((i / 8) % 2) == 0)
                   if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                   } else {
                        box.setBackground( Color.white);
              } else {
                   if( (i % 2) ==0)
                        box.setBackground(Color.white);
                   } else {
                        box.setBackground(Color.lightGray);
    //Method for adding chess pieces to the board
    public void addPiece()
    // Add a few pieces to the board
         //black pieces
         for (int i = 0; i < 64; i++)
              //adding black pieces
              if (i < 8)
                   String fileName = i + ".gif";
                   JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPieces );
              //adding black pones
              if ((i > 7) && (i < 16))
                   String fileName = "8.gif";
                   JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPones );
              //jump to white position (Component 48)
              if (i == 16) i = 48;
              //adding white pones
              if(( i > 47 ) && (i < 56))
                   JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( whitePones );
              //adding white pieces
              if (i > 55)
                   String fileName = i + ".gif";
                   JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i);
                   panel.add( whitePieces );
    ** Add the selected chess piece to the dragging layer so it can be moved
    public void mousePressed(MouseEvent e)
    chessPiece = null;
    Component c = board.findComponentAt(e.getX(), e.getY());
         c.setBackground(Color.red);
    if (c instanceof JPanel) return;
    Point parentLocation = c.getParent().getLocation();
    xAdjustment = parentLocation.x - e.getX();
    yAdjustment = parentLocation.y - e.getY();
    chessPiece = (JLabel)c;
    chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
    chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
    layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
    ** Move the chess piece around
    public void mouseDragged(MouseEvent me)
    if (chessPiece == null) return;
    chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
    ** Drop the chess piece back onto the chess board
    public void mouseReleased(MouseEvent e)
         Component c = board.findComponentAt(e.getX(), e.getY());
         int x = (int)c.getBounds().getX();
         int y = (int)c.getBounds().getY();
         System.out.println(c.getLocation());
         System.out.println(x + " "+ y);
         c.setBackground(currentColor);
    if (chessPiece == null) return;
    chessPiece.setVisible(false);
    if (c instanceof JLabel)
    Container parent = c.getParent();
         //remove the piece that is capture
    parent.remove(0);
    parent.add( chessPiece );
    else
    Container parent = (Container)c;
    parent.add( chessPiece );
    chessPiece.setVisible(true);
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    private static void createAndShowGUI()
         //Make sure we have nice window decorations
         JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new ChessBoard();
         frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
         //Display the window
         frame.pack();
         frame.setResizable( false );
         frame.setLocationRelativeTo( null );
         frame.setVisible(true);
    public static void main(String[] args)
         //Schedule a job for the event-dispatching thread:
         //creating and showing this application's GUI
         javax.swing.SwingUtilities.invokeLater( new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoardRx extends JFrame implements MouseListener, MouseMotionListener
        Object currentPosition;
        Color currentColor;
        Dimension boardSize = new Dimension(600, 600);
        JLayeredPane layeredPane;
        JPanel board;
        JPanel box;
        JLabel chessPiece;
        int xAdjustment;
        int yAdjustment;
        Container lastParent;
        public ChessBoardRx()
            // Use a Layered Pane for this this application
            layeredPane = new JLayeredPane();
            getContentPane().add(layeredPane);
            layeredPane.setPreferredSize( boardSize );
            layeredPane.addMouseListener( this );
            layeredPane.addMouseMotionListener( this );
            // Add a chess board to the Layered Pane
            board = new JPanel();
            // set "board" to the lowest layer (default_layer)
            layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
            board.setLayout( new GridLayout(8, 8) );
            board.setPreferredSize( boardSize );
            board.setBounds(0, 0, boardSize.width, boardSize.height);
            addShade();
            addPiece();
    //        populateBoard();
        public void addShade()
            for (int i = 0; i < 64; i++)
                box = new JPanel( new BorderLayout() );
                board.add( box, BorderLayout.CENTER );
                if( ((i / 8) % 2) == 0)
                    if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                    } else {
                        box.setBackground( Color.white);
                } else {
                    if( (i % 2) ==0)
                        box.setBackground(Color.white);
                    } else {
                        box.setBackground(Color.lightGray);
        //Method for adding chess pieces to the board
        public void addPiece()
            // Add a few pieces to the board
            //black pieces
            for (int i = 0; i < 64; i++)
                //adding black pieces
                if (i < 8)
                    String fileName = i + ".gif";
                    JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPieces );
                //adding black pones
                if ((i > 7) && (i < 16))
                    String fileName = "8.gif";
                    JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPones );
                //jump to white position (Component 48)
                if (i == 16) i = 48;
                //adding white pones
                if(( i > 47 ) && (i < 56))
                    JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( whitePones );
                //adding white pieces
                if (i > 55)
                    String fileName = i + ".gif";
                    JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i);
                    panel.add( whitePieces );
        private void populateBoard() {
            int[][] pos = {
                { 9, 7, 5, 1, 3, 5, 7, 9 },
                { 8, 6, 4, 0, 2, 4, 6, 8 }
            for(int j = 0; j < 8; j++) {
                String fileName = "chessImages/" + pos[0][j] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 8; j < 16; j++) {
                String fileName = "chessImages/" + 11 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 56, k = 0; j < 64; j++, k++) {
                String fileName = "chessImages/" + pos[1][k] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 48; j < 56; j++) {
                String fileName = "chessImages/" + 10 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
         ** Add the selected chess piece to the dragging layer so it can be moved
        public void mousePressed(MouseEvent e)
            chessPiece = null;
            Component c = board.findComponentAt(e.getX(), e.getY());
            c.setBackground(Color.red);
            if (c instanceof JPanel) return;
            lastParent = c.getParent();
            Point parentLocation = c.getParent().getLocation();
            xAdjustment = parentLocation.x - e.getX();
            yAdjustment = parentLocation.y - e.getY();
            chessPiece = (JLabel)c;
            chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
            chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
            layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
         ** Move the chess piece around
        public void mouseDragged(MouseEvent me)
            if (chessPiece == null) return;
            chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
         ** Drop the chess piece back onto the chess board
        public void mouseReleased(MouseEvent e)
            Component c = board.findComponentAt(e.getX(), e.getY());
            if(c == null) {
                layeredPane.remove(chessPiece);
                lastParent.add(chessPiece);
                Rectangle r = lastParent.getBounds();
                chessPiece.setLocation(r.x+xAdjustment, r.y+yAdjustment);
                lastParent.validate();
                lastParent.repaint();
                return;
            int x = (int)c.getBounds().getX();
            int y = (int)c.getBounds().getY();
            System.out.println(c.getLocation());
            System.out.println(x + " "+ y);
            c.setBackground(currentColor);
            if (chessPiece == null) return;
            chessPiece.setVisible(false);
            if (c instanceof JLabel)
                Container parent = c.getParent();
                //remove the piece that is capture
                parent.remove(0);
                parent.add( chessPiece );
            else
                Container parent = (Container)c;
                parent.add( chessPiece );
            chessPiece.setVisible(true);
        public void mouseClicked(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        private static void createAndShowGUI()
            //Make sure we have nice window decorations
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new ChessBoardRx();
            frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            //Display the window
            frame.pack();
            frame.setResizable( false );
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI
            javax.swing.SwingUtilities.invokeLater( new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Java Security Manager in Multi-threaded application

    I am writing a multi-threaded application listening (TCP and UDP) to several ports. To help implement certain security features (eg. refusing connections from certain ip address), I'm using the java.lang.SecurityManager (by subclassing it). I am having a few problems and queries and am hoping someone here can help me.
    1. As all the threads are calling the checkAccept(host, port) method. Is there a way to know which thread is currently accessing the security manager? For example if host A were to make 2 connections to the application, one to thread 1 (say listening to port 5001) and the other to to thread 2 (say listening to port 5002). I intend to refuse the connection to thread 2 but there is not way of differentiating the 2 connections since they are from the same host and there isnt any way of knowing their port number.
    2. Are calls to the Security Manager thread safe?
    I have been having this problem for a long time, would appreciate if someone can help point me to the right direction. cheers.

    1. As all the threads are calling the
    checkAccept(host, port) method. Is there a way to
    know which thread is currently accessing the security
    manager?Just use Thread.currentThread(). As specified in the Javadoc for e.g. SecurityManager.checkAccept().
    2. Are calls to the Security Manager thread safe? No.

  • Cannot get bitmap from native DLL from multi threaded Java app.

    I have a native DLL that gives me a HBITMAP (Windows handle to bitmap). I have made a JNI wrapper for this that gives me a BufferedImage back. The native code simple gets the actual bitmap for the handle, converts the RGB byte triplets to RGB ints, puts this in a jintArray and creates a BufferedImage.
    This all works fine within a single Java thread. If I do this multi threaded (thread 1 calls the native function and several seconds later, thread 2 calls the native function) I keep getting the last image of the first thread. Can enyone help me out?
    I know that this is probably a question for MSDN but I just know that they will tell me its a JNI question.
    The native code:
    JNIEXPORT jobject JNICALL Java_somenamespace_getPicture
    (JNIEnv *env, jclass cl, jstring serialNumber)
    jobject jImage;
    jclass jImageClass;
    jmethodID jMethod;
    jfieldID jField;
    jintArray rgbArray;
    char *str;
    char *charArray;
    int *intArray;
    int w, h, index, type;
    HBITMAP hbmp;
    BITMAP bmp;
    str = (char*)((*env)->GetStringUTFChars(env, serialNumber, NULL));
    // Gets the HBITMAP handle from the native DLL. The first argument is to select the device, based on serial number.
    getPicture(str, &hbmp);
    (*env)->ReleaseStringUTFChars(env, serialNumber, str);
    // Get the BITMAP for the HBITMAP
    GetObject(hbmp, sizeof(BITMAP), &bmp);
    // Create my BufferedImage
    jImageClass = (*env)->FindClass(env, "java/awt/image/BufferedImage");
    jMethod = (*env)->GetMethodID(env, jImageClass, "<init>", "(III)V");
    jField = (*env)->GetStaticFieldID(env, jImageClass, "TYPE_INT_RGB", "I");
    type = (*env)->GetStaticIntField(env, jImageClass, jField);
    jImage = (*env)->NewObject(env, jImageClass, jMethod, bmp.bmWidth, bmp.bmHeight, type);
    // Get the RGB byte triplets of the BITMAP
    charArray = (char *)malloc(sizeof(char) * bmp.bmHeight * bmp.bmWidth * 3);
    GetBitmapBits(hbmp, sizeof(char) * bmp.bmHeight * bmp.bmWidth * 3, charArray);
    // Allocate space to store the RGB ints and convert the RGB byte triplets to RGB ints
    intArray = (int *)malloc(sizeof(int) * bmp.bmHeight * bmp.bmWidth);
    index = 0;
    for (h = 0; h < bmp.bmHeight; ++h)
    for (w = 0; w < bmp.bmWidth; ++w)
    int b = *(charArray + index * 3) & 0xFF;
    int g = *(charArray + index * 3 + 1) & 0xFF;
    int r = *(charArray + index * 3 + 2) & 0xFF;
    *(intArray + index) = 0xFF000000 | (r << 16) | (g << 8) | b;
    ++index;
    // Create a jintArray for the C RGB ints
    rgbArray = (*env)->NewIntArray(env, bmp.bmHeight * bmp.bmWidth);
    (*env)->SetIntArrayRegion(env, rgbArray, 0, bmp.bmHeight * bmp.bmWidth, (jint*)intArray);
    // Use BufferedImage.setRGB() to fill the image
    jMethod = (*env)->GetMethodID(env, jImageClass, "setRGB", "(IIII[III)V");
    (*env)->CallVoidMethod(env, jImage, jMethod,
    0, // int startX
    0, // int startY
    bmp.bmWidth, // int width
    bmp.bmHeight, // int height
    rgbArray, // int[] rgbArray
    0, // int offset
    bmp.bmWidth); // int scansize
    // Free stuff
    (*env)->DeleteLocalRef(env, rgbArray);
    free(charArray);
    free(intArray);
    return jImage;
    }I already tried working with native HDCs (GetDC, CreateCompatibleBitmap, SelectObject, GetDIBits, ...) but this just complicates stuff and gives me the same result.

    Have you verified what the "native DLL" gives you back on the second call?The HBITMAP handle returned is the same each call (no matter which thread). The actual BITMAP associated with this handle is only updated in the first thread.
    How are you determining that the image is the same?If I point the camera (I don't get a stream, I just get individual images) to a moving scene, I get different images for each call from within the first thread. The second thread only gets the latest image from the first thread. There is no concurrency of the threads and all methods are synchronized.
    Specifically did you verify that the problem is not that your test code itself is using the same instance?Yes, I tested the native side as well as the Java side. The BufferedImage is always an exact copy of the native BITMAP.
    Try printing out the hash for each instance.I have written the image to a file in the native code itself to eliminate anything related to the mechanism of returning the BufferedImage. This had the same result.
    The return values of all native calls all indicate successful calls.
    I am suspecting the native side of creating a second graphical context for the second thread while it keeps refering to the first context.
    (I will start a thread on the MSDN as well and will post here if anything turns up.)

  • HELP Needed with this error:   Exception in thread "main" java.lang.NoClass

    Folks,
    I am having a problem connecting to my MSDE SQL 2000 DB on a WindowsXP pro. environment. I am learning Java and writing a small test prgm to connect the the database. The code compiles ok, but when I try to execute it i keep getting this error:
    "Exception in thread "main" java.lang.NoClassDefFoundError: Test1"
    I am using the Microsoft jdbc driver and my CLASSPATH is setup correctly, I've also noticed that several people have complained about this error, but have not seen any solutions....can someone help ?
    Here is the one of the test programs that I am using:
    import java.sql.*;
    * Microsoft SQL Server JDBC test program
    public class Test1 {
    public Test1() throws Exception {
    // Get connection
    DriverManager.registerDriver(new
    com.microsoft.jdbc.sqlserver.SQLServerDriver());
    Connection connection = DriverManager.getConnection(
    "jdbc:microsoft:sqlserver://LAPTOP01:1433","sa","sqladmin");
    if (connection != null) {
    System.out.println();
    System.out.println("Successfully connected");
    System.out.println();
    // Meta data
    DatabaseMetaData meta = connection.getMetaData();
    System.out.println("\nDriver Information");
    System.out.println("Driver Name: "
    + meta.getDriverName());
    System.out.println("Driver Version: "
    + meta.getDriverVersion());
    System.out.println("\nDatabase Information ");
    System.out.println("Database Name: "
    + meta.getDatabaseProductName());
    System.out.println("Database Version: "+
    meta.getDatabaseProductVersion());
    } // Test
    public static void main (String args[]) throws Exception {
    Test1 test = new Test1();

    I want to say that there was nothing wrong
    with my classpath config., I am still not sure why
    that didn't work, there is what I did to resolved
    this issue.You can say that all you like but if you are getting NoClassDefFound errors, that's because the class associated with the error is not in your classpath.
    (For future reference: you will find it easier to solve problems if you assume that the problem is your fault, instead of trying to blame something else. It almost always is your fault -- at least that's been my experience.)
    1. I had to set my DB connection protocol to TCP/IP
    (this was not the default), this was done by running
    the
    file "svrnetcn.exe" and then in the SQL Server Network
    Utility window, enable TCP/IP and set the port to
    1433.Irrelevant to the classpath problem.
    2. I then copied all three of the Microsoft JDBC
    driver files to the ..\jre\lib\ext dir of my jdk
    installed dir.The classpath always includes all jar files in this directory. That's why doing that fixed your problem. My bet is that you didn't have the jar file containing the driver in your classpath before, you just had the directory containing that jar file.
    3. Updated my OS path to located these files
    and....BINGO! (that simple)Unnecessary for solving classpath problems.
    4. Took a crash course on JDBC & basic Java and now I
    have created my database, all tables, scripts,
    stored procedures and can read/write and do all kinds
    of neat stuff.All's well that ends well. After a few months you'll wonder what all the fuss was about.

  • Running a Java Multi Thread Program in database

    I have created a multi threaded program in Java and it runs successfully from the command prompt. I want to create a DBMS Job which will wake up at regular intervals and runs the java program(Java stored procedure). Is this possible in 9.2/10G ?? If Yes, will there be any impact on the DB performance/increase memory etc.,
    The database (9.2...) resides on a RH 2.3 AS box.
    Any ideas...
    Thanks,
    Purush

    Purush,
    Java stored procedures cannot be multi-threaded. Well, they can, but the threads will not run in parallel. You may be able to find some more information in the Oracle documentation, which is available from:
    http://tahiti.oracle.com
    Good Luck,
    Avi.

  • Help with java swing

    Hi people!i need some help
    Im a new user for java programming language.Well im programming an application using java swing libraries. I have some problems trying to accesing variables from those swing Jpanels. Ill make it clear....
    Im using Netbeans...
    I have a class for the window (a JFrame) including 2 Jtextfields and 2 Jlabels
    import .......
    public class myclass extends javax.swing.JFrame{
    public double gp;
    public double gv;
    public G() {
    initComponents();
    gpnom=this.gpnom;
    gvnom=this.gvnom;
    private void TXFgpnom(java.awt.event.ActionEvent evt) {        //TXField                                
    gpnom= Double.parseDouble(TXFgpnom.getText());
    gvnom= Double.parseDouble(TXFgvnom.getText());
    .......//theres a lot of more code .for listeners..next...
    Now ive created a new file (a new class)in the same package ,but i cant access public variables from swing class
    //the next class was created in a new file
    public class hi () {
    JPanel prin =(JPanel) new myclass().getContentPane(); //ok
    double number=gpnom // error variable not found
    When i try to get the value of "number" ...i always get "ERROR" And the class for that textfield was public..i think...
    HOw can i use variables from that Jpanel?
    Id appreciate an answer...
    thanx for your help!
    Paco

    In future Swing related questions should be posted in the Swing forum and camickr will be more likely to answer if you have used code tags to properly format your code.
    Luckily this problem does not seem to be Swing related in the least because the public variables you have in your other class are named gp and gv and further when you access public variables (or properties) of a class you must access them by an instance of that class. Which you don't appear to be doing either.

  • Exception in thread "main" java.lang.OutOfMemoryError(please help me )

    Hi All
    here my java class trying to read a txt file(which is having size of 60MB).and putting each line into a Vector class. problem is ,upto certain number of line it is reading properly and putting into vector..after that it is giving error like Exception in thread "main" java.lang.OutOfMemoryError..what is the problem and how to rectify this one..anybody help me on this.
    actual situation is one txt is there in that 80 lakhs of lines of content is there..java file trying to read each line and put it into vector or stringbuffer and split it into two lines like key=value and put it into hashmap object.then finally iam creating new file(.properties) and writing these hashmap data on it. if you want clearly..please look into below code..
    package test.utf8; import java.io.*; import java.util.*; public class AssetUtils
    //static StringBuffer stringbuffer = new StringBuffer();
    public AssetUtils()
    public static void main(String args[]) throws IOException
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\list.txt")));
    Vector vector = new Vector(0x30D40, 50000);
    System.out.println(vector.capacity());
    Object obj = null;
    int n=0;
    System.out.println("Reading list:" + new Date(System.currentTimeMillis()));
    do
    String s = bufferedreader.readLine();
    //System.out.println("line no: "+ ++n);
    if(s == null)
    break;
    vector.add(s);
    } while(true);
    System.out.println("List Read complete:" + new Date(System.currentTimeMillis()));
    String s1 = args[0];
    System.out.println("S1: "+s1);
    System.out.println(vector.capacity());
    HashMap hashmap = new HashMap();
    System.out.println( "Vector.Size..>>>>>>>>>>>>>>>>.."+vector.size());
    for(int i = 0; i < vector.size(); i++)
    System.out.println("i value:"+i);
    String s2 = (String)vector.get(i);
    //System.out.println("S2: "+s2);
    if(s2.indexOf("/") != -1)
    String s3 = s2.substring(s1.length(), s2.length());
    //System.out.println("S3: "+s3);
    if(s3.indexOf("/") != -1) {
    String s4 = s3.substring(0, s3.lastIndexOf("/"));
    //System.out.println("S4: "+s4);
    String s6 = s3.substring(s3.lastIndexOf("/") + 1, s3.length());
    //System.out.println("S6: "+s6);
    StringBuffer stringbuffer=null;
    stringbuffer = new StringBuffer();
    String s8 = (String)hashmap.get(s4);
    //System.out.println("S8: "+s8);
    if(s8 != null) stringbuffer.append(s8 + "," + s6);
    else
    stringbuffer.append(s6);
    hashmap.put(s4, stringbuffer.toString());
    //stringbuffer.delete(0,stringbuffer.length());
    stringbuffer=null;
    System.out.println("Opening asset.properties:" + new Date(System.currentTimeMillis()));
    File file = new File("D:\\asset.properties");
    PrintWriter printwriter = new PrintWriter(new FileOutputStream(file));
    String s5;
    String s7;
    for(Iterator iterator = hashmap.keySet().iterator(); iterator.hasNext(); printwriter.println(s5 + "=" + s7))
    { s5 = (String)iterator.next(); s7 = (String)hashmap.get(s5); } printwriter.close();
    System.out.println("Closing asset.properties:" + new Date(System.currentTimeMillis()));

    Theres a number of ways you can improve your memory usage:
    1) Build you map as you read in your file.
    2) Use StringBuffers in your map - do not use "asshaj" + "ashaskj" This is very memory intensive
    If you still run out of memory try running the JVM using -Xms128m -Xmx512m or higher

Maybe you are looking for

  • When trying to print to pdf the program I am printing from locks up

    I'm using Acrobat 11.0.07 on a Windows PC with Win 8.1 I'm printing to pdf from QuickBooks. My first attempt works fine then the second locks up both programs. If I force close QuickBooks; run a repair on Adobe; reboot my computer; I am then able to

  • 10G Reports download in 11g

    Hello All I downloaded the sample reports for OIM in BI Publisher 10G but I want to use 11g based on better security capabilities. I was wondering if there is a way to import the 10g reports from the download into 11g? I found a couple documents on t

  • Printing to a Windows XP printer

    My roommate has his printer, HP psc 1315, hooked up to his Windows XP machine. He has it shared, as my other roommate with a Windows XP machine can print to it. I am trying to print to this computer using my Macbook Pro, but when I print something, i

  • Importing two sets of pictures into same collection

    Hi, I have two sets of pictures on 2 different CF cards and would like to import them into the same collection because they belong together. I already imported one set of photos from one CF card into the appropriate collection name. Since there doesn

  • Font is fuzzy not sharp lost crispness

    the font on my computer has just gotten fuzzy. its lost its crispness, isn't sharp and is in all areas. how should I fix this?