Threads updating Swing

Hi. I noticed that when trying to add text to a textbox:
myJTextArea.append("abc");From a Thread:
loop 100 times{call append()
}>
My application hangs.
But when I add an sleep:
loop 100 times{call append()
Thread.Sleep(10);
}>
It all works fine. Is this correct behavior?
If it is: can I speed up without Sleep? (synchronize?)

Might be you are creating some sort of deadlock. You might want to check out this recent thread to learn how to properly deal with Swing and threads:
Event Dispatching Thread
or read the appropriate chapter of the tutorial of course:
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

Similar Messages

  • Updating Swing components from a different class

    I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
    I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
    Many Thanks in advance Sean

    Hi
    Why don't you just implement a basic callback method?
    To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
    This might sound very complex, but it's really simple once you've done it once.

  • View count AND thread update bug?

    It's the end of the year, so that might be the reason of this oddity, but here is my problem:
    I just posted a comment to this thread and returned to my profile page to just realize that somebody had already posted a comment. I went back to the thread and did not find anyhting new, so I went back to my profile...just to discover that a new post had just been added to the thread (and the view count had been incremented).
    Long story made short, at each iteration of this procedure, the view count goes up by 1 and the thread keep appearing as updated, when it is not. I tried that on Chrome and IE8, same thing.
    The interesting thing is that this does not happen for another thread (I just posted in this one too and repeated the above sequence and did not see the thread update bug happen, however, the view count increases each time I go back to the thread).
    To me the thread activity being stuck IS a bug. The view count being incremented each time the original poster displays the thread is debatable. I guess strictly speaking it is the correct behavior and what would be an intersting additional information would be the number of VIEWERS...

    Hmm, I think I understood what is happening: for some reason, I must have failed to read ALL the posts in those threads (very likely in the case of the first one I mentioned, as it is 10 pages long, but I was under the impression I had followed the second one quite closely). I can only see that if I click on the "View All" link at the bottom of the panel showing my recent posts:
    Then the list that shows up indicates the number of NEW posts. This is a misnomer in the sense that generally those posts can be be anterior to the one you posted, so there are not "new" rather just "unread". I may be mistaken, but in the case of the second thread I mentioned, I think that what I may have not checked out AGAIN is the response that was labeled as "answer" by the original poster (but I thought I did though). It is only when I went through all pages (without reading anything, of course) that the thread lost its "highlighted" status.
    Anyhow, here it the suggestions I would have:
    - introduce a new "unread" post column (in addition to the "new" one).
    - offer an option to "mark thread/topic as read" (so that you don't have to go through 20+ pages of a thread to deactivate it)
    Sorry for the misunderstanding.

  • How to use multiple threads and swing for displaying status/interaction

    I have a Swing-app which have to show progress and allow userinteraction for these tasks:
    * First:
    retrieve a list of IDs(String) from the database (single thread running)
    * Second:
    some work on the id-list and list written to hd (same thread as above)
    * Third:
    retrieve Objects (based on the id-list) from different sources (Multiple Threads are running)
    To show the status I have a JProgressBar (indeterminate while task1&2 running) and
    a JTextArea showing the current status (connect,retrieve list, sort, ...)
    When task3 is starting the JTextArea have to disappear and be replaced by a ScrollPane
    with an array of Labels/TextAreas showing the status of each thread.
    While theses threads are working, the ID-list will be consumed and the JProgressBar
    shows the remaining precentage of the hole progress.
    Everything is working so far (excepts UI :) , the problem(s) I have:
    I need the threads to interacts with the user through the ui. e.g: "Connection to db-xyz lost! reconnect?"
    But I don´t know how to do this correctly.
    I think one way would be to send an event to the ui... but how?
    (the ui must know which thread is calling to unpause it after user answered)
    I know that threads should NOT change the swing(-container) - How do I notify the ui that a thread has a question?
    Since these threads are really time-consuming the UI is not updated frequently,
    how can I increase this? (perhaps using another thread-priority?)
    thanks for help!

    if/when your threads need to interact with the UI, they can create a Runnable & send it to SwingUtilities.invokeLater or invokeAndWait. This Runnable can popup a message to the user, and act on the choice of the user (reconnect, cancel, ...). This action could be something which "unpauses" the task thread.
    You may need to do synchronisation between the code in the Runnable & the Thread to which it is related - so the latter Thread knows when the user has made the choice.

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Good practice to update Swing i SwingUtilities.invokeLater() method?

    Is it a good practice to allways make the updates/changes of Swing components in the SwingUtilities.invokeLater() method in a multithreaded application. Or are there any situations when it´s not?

    There are a number of methods that are thread safe, but they generally say so in the API
    If they aren't then you shouldn't be updating them on the EDT.
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html|http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html]

  • Thread in Swing help please

    Hey gang, I am relatively new to Java world, and especially to swing and thread. I am trying to build an application with a main dashboard, where the users can click on a button and parse a text file. However, if there were an error in the file, I would like to stop paring the file, but not exit the application once there is an error. I don?t know quite how to stop the process without using System.exit(0); When I use System.exit(0); needless to say my main dashboard exits also, which I want to avoid.
    I was told to use threads by my friends, but I trying reading up on SwingWorker class found on the website to help with threads (at least I think so). I am still very lost. If there is any more clarification needed, please let me know

    Your problem has nothing to do with threads. As "kulkarni_ash" wrote, you need to surround code which crashes with try{ }catch(Throwable t}{...}. Most runtime problems are reported by throwing an exception, which is understood as "abrubtly abort code execution and gracefully return to closest enclosing catch". There is many exceptions classes, each tided to specific kind of error. Throwable is most general one, and you should not use it usually.
    Threads, on other hand are used only, if you expect to have a lot of work to be done and like to have it done "in background" what leaves user interface alive. Example is printing - without thread user interface will freez until last page is printed - with printing thread user may click cancel to abort printing.

  • Very Urgent, files, threads, and swing !!!!

    Dear friends, i have a swing application, in that application i have a class that extends a thread, that thread will do nothing but read the contents of my data file and puts them in an array, but i am getting a NullpointerException in my thread, could any friend help me please, it is very urgent, i will post my code below.
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DateFormat;
    import java.util.*;
    import javax.swing.*;
    import java.sql.*;
    import java.net.URL;
    import java.io.*;
    public class FinalMachine extends JFrame
    private JPanel MainPanel, ThicknessPanel, MainManager,fieldsPanel, sub_panel;
    private Container c;
    private CardLayout CardManager;
    private String timezone;
    private static final int ONE_SECOND = 1000;
    private JLabel welcome_label, label1, label2, label3,field_label;
    private JTextField data_entry;
    private Connection connection;
    public JPanel thick_figure;
    public int num_of_hits, next_index, recCount;
    public int dataBuffer[];
    public FileReader data_file;
    public BufferedReader b_data_file;
    public File tem_file;
    final int num_of_rec = 20;
    public FinalMachine()
    super("PHOENIX MACHINERY s.a.l");
    /* Start all threads */
    /* Start filling data file in global array */
         loadData dataFile = new loadData();
         dataFile.start();          
    /* Adding control to window application */
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent windowevent)
    // setDefaultCloseOperation(0);
              System.exit(0);
    public void windowDeiconified(WindowEvent eve)
    setState(0);
    addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent componentevent)
    setSize(500, 500);
    Dimension dimension1 = Toolkit.getDefaultToolkit().getScreenSize();
    if(dimension1.width == 800 && dimension1.height == 600)
    setLocation(150, 25);
    else
    if(dimension1.width == 1024 && dimension1.height == 768)
    setLocation(200, 100);
    /* Setting the location of the application on the screen */
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    if(dimension.width == 800 && dimension.height == 600)
    setLocation(150, 25);
    else
    if(dimension.width == 1024 && dimension.height == 768)
    setLocation(200, 100);
    /* Constructing the main menu */
         JMenuBar bar = new JMenuBar();
         setJMenuBar( bar );
         JMenu fileMenu = new JMenu( "File");
         fileMenu.setMnemonic( 'F' );
         JMenuItem mainItem = new JMenuItem( "Main page" );
         mainItem.setMnemonic( 'M' );
         mainItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "main");
         fileMenu.add( mainItem );
         JMenuItem dataItem = new JMenuItem( "Database page" );
         dataItem.setMnemonic( 'D' );
         dataItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "data_base");
         fileMenu.add( dataItem );
         JMenuItem printItem = new JMenuItem( "Print" );
         printItem.setMnemonic( 'P' );
         printItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   PrintUtilities.printComponent(MainManager);
         fileMenu.add( printItem );
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'P' );
         exitItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                        System.exit(0);
         fileMenu.add( exitItem );
         bar.add( fileMenu );
         JMenu figureMenu = new JMenu( "Figures");
         figureMenu.setMnemonic( 'G' );
         JMenuItem thicknessItem = new JMenuItem( "Thickness" );
         thicknessItem.setMnemonic( 'T' );
         thicknessItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "thickness");
         figureMenu.add( thicknessItem );
         bar.add( figureMenu );
         JMenu helpMenu = new JMenu( "Help");
         helpMenu.setMnemonic( 'H' );
         JMenuItem aboutItem = new JMenuItem( "About us" );
         aboutItem.setMnemonic( 'A' );
         aboutItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   JOptionPane.showMessageDialog(null, "Engineer Bilal Haidar (Computer & "+                     "Communication Engineering)\n\n All Rights Reserevd. @ 2002",
                        "About me...", JOptionPane.PLAIN_MESSAGE);
         helpMenu.add( aboutItem );
         bar.add( helpMenu );
    /* Intializing global values */
    dataBuffer = new int[60];
    /* Initializing the panels */
    c = getContentPane();
    c.setLayout(new FlowLayout());
    CardManager = new CardLayout();
    MainManager = new JPanel(false);
    MainManager.setLayout(CardManager);
    c.add(MainManager);
    javax.swing.border.Border border = BorderFactory.createEmptyBorder(10, 10, 5, 10);
    MainPanel = new JPanel(false);
    MainPanel.setLayout(new BoxLayout(MainPanel, 1));
    MainPanel.setBorder(border);
    ThicknessPanel = new JPanel(false);
    ThicknessPanel.setLayout(new BoxLayout(ThicknessPanel, 1));
    ThicknessPanel.setBorder(border);
    fieldsPanel = new JPanel(false);
    fieldsPanel.setLayout( new BoxLayout( fieldsPanel,1));
    fieldsPanel.setBorder(border);
    sub_panel = new JPanel(false);
    sub_panel.setLayout( new BoxLayout(sub_panel,0) );
    sub_panel.setBorder(border);
    thick_figure = new JPanel(false);
    thick_figure.setBorder(border);
    /* Filling the main panel */
    JLabel jlmain = new JLabel("Main Page");
    MainPanel.add(jlmain);
    timezone = showTime(new Locale("en", "US"));
    JLabel jltime = new JLabel(" " + timezone);
    MainPanel.add(jltime);
    MainManager.add(MainPanel, "main");
    /* Filling the thickness panel */
    num_of_hits = 0;
    next_index = 0;
    /* fill in with ero values for everything*/
    /*display the figure*/
    ThicknessPanel.add(thick_figure);
    JLabel blanklabel = new JLabel(" ");
    ThicknessPanel.add(blanklabel);
    JButton build_fig = new JButton("Draw Figure");
    build_fig.addActionListener(
         new ActionListener() {  // anonymous inner class
         public void actionPerformed( ActionEvent e )
    if ( num_of_hits == 0 )
    /* draw figure based on first 20 points in the array */
    next_index = num_of_rec;
    else
    if ( num_of_hits > 3 )
    JOptionPane.showMessageDialog(null,"No more data to draw","Error Drawing",JOptionPane.ERROR_MESSAGE);
    else
    /* draw the figure starting the data from index 20*/
    next_index = next_index + num_of_rec;
    num_of_hits += 1;
    ThicknessPanel.add(build_fig);
    MainManager.add(ThicknessPanel, "thickness");
    /* filling the database panel */
    label1 = new JLabel(" ",SwingConstants.CENTER);
    welcome_label = new JLabel(" Database Page ",SwingConstants.CENTER);
    label2 = new JLabel(" ",SwingConstants.CENTER);
    fieldsPanel.add( label1 );
    fieldsPanel.add( welcome_label );
    fieldsPanel.add( label2 );
    field_label = new JLabel(" Enter your name: ");
    data_entry = new JTextField( 10 );
    sub_panel.add( field_label );
    sub_panel.add( data_entry );
    fieldsPanel.add( sub_panel );
    JButton add_data = new JButton( "Add me" );
    add_data.addActionListener(
         new ActionListener() {  // anonymous inner class
         public void actionPerformed( ActionEvent e )
    // try {
    //          url = "jdbc:odbc:DataEntry";
    //          Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    //          connection = DriverManager.getConnection( url );
    //               System.out.println( "Connection Suucessfull");
    // Statement statement = connection.createStatement();
    //                String get_field;
    //               get_field = data_entry.getText();
    //               String query = "INSERT INTO data (anyField) VALUES ('get_field')";
    //                int result1 = statement.executeUpdate( query );
    //           if ( result1 == 1 )
    // JOptionPane.showMessageDialog(null, "Thanks for the info..."," Data Entry Success",JOptionPane.INFORMATION_MESSAGE);
    //                else
    //                     JOptionPane.showMessageDialog(null, "Sorry, your name was not added...","Data entry error",JOptionPane.ERROR_MESSAGE);
    //     catch ( ClassNotFoundException cnfex ) {
    //          // process ClassNotFoundExceptions here
    //          cnfex.printStackTrace();
    //               System.out.println( "Connection UN Suucessfull");
    //          catch ( SQLException sqlex ) {
    //     // process SQLExceptions here
    //          sqlex.printStackTrace();
    //                System.out.println( "Connection UN Suucessfull");
    //          catch ( Exception ex ) {
    //          // process remaining Exceptions here
    //          ex.printStackTrace();
    //               System.out.println( "Connection UN Suucessfull");
    fieldsPanel.add(add_data);
    MainManager.add(fieldsPanel, "data_base");
    /* display time */
    Timer timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent actionevent)
    timezone = showTime(new Locale("en", "US"));
    setTitle("PHOENIX MACHINERY s.a.l " + timezone);
    timer.start();
    public static void main(String args[])
    FinalMachine finalmachine = new FinalMachine();
    finalmachine.setSize(500, 500);
    ImageIcon imageicon = new ImageIcon("images/pc.gif");
    finalmachine.setIconImage(imageicon.getImage());
    finalmachine.show();
    public static String showTime(Locale locale)
    java.util.Date date = new java.util.Date();
    byte byte0 = 2;
    DateFormat dateformat = DateFormat.getTimeInstance(byte0, locale);
    String s = dateformat.format(date);
    return s;
    /* Thread loadData starts here */
    class loadData extends Thread
    public void run()
    try {
              readMyFile();
    catch( Exception x )
    System.out.println("The following error occured in LoadData thread : "+x.toString() ); }
    } // run() ends here
    /* method read file inside thread loadData */
    void readMyFile() {
    String record = " ";
    recCount = 0;
    try {
              tem_file = new File("mydata.dat");
              data_file = new FileReader(tem_file);
              b_data_file = new BufferedReader( data_file );
              record = new String();
              while ( (record = b_data_file.readLine()) != null ) {
              dataBuffer[recCount] = Integer.parseInt(record);
              recCount += 1; }
         b_data_file.close();     
              catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
         } // end of readMyFile()
    } // thread loadData ends
    mydata.dat
    2
    4
    3
    1
    2
    3
    5
    2
    4
    1
    6
    3
    2
    5
    4
    1
    2
    5
    8
    2
    6
    9
    7
    4
    2
    1
    0
    2
    5
    4
    8
    7
    5
    6
    3
    2
    1
    4
    3
    0
    2
    3
    6
    5
    2
    1
    4
    5
    6
    9
    8
    5
    2
    1
    6
    8
    3
    1
    7
    5

    Thank you Mr. jobuck, you helped me a lot, i wonder if you can provide me with a tutorial on how threads work and how runnables work too. i fixed the error ut old me about but still when i try to add another thread to my program i got an error saying that, i must decalre the new thread in a seperate file please can u have a look on what i have:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DateFormat;
    import java.util.*;
    import javax.swing.*;
    import java.sql.*;
    import java.net.URL;
    import java.io.*;
    public class FinalMachine extends JFrame
    private JPanel MainPanel, ThicknessPanel, MainManager,fieldsPanel, sub_panel;
    private Container c;
    private CardLayout CardManager;
    private String timezone;
    private static final int ONE_SECOND = 1000;
    private JLabel welcome_label, label1, label2, label3,field_label;
    private JTextField data_entry;
    private JPanel thick_figure;
    private int num_of_hits, next_index, recCount, read_flag;
    private int dataBuffer[];
    private FileReader data_file;
    private BufferedReader b_data_file;
    private File tem_file;
    private Connection connection;     
    final int num_of_rec = 20;
    public FinalMachine()
    super("PHOENIX MACHINERY s.a.l");
    /* load JDBC drivers */
    try {
    String url = "jdbc:odbc:DataEntry";
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
         connection = DriverManager.getConnection( url );
         System.out.println( "Connection Suucessfull");
    catch ( ClassNotFoundException cnfex ) {
    // process ClassNotFoundExceptions here
    cnfex.printStackTrace();
         System.out.println( "Connection UN Suucessfull");
    catch ( SQLException sqlex ) {
    // process SQLExceptions here
    sqlex.printStackTrace();
         System.out.println( "Connection UN Suucessfull");
    catch ( Exception ex ) {
    // process remaining Exceptions here
    ex.printStackTrace();
         System.out.println( "Connection UN Suucessfull");
    /* Intializing global values */
    dataBuffer = new int[60];
    /* Start all threads */
    /* Start filling data file in global array */
         loadData dataFile = new loadData();
         dataFile.start();          
         setData setdata = new setData();
         setdata.start();          
    /* Adding control to window application */
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent windowevent)
    // setDefaultCloseOperation(0);
              System.exit(0);
    public void windowDeiconified(WindowEvent eve)
    setState(0);
    addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent componentevent)
    setSize(500, 500);
    Dimension dimension1 = Toolkit.getDefaultToolkit().getScreenSize();
    if(dimension1.width == 800 && dimension1.height == 600)
    setLocation(150, 25);
    else
    if(dimension1.width == 1024 && dimension1.height == 768)
    setLocation(200, 100);
    /* Setting the location of the application on the screen */
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    if(dimension.width == 800 && dimension.height == 600)
    setLocation(150, 25);
    else
    if(dimension.width == 1024 && dimension.height == 768)
    setLocation(200, 100);
    /* Constructing the main menu */
         JMenuBar bar = new JMenuBar();
         setJMenuBar( bar );
         JMenu fileMenu = new JMenu( "File");
         fileMenu.setMnemonic( 'F' );
         JMenuItem mainItem = new JMenuItem( "Main page" );
         mainItem.setMnemonic( 'M' );
         mainItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "main");
         fileMenu.add( mainItem );
         JMenuItem dataItem = new JMenuItem( "Database page" );
         dataItem.setMnemonic( 'D' );
         dataItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "data_base");
         fileMenu.add( dataItem );
         JMenuItem printItem = new JMenuItem( "Print" );
         printItem.setMnemonic( 'P' );
         printItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   PrintUtilities.printComponent(MainManager);
         fileMenu.add( printItem );
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'P' );
         exitItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                        System.exit(0);
         fileMenu.add( exitItem );
         bar.add( fileMenu );
         JMenu figureMenu = new JMenu( "Figures");
         figureMenu.setMnemonic( 'G' );
         JMenuItem thicknessItem = new JMenuItem( "Thickness" );
         thicknessItem.setMnemonic( 'T' );
         thicknessItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   CardManager.show(MainManager, "thickness");
         figureMenu.add( thicknessItem );
         bar.add( figureMenu );
         JMenu helpMenu = new JMenu( "Help");
         helpMenu.setMnemonic( 'H' );
         JMenuItem aboutItem = new JMenuItem( "About us" );
         aboutItem.setMnemonic( 'A' );
         aboutItem.addActionListener (
              new ActionListener() {
                   public void actionPerformed( ActionEvent e )
                   JOptionPane.showMessageDialog(null, "Engineer Bilal Haidar (Computer & "+                     "Communication Engineering)\n\n All Rights Reserevd. @ 2002",
                        "About me...", JOptionPane.PLAIN_MESSAGE);
         helpMenu.add( aboutItem );
         bar.add( helpMenu );
    /* Initializing the panels */
    c = getContentPane();
    c.setLayout(new FlowLayout());
    CardManager = new CardLayout();
    MainManager = new JPanel(false);
    MainManager.setLayout(CardManager);
    c.add(MainManager);
    javax.swing.border.Border border = BorderFactory.createEmptyBorder(10, 10, 5, 10);
    MainPanel = new JPanel(false);
    MainPanel.setLayout(new BoxLayout(MainPanel, 1));
    MainPanel.setBorder(border);
    ThicknessPanel = new JPanel(false);
    ThicknessPanel.setLayout(new BoxLayout(ThicknessPanel, 1));
    ThicknessPanel.setBorder(border);
    fieldsPanel = new JPanel(false);
    fieldsPanel.setLayout( new BoxLayout( fieldsPanel,1));
    fieldsPanel.setBorder(border);
    sub_panel = new JPanel(false);
    sub_panel.setLayout( new BoxLayout(sub_panel,0) );
    sub_panel.setBorder(border);
    thick_figure = new JPanel(false);
    thick_figure.setBorder(border);
    /* Filling the main panel */
    JLabel jlmain = new JLabel("Main Page");
    MainPanel.add(jlmain);
    timezone = showTime(new Locale("en", "US"));
    JLabel jltime = new JLabel(" " + timezone);
    MainPanel.add(jltime);
    MainManager.add(MainPanel, "main");
    /* Filling the thickness panel */
    num_of_hits = 0;
    next_index = 0;
    /* fill in with ero values for everything*/
    /*display the figure*/
    ThicknessPanel.add(thick_figure);
    JLabel blanklabel = new JLabel(" ");
    ThicknessPanel.add(blanklabel);
    JButton build_fig = new JButton("Draw Figure");
    build_fig.addActionListener(
         new ActionListener() {  // anonymous inner class
         public void actionPerformed( ActionEvent e )
    if ( num_of_hits == 0 )
    /* draw figure based on first 20 points in the array */
    next_index = num_of_rec;
    else
    if ( num_of_hits > 3 )
    JOptionPane.showMessageDialog(null,"No more data to draw","Error Drawing",JOptionPane.ERROR_MESSAGE);
    else
    /* draw the figure starting the data from index 20*/
    next_index = next_index + num_of_rec;
    num_of_hits += 1;
    ThicknessPanel.add(build_fig);
    MainManager.add(ThicknessPanel, "thickness");
    /* filling the database panel */
    label1 = new JLabel(" ",SwingConstants.CENTER);
    welcome_label = new JLabel(" Database Page ",SwingConstants.CENTER);
    label2 = new JLabel(" ",SwingConstants.CENTER);
    fieldsPanel.add( label1 );
    fieldsPanel.add( welcome_label );
    fieldsPanel.add( label2 );
    field_label = new JLabel(" Enter your name: ");
    data_entry = new JTextField( 10 );
    sub_panel.add( field_label );
    sub_panel.add( data_entry );
    fieldsPanel.add( sub_panel );
    JButton add_data = new JButton( "Add me" );
    add_data.addActionListener(
         new ActionListener() {  // anonymous inner class
         public void actionPerformed( ActionEvent e )
              try {
    Statement statement = connection.createStatement();
                   String get_field;
              get_field = data_entry.getText();
              String query = "INSERT INTO data (anyField) VALUES ('"+get_field+"')";
              int result1 = statement.executeUpdate( query );
              if ( result1 == 1 )
              JOptionPane.showMessageDialog(null, "Thanks for the info..."," Data Entry Success",JOptionPane.INFORMATION_MESSAGE);
                        data_entry.setText(" ");     
              else
                        JOptionPane.showMessageDialog(null, "Sorry, your name was not added...","Data entry error",JOptionPane.ERROR_MESSAGE);
         catch ( SQLException sqlex ) {
         // process SQLExceptions here
              sqlex.printStackTrace();
                   System.out.println( "Connection UN Suucessfull");
              catch ( Exception ex ) {
              // process remaining Exceptions here
              ex.printStackTrace();
                   System.out.println( "Connection UN Suucessfull");
    fieldsPanel.add(add_data);
    MainManager.add(fieldsPanel, "data_base");
    /* display time */
    Timer timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent actionevent)
    timezone = showTime(new Locale("en", "US"));
    setTitle("PHOENIX MACHINERY s.a.l " + timezone);
    timer.start();
    public static void main(String args[])
    FinalMachine finalmachine = new FinalMachine();
    finalmachine.setSize(500, 500);
    ImageIcon imageicon = new ImageIcon("images/pc.gif");
    finalmachine.setIconImage(imageicon.getImage());
    finalmachine.show();
    public static String showTime(Locale locale)
    java.util.Date date = new java.util.Date();
    byte byte0 = 2;
    DateFormat dateformat = DateFormat.getTimeInstance(byte0, locale);
    String s = dateformat.format(date);
    return s;
    /* Thread loadData starts here */
    public class loadData extends Thread
    public void run()
    try {
              readMyFile();
              read_flag = 1;
              notify();
    catch( Exception x )
    System.out.println("The following error occured in LoadData thread : "+x.toString() );
    } // run() ends here
    /* method read file inside thread loadData */
    void readMyFile() {
    String record = " ";
    recCount = 0;
    try {
              tem_file = new File("mydata.dat");
              data_file = new FileReader(tem_file);
              b_data_file = new BufferedReader( data_file );
              record = new String();
              while ( (record = b_data_file.readLine()) != null ) {
              dataBuffer[recCount] = Integer.parseInt(record);
              recCount += 1; }
         b_data_file.close();     
              catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
         } // end of readMyFile()
    } // thread loadData ends
    public class setData extends Thread {
    public void run()
    try {
              while ( !read_flag ) {
                   try {     wait(); }
                   catch( InterruptedException e ) {
                        e.printStackTrace();
              } // end while
              for(int index = 0; index < 60; index++)
              System.out.println("Array["+index+"] = "+dataBuffer[index]);
    catch( Exception x )
    System.out.println("The following error occured in LoadData thread : "+x.toString() );
    } // run() ends here
    the only added thing is the setData thread, i want this thread to start printing out the array whenever, loadData thread has finished filling the data inside the array please i need ur help.

  • More on Updating Swing Components during long operations...

    After reading thru a few posts here, I've come to the conclusion that what I need is going to be much more difficult than I'd planned. Neverthess i'll try to explain...
    I have a JFrame which contains a simple JLabel and JProgressBar. While I am performing a long network operation, I am making calls to a Thread class (which contains the above components) to update the JFrame indicating the current status. Normally I have no problem with this as the paintImmediately method suffices. However, when I call this long operation from the constructor of a larger, more complex JFrame, the GUI remains unresponsive (despite the plethora of paintImmediately calls that are executed) until the user clicks in the threaded progress box.
    Unfortunately the SwingWorker solution will not work for me as I need to be completely backwards compatible with JDK 1.3 (supporting Mac OSX 10.X). Oddly enough tho, I don;t get these problems when I use the same code in JDK 1.1.8 on Mac OS9.
    Any ideas?
    thanks!

    heh...looks like it was a simple thing afterall :)
    The JDialog (not JFrame) just needed focus.
    heh...is it friday yet? ;)

  • Thread update problem

    hi
       i am having problem with my ID, threads from 13th onwards after 4;48 pm are not updating.
    thanks

    might be it is your browser problem.
    Regards,
    venkat

  • Updating swing components

    Here is my problem...I am trying to update each of my components like JTree, and JTable when my data changes in a mysql database after the user enters information and clicks the save button. I want this to happen while the program is up and running...I looked at threads but I wasn't certain that this is what I need...Also I looked at SwingWorker but I can't figure out how to use it, or if this is even what I need...Also I am using tabs to display my information so if mysql is updated on one tab I want all the other tabs to immediatly update...I don't know if I am explaining it right....but I hope you can help.
    thanks
    James

    I am not too sure about tabs, but as far as JTree and Jtable are concerned you can update them by updating their TableModel and TreeModel.
    //update the model
    table.setModel(model);
    You can look at TableModel and TreeModel turorials for detailed info

  • Having troble focusing when updating swing form type application

    I'm writing a piece of code where it is necessary to allow the end-user to unmask a password. I want the focus to return to the text field/password field however because it is necessary to call repaint() using the ActionListner calling requestFocusInWindow has very little effect. This is because repaint que's and is run by run by the thread that was running the ActionListner, (I hope I'm making sense). I don't do GUI often for obvious reasons. Please look at the Box bellow and tell me if you have a solution.
    import javax.swing.*;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    class Blah extends Box {
      protected final Document doc=new PlainDocument();
      JTextField jtf=new JTextField(doc,null,10);
      JPasswordField jpf=new JPasswordField(doc,null,10);
      JCheckBox jcb = new JCeckBox("switch");
      Blah(){
        super(BoxLayout.X_AXIS);
        jcb.addActionListner(new LayoutAction(this));
        this.invalidate(); //Makesure that doLayout is called (not verbosely necessary)
      @Overrides
      public void doLayout(){
        this.removeAll();
        /*This is the main function of the code */
        if(jcb.isSelected())this.add(jtf);
        else this.add(jpf);
        this.add(jcb);
        super.doLayout();
    } class LayoutAction implements ActionListner {
      JComponent owner;
      LayoutAction(JComponent owner){
        this.owner=owner;
      public void actionPerformed(ActionEvent e){
        this.owner.revalidate();
        this.owner.repaint();
    }

    Hey thanks... That helped out with another situation similar to this I was having trouble with... Turns out it's the revalidate() that makes requestFocus() usless thus I changed the code to have teh request focus in the overriden doLayout().... I'm sure this doesn't matter to you much more than you were being helpful.
    So thanks!!! :)

  • Is it possible to create Thread for Swing Components or for JApplet?

    Can i create a Thread by extending Thread class or implementing Runnable interface for Swing Components?
    Can i create a Thread by extending Thread class or implementing Runnable interface with JApplet?
    thanks

    Does your website live on a Windows server? The above link you posted will require a Windows server for that to work but if you do, then you should be able to just follow the links instructions.
    If your site is not on a Windows server (maybe it's on Linux?) then you would most likely need a PHP solution - something like this: http://www.w3schools.com/php/php_mail.asp. Depending on your host, they might actually have a ready-built form script for you to use so it might be best to ask them first.
    You might also want some kind of validation to ensure you receive the correct information so something like jQuery Validate could work.

  • Help Update Swing

    Hi,
    I'm having some trouble with a swing application, let me explain it to you.
    I have a function (provided by a library, so it wont be easy to modify it), that retrieves files from a server; An object must be handed over to this function so the programmer can execute some code when a file is retrieved. What I'm trying to do is to update (append some text) on a JTextArea whenever a file is retrieved so the user has some idea of whats going on during the (usually) lengthy process.
    Problem here is that the JTextArea, does not get updated on the screen until during the retriving process, so it goes from an empty JTextArea (at the beginning and during the file transmission process), to a JTextArea with all the information of the process after the last file has been retrieved.
    The function which updates the JTextArea looked like this:
    public void sendReceivedObjectIndication(final String dicomFileName, final String transferSyntax, final String callingAETitle) throws DicomNetworkException, DicomException, IOException {
            if (dicomFileName != null) {
                         area.append("\nReceived: " + dicomFileName + " from " + callingAETitle);
             } else {
                //Notify failure
        }I also tried this
    public void sendReceivedObjectIndication(final String dicomFileName, final String transferSyntax, final String callingAETitle) throws DicomNetworkException, DicomException, IOException {
            if (dicomFileName != null) {
                //System.out.println("Received: " + dicomFileName + " from " + callingAETitle + " in " + transferSyntax);
                Runnable r=new Runnable() {
                    public void run() {
                       area.append("\nReceived: " + dicomFileName + " from " + callingAETitle);
                SwingUtilities.invokeLater(r);           
            } else {
               //Notify failure
        }But none of them works as expected.
    Anybody knows what to do here?
    Thanks in advance
    Jc

    You need to perform your lengthy task off of the EDT. Use a javax.swing.SwingWorker, as it facilitates periodically updating a GUI (on the EDT) while doing the lengthy task off of the EDT.
    Also, read this for a general tutorial and background on the subject: [Concurrency in Swing|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html] .

  • Batch thread updates running?

    What did just happen? How come the Oracle Database category list page shows almost every forum with a Last post updated around "Nov 22, 2012 8:01 AM"?
    Same thing with the first forums on the Fusion Middleware category page as well.
    Noticed the same thing in the top Java category (but with dates around "Nov 21, 2012 9:19 AM").
    Related to upgrade preparations perhaps?
    Edited by: orafad on Nov 22, 2012 1:48 PM

    Well your problem is that you are not actually starting your pdf threads, you are simply calling the run method of the object. You need to call start() in the mft object. The start method causes the underlying system thread to be started then the execution of the run method is carried out within that thread.
    You should check why calling mft.start() does not result in the run method being called.
    1- Threads never run in parallel on a single CPU machine, they share time on the CPU. No CPU can run more than one process simultaneously even if the OS makes it look that way.
    2- The process you are carrying out is not going to be performant enough using multi-threading, you are simply going to clog your machine with Threads which do a lot of I/O which will cause them to spend most of their time in the blocked state (this means that they automatically yield to other threads. It is actually more performant to use a single thread to do this job.

Maybe you are looking for

  • (266436851) Q: WWSD-7 Can web service be in packages other than .ear files?

    Q:<WWSD-7> Could we deploy the SOAP package not using the ear, instead could we put all the related Java code to jar file and the rest of the code to the war files? The reason I asked is because we do not deploy our applciation in ear format. A:<WWSD

  • ASNs with Third Party Orders

    Hi All, I ve tried my luck by posting this question some time back but had no response. Want to try once more. The scenario is with Third Part Order Processing. We have some third party orders. The vendor manufactires the goods and ships it directly

  • How do i put icloud in my dock

    how do i put icloud or a mail icon in my dock. I have an G4 imac.

  • Tasks stuck in 'In Queue' status

    Hi, Recently we upgraded from OIM 8.5.3 to OIM 9.1. We have a Websphere Clustered environment. Whenever an Approver or SA approved a pending task or sets response to the Open Tasks, the task's status becomes In Queue and remains as that only. It does

  • How do you append, or copy and paste, pages

    Hi, if I'm in a file and want to extract a few pages but not the whole file to another file, is there a quick way to do it? I know you can extract the pages to a separate file, save the file and then insert into or combine with another file but this