import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloJava4 { public static void main( String[] args ) { JFrame cornice = new JFrame( "HelloJava4" ); cornice.getContentPane().add( new HelloComponent4("Ehila`, Java!") ); cornice.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); cornice.setSize( 300, 300 ); cornice.setVisible( true ); // Dopo aver costruito una prima cornice con un messaggio lampeggiante, // costruiamone un'altra quasi uguale ma che opera indipendentemente. // Si trattera` di un altro oggetto della stessa classe di quello di prima. JFrame kornice = new JFrame( "HelloJava4" ); kornice.getContentPane().add( new HelloComponent4("Ohime`, Java!") ); kornice.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); kornice.setSize( 300, 300 ); kornice.setVisible( true ); } } class HelloComponent4 extends JComponent implements MouseMotionListener, ActionListener, Runnable { String theMessage; int messageX = 125, messageY = 95; // Coordinates of the message JButton theButton; int colorIndex; // Current index into someColors static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; boolean blinkState; public HelloComponent4( String message ) { theMessage = message; theButton = new JButton( "Cambia Colore" ); setLayout( new FlowLayout() ); add( theButton ); theButton.addActionListener( this ); addMouseMotionListener( this ); Thread t = new Thread( this ); t.start( ); } public void paintComponent( Graphics g ) { g.setColor( blinkState ? getBackground() : currentColor() ); g.drawString( theMessage, messageX, messageY ); } public void mouseDragged( MouseEvent e ) { // Save the mouse coordinates and paint the message. messageX = e.getX(); messageY = e.getY(); repaint(); } public void mouseMoved( MouseEvent e ) { } 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, awkwardly. if ( ++colorIndex == someColors.length ) colorIndex = 0; setForeground( currentColor() ); // Use the new color. repaint(); } synchronized private Color currentColor( ) { return someColors[ colorIndex ]; } public void run() { try { while( true ) { blinkState = !blinkState; // Toggle blinkState. repaint( ); // Show the change. Thread.sleep( 300 ); } } catch (InterruptedException ie) { } } }