import java.awt.*; import javax.swing.*; import java.awt.event.*; // Ejemplo proveniente de // AnimationApplet // By David Reilly // un ejemplo de "hilos desenredados", // http://www.javacoffeebreak.com/articles/threads/ // public class Ticker2 extends JPanel implements Runnable { private Thread animationThread = null; private String animationString; private Font animationFont; private int animationWidth; private int xoffset; private int tickerWidth; private boolean animate = true; public static final Dimension DEFAULT_SIZE = new Dimension( 400, 200 ); public Ticker2( String s ) { animationString = s; setOpaque( true ); setBackground( Color.black ); setForeground( Color.white ); animationFont = new Font( "SansSerif", Font.BOLD, 16); animationWidth = getFontMetrics( animationFont ).stringWidth( animationString ); setFont( animationFont ); xoffset = 15; tickerWidth = DEFAULT_SIZE.width; addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { animate = false; } public void mouseReleased( MouseEvent e ) { animate = true; } } ); // Pasa nuestro hilo a una instancia de java.lang.Runnable (us) animationThread = new Thread(this); // Inicia el hilo (el nuevo hilo ejecuta el método public void run() animationThread.start(); } public Dimension getPreferredSize() { return DEFAULT_SIZE; } public void paintComponent(Graphics g) { super.paintComponent( g ); int yoffset = getHeight() / 2; tickerWidth = getWidth(); // permite reajustar tamaño g.drawString( animationString, xoffset, yoffset ); } public void run() { while (true) { try { if (animate == false) { Thread.sleep(100); continue; } // Disminuye xOffset para el efecto de desplazamiento xoffset--; // si la cadena se sale de la pantalla, vuelve a la derecha if (xoffset <= -animationWidth) xoffset = tickerWidth; repaint(); Thread.sleep(10); } catch (InterruptedException e) {} } } public static void main( String [] args ) { JFrame aFrame = new JFrame( "Ticker" ); aFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); Ticker2 theTicker = new Ticker2( "Pulse para detenerme." ); aFrame.getContentPane().add( theTicker, BorderLayout.CENTER ); aFrame.pack(); aFrame.setVisible( true ); } }