I am programming the Mexican lottery game (with custom cards) in Java and I would like to display the images in an array so that they are taken randomly and without repeating. I attach my code that works so far, but using Strings
the names of the cards and I thank you in advance for the help.
letter class
public class Carta {
private String cara;
public Carta( String caraCarta )
{
cara = caraCarta;
}
public String toString()
{
return cara;
}
}
CardPack class which is where I load the GUI with code removed and left out for simplicity
private Carta paquete[];
private int cartaActual;
public PaqueteDeCartas2()
{
super( "Lotería Mágica" );
String caras[] = { "Strings que tienen nombres de cartas" };
paquete = new Carta[ 44 ];
cartaActual = -1;
for ( int cuenta = 0; cuenta < paquete.length; cuenta++ )
paquete[ cuenta ] = new Carta( caras[ cuenta % 44 ] );
Container contenedor = getContentPane();
contenedor.setLayout( new FlowLayout() );
repartirBoton = new JButton( "Corre y se va con..." );
repartirBoton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent eventoAccion )
{
Carta repartida = repartirCarta();
if ( repartida != null ) {
pantallaCampo.setText( repartida.toString() );
estadoEtiqueta.setText( "Carta #: " + cartaActual );
}
else {
pantallaCampo.setText( "NO HAY MAS CARTAS QUE REPARTIR" );
estadoEtiqueta.setText( "Barajee las cartas para continuar" );
}
}
}
);
contenedor.add( repartirBoton );
barajarBoton = new JButton( "Barajar cartas" );
barajarBoton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent eventoAccion )
{
pantallaCampo.setText( "BARAJANDO ..." );
barajar();
pantallaCampo.setText( "SE BARAJO EL PAQUETE" );
}
}
);
contenedor.add( barajarBoton );
/* Cosas de GUI*/
}
private void barajar()
{
cartaActual = -1;
for ( int primera = 0; primera < paquete.length; primera++ ) {
int segunda = ( int ) ( Math.random() * 44 );
Carta temp = paquete[ primera ];
paquete[ primera ] = paquete[ segunda ];
paquete[ segunda ] = temp;
}
repartirBoton.setEnabled( true );
}
private Carta repartirCarta()
{
if ( ++cartaActual < paquete.length )
return paquete[ cartaActual ];
else
{
repartirBoton.setEnabled( false );
return null;
}
}
public static void main( String args[] )
{
PaqueteDeCartas2 aplicacion = new PaqueteDeCartas2();
aplicacion.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
First you need to create a Panel to paint the image:
Then you can generate within your code an array with the list of images, if you prefer you can use a Map to maintain a name/image relationship:
So you can generate a panel for each image and use that panel in your frontend instead of displayField
By the way, to randomize the list you just need the list with the panels, or references, or whatever, and use
Collections.shuffle(fileList, new Random(seed));