Programación General > Java

 ActionListener en ciclo y cargar imágenes en ventana

(1/1)

Hidetoxin:
Hola soy nuevo en estos foros y también en el lenguaje Java   :hola:  . Espero me puedan hacer el favor de ayudarme a aclarar mis dudas, mi consulta es la siguiente: tengo que programar  :comp: un juego del ahorcado en el cual el usuario tiene 6 intentos para adivinar la palabra y cada vez que no acierte tiene que aparecer en la ventana la imagen del ahorcado, sin embargo no sé como cargar imágenes en la ventana  :(  .  En uno de los temas de este foro vi que se podía hacer de la siguiente manera, pero por alguna razón no me parece funcionar, ¿ Me he equivocado en algo o se hace de alguna otra manera ?

Código para cargar imágenes:


--- Código: Text --- private JLabel etiquetas[] = new JLabel[6];    private ImageIcon imagenes[] = new ImageIcon[6]; getContentPane( ).setLayout( null );        imagenes[0] = new ImageIcon( "BlackCat.jpg" );etiquetas[0] = new JLabel( imagenes[0] );etiquetas[0].setBounds( 20 , 30 , 320 , 480 );getContentPane( ).add( etiquetas[0] );  
Y otra duda que tengo es que tengo un teclado para ingresar las letras. El teclado es un arreglo de JButtons y los inicializo en un ciclo, ahora mi pregunta ¿ hay manera de implementar un Actionlistener por cada botón en un ciclo ? lo intente de la siguiente forma pero no funciona.


--- Código: Text --- String teclado = qwerty + asdfg + zxcv;                for( int i = 0 ; i < teclado.length( ) ; i++ )        {            botones[i].addActionListener( new ActionListener( ) {                public void actionPerformed( ActionEvent evt ){                    letra = botones[i].getText(  );                    adivinarAction( evt );                     }  }  );        }  
También les dejo mi código completo como referencia.

Código Completo:


--- Código: Text --- import java.util.*;import java.awt.*;                                                                                                             import javax.swing.*;    import java.awt.event.*;   public class Ahorcado extends JFrame{        private JTextField palabra;        private JButton botones[] = new JButton[27] , nuevo;        private String qwerty = "qwertyuiop" , asdfg = "asdfghjklñ" , zxcv = "zxcvbnm" , auxiliar1 , auxiliar2 , letra;        private String animales[] = { "jirafa" , "ballena" , "rinoceronte" , "gorila" , "aguila" , "murcielago" , "avestruz" , "reno" , "mapache" , "capibara" , "ormitorrinco" };      private JLabel etiquetas[] = new JLabel[6];        private ImageIcon imagenes[] = new ImageIcon[6];        int j;     Ahorcado( )    {                setTitle( "Juego del ahorcado" );        setSize( 930 , 700 );        setResizable( false );        iniciar( );        accionar( );        getRootPane( ).setDefaultButton( nuevo );            }        private void iniciar( )    {                getContentPane( ).setLayout( null );                imagenes[0] = new ImageIcon( "BlackCat.jpg" );        etiquetas[0] = new JLabel( imagenes[0] );        etiquetas[0].setBounds( 20 , 30 , 320 , 480 );        getContentPane( ).add( etiquetas[0] );                palabra = new JTextField( "" );        palabra.setFont( new Font( "Arial" , 1 , 50 ) );        palabra.setHorizontalAlignment( SwingConstants.CENTER );        palabra.setToolTipText( "Adivina la palabra" );        palabra.setBounds( 20 , 300 , 880 , 70 );        palabra.setText( "" );        palabra.setEditable( false );         getContentPane( ).add( palabra );                nuevo = new JButton( "" );        nuevo.setFont( new Font( "Arial" , 1 , 25 ) );        nuevo.setToolTipText( "Presiona aquí para adivinar otra palabra" );        nuevo.setText( "Nuevo juego" );        nuevo.setBounds( 650 , 570 , 250 , 70 );        getContentPane( ).add( nuevo );         int x = 20 , y = 400;                String teclado = qwerty + asdfg + zxcv;                for( int i = 0 ; i < 27 ; i++ )        {            botones[i] = new JButton( "" );            botones[i].setFont( new Font( "Arial" , 1 , 25 ) );            botones[i].setToolTipText( "Introduce la letra " + Character.toString( teclado.charAt( i ) ) );            botones[i].setBounds( x , y , 70 , 70);            x += 90;            if( i == qwerty.length( ) - 1 )            {                y += 85;                x = 20;            }            else if( i == qwerty.length( ) + asdfg.length( ) - 1 )            {                y += 85;                x = 20;            }            getContentPane( ).add( botones[i] );        }                for( int i = 0; i < teclado.length( ) ; i++ )             botones[i].setText( Character.toString( teclado.charAt( i ) ) );                }        private void accionar( )    {                String teclado = qwerty + asdfg + zxcv;                for( int i = 0 ; i < teclado.length( ) ; i++ )        {            botones[i].addActionListener( new ActionListener( ) {                public void actionPerformed( ActionEvent evt ){                    /*letra = botones[j++].getText( );*/                    adivinarAction( evt );                     } } );        }                nuevo.addActionListener( new ActionListener( ) {            public void actionPerformed( ActionEvent evt ){                jugarAction( evt ); } } );            }        private void adivinarAction( ActionEvent e )    {                palabra.setText( letra );            }        private void jugarAction( ActionEvent e )    {                Random rndm = new Random( );                auxiliar1 = animales[ rndm.nextInt( 11 ) ];        auxiliar2 = "";                for( int i = 0 ; i < auxiliar1.length( ) ; i++ )             auxiliar2 += "-";                palabra.setText( auxiliar2 );            }        public static void main( String args[] ){                try        {            UIManager.setLookAndFeel(            UIManager.getSystemLookAndFeelClassName( ) );}            catch( Exception e )            {                System.out.print( "No se puede continuar" + e );            }                                 Ahorcado objeto = new Ahorcado( );            objeto.setVisible( true );                             }    }  
¡ Saludos  !  :hola:

Navegación

[0] Índice de Mensajes

Ir a la versión completa