Java Programing

June 14, 2007

public void actionPerformed(ActionEvent e) { // Did somebody

Filed under: Java Programming — webmaster @ 4:29 am

public void actionPerformed(ActionEvent e) { // Did somebody push our button? if (e.getSource( ) == theButton) changeColor( ); } synchronized private void changeColor( ) { // Change the index to the next color. if (++colorIndex == someColors.length) colorIndex = 0; setForeground(currentColor( )); // Use the new color. repaint( ); // Paint again so we can see the change. } synchronized private Color currentColor( ) { return someColors[colorIndex]; } public void run( ) { try { while(true) { blinkState = !blinkState; // Toggle blinkState. repaint( ); // Show the change. Thread.sleep(500); } } catch (InterruptedException ie) {} } public static void main(String[] args) { JFrame f = new JFrame(”HelloJava4″); // Make the application exit when the window is closed. f.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); f.setSize(300, 300); f.getContentPane( ).add(new HelloJava4(”Hello, Java!”)); f.setVisible(true); } } Compile and run this version of HelloJava just like the others. You’ll see that the text does in fact blink. Our apologies if you don’t like blinking text we’re not overly fond of it either but it does make for a simple, instructive example. 2.4.1 Threads All the changes we’ve made in HelloJava4 have to do with setting up a separate thread of execution to make the text blink. Java is a multithreaded language, which means there can be many threads running at the same time. A thread is a separate flow of control within a program. Conceptually, threads are similar to processes, except that unlike processes, multiple threads share the same address space, which means that they can share variables and methods (but also have their own local variables). Threads are also quite lightweight in comparison to processes, so it’s conceivable for a single application to be running hundreds of threads concurrently. Multithreading provides a way for an application to handle many different tasks at the same time. It’s easy to imagine multiple things going on at the same time in an application like a web browser. The user could be listening to an audio clip while scrolling an image; at the same time, the browser - 49

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by Java Web Hosting