elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: 1 [2] 3 4
11  Programación / Java / Problema con boton en: 14 Marzo 2021, 16:01 pm
Hola. Buenas tardes para todos.
Estoy haciendo un juego implementando RMI y MVC y me surgio un problema con el boton "agregar jugador".
Cuando abro solo un cliente anda bien, agrega a los jugadores de forma correcta. Pero al abrir dos falla, agrega solo a 1 jugador y le reparte seis cartas. Nose cual sera el problema ya que nunca trabaje con RMI, soy novata con eso.
Si alguien me puede ayudar para darme cuenta de que esta pasando se lo agradeceria.

Les dejo las clases:

import java.io.Serializable;
import java.util.ArrayList;

import Cartas.Cartas;
import Cartas.Mazo;
import Cartas.Palos;

public class Jugador implements Serializable {

public String nombre;
public int escoba=0;
public int sietes=0;
public int oros=0;
public int sieteOro=0;
public int cartas=0;
public int puntos=0;
protected boolean estado;
public ArrayList<Cartas> mazo_jugador = new ArrayList<>(); // Mazo donde juntara las cartas que levanta
public ArrayList<Cartas> cartasEnMano = new ArrayList<>(); //Cartas que va a tener en la mano


public Jugador (String nombre){
this.nombre=nombre;
this.puntos=0;
this.escoba=0;
//this.estado=true;

}

public int getPuntos() {
return this.puntos;
}

public void setPuntos() {
this.puntos++;
}
public void sieteOro() {
for (int i=0;i<mazo_jugador.size();i++) {
//mazo_jugador.get(i).getPalo();
if (mazo_jugador.get(i).numero==7 && mazo_jugador.get(i).getPalo().equals(Palos.ORO)) {
this.puntos++;


}
}
}


public void sietes() {
for (int i=0;i<mazo_jugador.size();i++) {
if(mazo_jugador.get(i).numero==7) {
this.sietes++;
}
}
if (this.sietes>=2) {
this.puntos++;
}
}


public void agregarCarta(Cartas carta){
if (carta!=null) {
cartasEnMano.add(carta); //Cuando reparten agrega carta a cartasEnMano (3 cartas)
}
}


public String getNombre() {
return nombre;
}

public void escoba() {
this.puntos++;// TODO Auto-generated method stub

}


}



import java.rmi.RemoteException;
import java.util.ArrayList;
import java.rmi.Remote;


import Cartas.Cartas;
import Cartas.Mazo;
import Cartas.Palos;
import Modelo.Jugador;
import ar.edu.unlu.rmimvc.observer.ObservableRemoto;

public class Juego extends ObservableRemoto implements IJuego{

 


public ArrayList<Jugador> jugadores = new ArrayList<>(); //Lista de jugadores
public static ArrayList<Cartas> mesa = new ArrayList<>(); //Cartas en mesa
public Mazo mazoCarta = new Mazo(); //Mazo
private static int jugadorActual=0;
//private int jugadorMano=0;
public static int ronda=0;
private int estado;
public static final int INICIANDO_JUEGO = 0;
public static final int JUGANDO = 1; //Controladores de estado
public static final int FINALIZADO = 2;
public static int contador=0;
public static int contador2=0;
public static int reparte=0;






public Juego() {
estado=INICIANDO_JUEGO;
jugadorActual = 0;
ronda = 0;
//notificarObservadores(1);
}

@Override
public void iniciar() throws RemoteException {
estado=INICIANDO_JUEGO;
jugadorActual=0;
ronda=0;
notificarObservadores(1);
}


@Override
public void jugando() throws RemoteException { //Para cuando este jugando
int cont=1;
estado=JUGANDO;
repartirMesa();
repartirJugadores();
jugadorActual=0;
ronda=0;
notificarObservadores(4);
}


@Override
public void agregarJugador (String nombre) throws RemoteException {

jugadores.add(new Jugador(nombre));
notificarObservadores(2);
}

@Override
public ArrayList<Jugador> getJugadores() throws RemoteException{
return jugadores;
}

public ArrayList<Cartas> getMesa() throws RemoteException{
return mesa;
}

}


import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Cartas.Cartas;
import Modelo.IJuego;
import Modelo.Juego;
import Modelo.Jugador;
import Vista.ControlVista;
import Vista.VistaConsola;
import Vista.VistaGrafica;
import ar.edu.unlu.rmimvc.cliente.IControladorRemoto;
import ar.edu.unlu.rmimvc.observer.IObservableRemoto;

 


public class ControladorJuego implements IControladorRemoto {

public static final int INICIANDO_JUEGO = Juego.INICIANDO_JUEGO;
public static final int JUGANDO = Juego.JUGANDO; // Controladores de estado
public static final int FINALIZADO = Juego.FINALIZADO;
public static int eleccionVista;



private IJuego miJuego;
private ControlVista miVista;

public ControladorJuego(ControlVista miVista/*, Juego juego*/) {
//this.miJuego = juego;
this.miVista = miVista;
//juego.addObserver(this);

}

public void agregarJugador(String nombre) throws RemoteException {
miJuego.agregarJugador(nombre);
}

public static void iniciarJuego() throws RemoteException{
//miJuego.addObserver(this);
//miJuego.iniciar();
}




public static void main(String args[]) throws RemoteException {
//vistaPrincipal();
/*System.out.println("Elige vista");
System.out.println("");
System.out.println("1. Vista consola");
System.out.println("2. Vista grafica");

Scanner sc = new Scanner(System.in);
int eleccionVista = sc.nextInt();

if (eleccionVista==1) {
Juego jue = new Juego();
ControlVista vista = new VistaConsola();
ControladorJuego c = new ControladorJuego(vista);
jue.iniciar();}

else {
if(eleccionVista==2) {
Juego jue= new Juego();
ControlVista vista = new VistaGrafica();
ControladorJuego c = new ControladorJuego(vista);
jue.iniciar();



}
}*/
}



public String getJugadores() throws RemoteException {
return miJuego.mostrarJugadores();

}

public ArrayList<Cartas> getMesa() throws RemoteException {
return miJuego.getMesa();
}

public void mostrarJugadores() throws RemoteException {
miVista.mostrarJugadores();
//miVista.menu();
}

public void mostrarJugador() throws RemoteException {
miVista.mostrarJugador();
miVista.menuJugador();
}

public String getCartasMesa() throws RemoteException {
return miJuego.mostrarMesa();
}

public String getCartasEnMano(Jugador j) throws RemoteException{
return miJuego.mostrarCartasEnMano(j);
}

public void mostrarCartasEnMano() throws RemoteException {
System.out.println("Cartas en mano");
miVista.mostrarCartasEnMano();
}

public void mostrarMesa() throws RemoteException {
System.out.println("Cartas en mesa");
miVista.mostrarMesa();
}

public void tirarCarta(int op, Jugador j) throws RemoteException{
miJuego.tirarCarta(op, j);

}

public void seleccionarCartasMesa(int op, Jugador j) throws RemoteException {
miJuego.seleccionarCartasMesa(op, j);
}

public void seleccionarCartasMazo(int op, Jugador j) throws RemoteException{
miJuego.seleccionarCartasMazo(op, j);
}

public String mostrarCartasEnMano(Jugador j) throws RemoteException{
return miJuego.mostrarCartasEnMano(j);
}

public Jugador getJugador()throws RemoteException {
return miJuego.getJugador();
}

public void turnosJugador() throws RemoteException {
miJuego.turnosJugador();
}

public int mostrarContador() throws RemoteException{
return miJuego.mostrarContador();
}

public void devolverCartasMesa(Jugador j) throws RemoteException {
miJuego.devolverCartasMesa(j);
}

public void devolverCartasMazo(Jugador j)throws RemoteException {
miJuego.devolverCartasMazo(j);
}

public boolean controlCartaJugadores() throws RemoteException {
return miJuego.controlCartaJugadores();
}

public void verificarCartas() throws RemoteException{
miJuego.verificarCartas();
}



public void getMesa(Jugador j) throws RemoteException {
miJuego.agarrarMesa(j);

}

@Override
public void actualizar(IObservableRemoto modelo, Object queCambio) throws RemoteException{
int cambio = (int) queCambio;
switch (cambio) {
case 1:
//miVista.menu();
break;
case 2:
System.out.println("Jugador agregado con exito");
break;
case 3:
break;
case 4:
break;
}}


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.Scanner;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

import Controlador.ControladorJuego;
import Modelo.Juego;
import Modelo.Jugador;
//import Modelo.Jugador;




public class VistaGrafica extends JFrame implements ControlVista{

private JPanel contentPane;
private JTextField txtAgregarJugador;
private JButton boton1;
private JButton boton2;
private static JPanel panel;
private static JPanel panel2;
private static JTextArea textArea;
private static ControladorJuego miControl;
private static Juego miJuego;
private static int indice=0;
private static int indice2=0;
private static int r=0;
private static int r2=0;
private static JFrame frame;
private JLabel turno;
public Image fondo;





public void menu() throws RemoteException{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400, 50, 700, 500);
frame.setTitle("Escoba de 15");
frame.setLayout(null);
JPanel contentPane = new JPanel();
contentPane.setBounds(0,0,700,500);
contentPane.setBackground(Color.black);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setVisible(true);

frame.getContentPane().add(contentPane);



panel = new JPanel();
panel.setBounds(0,0,700, 500);
panel.setBackground(Color.LIGHT_GRAY);
panel.setBorder(new EmptyBorder(5, 5, 5, 5));




JLabel imagenMenu = new JLabel("MENU");
imagenMenu.setFont(new Font("Curlz MT",Font.PLAIN,70));
imagenMenu.setBounds(250,20,200,200);
imagenMenu.setForeground(Color.pink);
contentPane.add(imagenMenu);

JLabel imagenCartas = new JLabel();
imagenCartas.setBounds(0,300,200,200);
ImageIcon imagen3 = new ImageIcon("cartas2.jpg");
imagenCartas.setIcon(new ImageIcon(imagen3.getImage().getScaledInstance(imagenCartas.getWidth(),imagenCartas.getHeight(),Image.SCALE_SMOOTH)));
//contentPane.add(imagenCartas);






panel2 = new JPanel();
panel2.setBounds(0,0,700,500);
panel2.setBackground(Color.pink);
panel2.setBorder(new EmptyBorder(5, 5, 5, 5));



JTextField txtAgregarJugador = new JTextField();
//txtAgregarJugador.setBounds(new Rectangle(0, 0, 25, 23));
//txtAgregarJugador.setEditable(true);
txtAgregarJugador.setBounds(250, 200, 179, 33);
txtAgregarJugador.setHorizontalAlignment(SwingConstants.CENTER);
txtAgregarJugador.setBackground(new Color(192, 192, 192));
//txtAgregarJugador.setEnabled(false);
txtAgregarJugador.setFont(new Font("Arial", Font.ITALIC, 13));
txtAgregarJugador.setText("Nombre jugador");
txtAgregarJugador.setToolTipText("Agregar jugador");
txtAgregarJugador.setColumns(10);
contentPane.add(txtAgregarJugador);


JButton boton1 = new JButton("Agregar jugador");
//boton1.setForeground(new Color(255, 0, 255));
boton1.setBackground(new Color(218, 112, 214));
boton1.setBounds(new Rectangle(250, 250, 179, 31));
//boton1.setFont(new Font("Trebuchet MS", Font.PLAIN, 11));
contentPane.setLayout(null);
contentPane.add(boton1);
boton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try {
miControl.agregarJugador(txtAgregarJugador.getText());
txtAgregarJugador.setText(null);
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}


}


// textArea.setText(txtAgregarJugador.getText()+"");



});

textArea = new JTextArea(12,30);
//textArea.setForeground(new Color(255, 105, 180));
//textArea.setToolTipText("mostrarJugadores");
//textArea.setBounds(0,0, 100, 100);
textArea.setEditable(false);
//contentPane.add(textArea);

JButton boton2 = new JButton("Iniciar juego");
boton2.setBackground(new Color(218, 112, 214));
//boton2.setForeground(new Color(255, 0, 255));
boton2.setBounds(550, 400, 108, 33);
contentPane.add(boton2);
boton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.setVisible(false);
frame.setBounds(400, 50, 700, 600);
frame.setContentPane(panel);
frame.setTitle("Jugando");
frame.setVisible(true);
panel.setVisible(true);
panel.setLayout(null);

try {
miControl.jugando() ;
menuJugador();
mostrarMesa();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}


});

frame.setVisible(true);



}






public void menuJugador() throws RemoteException {
JLabel cartaNum = new JLabel();
cartaNum.setBounds(420,250,120,120);


ImageIcon imagen = new ImageIcon("tapa.jpg");
JLabel btn = new JLabel();
btn.setBounds(270,350,120,180);

turno = new JLabel("Turno de: "+miControl.getJugador().getNombre());

turno.setBounds(0,0,200,20);
panel.add(turno);

JButton boton = new JButton("Siguiente");
boton.setBounds(420,360,100,30);
boton.setBackground(new Color(218, 112, 214));


JButton boton3 = new JButton("Tirar");
boton3.setBounds(420,410,100,30);
boton3.setBackground(new Color(218, 112, 214));

JButton boton4 = new JButton("Agrupar");
boton4.setBounds(420,460,100,30);
boton4.setBackground(new Color(218, 112, 214));

JButton boton5 = new JButton("Formar 15");
boton5.setBounds(540,410,100,30);
boton5.setBackground(Color.magenta);








btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));

panel.add(btn);
panel.add(boton);
panel.add(boton3);
panel.add(boton4);
panel.add(boton5);
panel.add(cartaNum);

turno.setText("Turno de: "+miControl.getJugador().getNombre());
boton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (indice < miControl.getJugador().cartasEnMano.size()) {
r=indice;
ImageIcon imagen = new ImageIcon(miControl.getJugador().cartasEnMano.get(indice)+".jpg");
cartaNum.setText("Carta numero: "+ indice);
btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));
indice++;

} else {
indice=0;
r=0;

}
}

catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
} );

boton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
miControl.tirarCarta(r,miControl.getJugador());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
indice=0;
r=0;
cartaNum.setText("");
try {
turno.setText("Turno de: "+miControl.getJugador().getNombre());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ImageIcon imagen = new ImageIcon("tapa.jpg");
btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));


}




});

boton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
miControl.seleccionarCartasMazo(r, miControl.getJugador());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
indice=0;
r=0;
cartaNum.setText("");
/*ImageIcon imagen = new ImageIcon("tapa.jpg");
btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));
miControl.verificarCartas();
turno.setText("Turno de: "+miControl.getJugador().getNombre());*/
}
});
boton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon imagen = new ImageIcon("tapa.jpg");
btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));
try {
miControl.verificarCartas();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
turno.setText("Turno de: "+miControl.getJugador().getNombre());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}});


};
public void mostrarJugadores(){
System.out.println("todavia nada");
};


public void mostrarMesa() throws RemoteException {

JLabel cartaNum = new JLabel();
cartaNum.setBounds(0,100,120,120);

ImageIcon imagen2 = new ImageIcon(miControl.getMesa().get(indice2)+".jpg");
JLabel btn2 = new JLabel();
btn2.setBounds(270,20,120,180);

JButton boton5 = new JButton("Siguiente");
boton5.setBounds(420,70,100,30);
boton5.setBackground(new Color(218, 112, 214));


JButton boton6 = new JButton("Agrupar");
boton6.setBounds(420,120,100,30);
boton6.setBackground(new Color(218, 112, 214));

btn2.setIcon(new ImageIcon(imagen2.getImage().getScaledInstance(btn2.getWidth(),btn2.getHeight(),Image.SCALE_SMOOTH)));

panel.add(btn2);
panel.add(boton5);
panel.add(boton6);
boton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (indice2 < miControl.getMesa().size()) {
r2=indice2;
ImageIcon imagen2 = new ImageIcon(miControl.getMesa().get(indice2)+".jpg");
cartaNum.setText("Carta numero: "+ indice2);
btn2.setIcon(new ImageIcon(imagen2.getImage().getScaledInstance(btn2.getWidth(),btn2.getHeight(),Image.SCALE_SMOOTH)));
indice2++;
} else {
indice2=0;
r2=0;
}
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}



}
});

boton6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*ImageIcon imagen2 = new ImageIcon("tapa.jpg");
btn2.setIcon(new ImageIcon(imagen2.getImage().getScaledInstance(btn2.getWidth(),btn2.getHeight(),Image.SCALE_SMOOTH)));*/
try {
miControl.seleccionarCartasMesa(r2, miControl.getJugador());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
indice2=0;
r2=0;
}
});
}



import java.rmi.RemoteException;

import Controlador.ControladorJuego;

public interface ControlVista {
void menu() throws RemoteException;
void setControlador(ControladorJuego controlador);
void menuJugador() throws RemoteException;
void mostrarJugadores() throws RemoteException ;
void mostrarMesa() throws RemoteException ;
void mostrarCartasEnMano() ;
void mostrarJugador() ;
void menuCartasAgrupadas();
void menuNoforman15();
void jugadorAgregado();
void menuSumarPuntos();
void iniciar() throws RemoteException ;



}


public interface IJuego extends IObservableRemoto {

void iniciar() throws RemoteException;

void jugando() throws RemoteException;

void agregarJugador(String nombre) throws RemoteException;

ArrayList<Jugador> getJugadores() throws RemoteException;

int getEstado() throws RemoteException;

void finaliza() throws RemoteException;

void repartirJugadores() throws RemoteException;

void repartirMesa() throws RemoteException ;

String mostrarMesa() throws RemoteException;

String mostrarCartasEnMano(Jugador j) throws RemoteException ;

void tirarCarta(int op, Jugador j) throws RemoteException;

 


boolean controlCartaJugadores() throws RemoteException;

String mostrarJugadores() throws RemoteException;

void turnosJugador() throws RemoteException;

Jugador getJugador() throws RemoteException;

int jugadorActual() throws RemoteException;

void seleccionarCartasMesa(int op, Jugador j) throws RemoteException;

void seleccionarCartasMazo(int op, Jugador j) throws RemoteException;

int mostrarContador() throws RemoteException ;

void verificarCartas() throws RemoteException;

void devolverCartasMesa(Jugador j) throws RemoteException;

void devolverCartasMazo(Jugador j) throws RemoteException;

int getCartaActual() throws RemoteException;

void agarrarMesa(Jugador j) throws RemoteException;

void getOros() throws RemoteException;

void getContarCartas()throws RemoteException ;

void contarPuntos() throws RemoteException;

String mostrarGanador() throws RemoteException;

boolean consultarMazo() throws RemoteException;

void actualizarARepartirCartas() throws RemoteException;

ArrayList<Cartas> getMesa() throws RemoteException;

}

import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import Modelo.IJuego;
import Modelo.Juego;
import ar.edu.unlu.rmimvc.RMIMVCException;
import ar.edu.unlu.rmimvc.Util;
import ar.edu.unlu.rmimvc.servidor.Servidor;

public class AppServidor {

public static void main(String[] args) throws RemoteException {
ArrayList<String> ips = Util.getIpDisponibles();
String ip = (String) JOptionPane.showInputDialog(
null,
"Seleccione la IP en la que escuchará peticiones el servidor", "IP del servidor",
JOptionPane.QUESTION_MESSAGE,
null,
ips.toArray(),
null
);
String port = (String) JOptionPane.showInputDialog(
null,
"Seleccione el puerto en el que escuchará peticiones el servidor", "Puerto del servidor",
JOptionPane.QUESTION_MESSAGE,
null,
null,
8888
);

Juego modelo = new Juego();
System.out.println("Juego creado");
Servidor servidor = new Servidor(ip, Integer.parseInt(port));
try {
servidor.iniciar(modelo);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RMIMVCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


import java.util.ArrayList;



import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import Controlador.ControladorJuego;
import Vista.ControlVista;
import Vista.VistaGrafica;
import ar.edu.unlu.rmimvc.RMIMVCException;
import ar.edu.unlu.rmimvc.cliente.Cliente;
import ar.edu.unlu.rmimvc.Util;
import Modelo.IJuego;
import Modelo.Juego;




//import cliente.Cliente;

public class AppCliente {

public IJuego miJuego;

public static void main(String[] args) throws RemoteException {
ArrayList<String> ips = Util.getIpDisponibles();;
String ip = (String) JOptionPane.showInputDialog(
null,
"Seleccione la IP en la que escuchará peticiones el cliente", "IP del cliente",
JOptionPane.QUESTION_MESSAGE,
null,
ips.toArray(),
null
);
String port = (String) JOptionPane.showInputDialog(
null,
"Seleccione el puerto en el que escuchará peticiones el cliente", "Puerto del cliente",
JOptionPane.QUESTION_MESSAGE,
null,
null,
9999
);
String ipServidor = (String) JOptionPane.showInputDialog(
null,
"Seleccione la IP en la corre el servidor", "IP del servidor",
JOptionPane.QUESTION_MESSAGE,
null,
null,
null
);
String portServidor = (String) JOptionPane.showInputDialog(
null,
"Seleccione el puerto en el que corre el servidor", "Puerto del servidor",
JOptionPane.QUESTION_MESSAGE,
null,
null,
8888
);
ControlVista vista = new VistaGrafica();
ControladorJuego controlador = new ControladorJuego(vista);
Cliente c = new Cliente(ip, Integer.parseInt(port), ipServidor, Integer.parseInt(portServidor));
vista.setControlador(controlador);
vista.iniciar();
try {
c.iniciar(controlador);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RMIMVCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}




Claramente las interfaces tienen metodos que no escribi porque sino se haria muy larga la publicacion y el problema puntual esta en agregarjugador
12  Programación / Java / Ayuda con rmi y mvc! en: 9 Marzo 2021, 17:34 pm
Hola! buen dia! Estoy haciendo un juego y tengo problemas al implementar RMI. Cuando quiero agregar un jugador a traves del boton 1,(clase vistaGrafica) me muestra el Showmessagedialog sin texto y se congela todo. Nose que estoy haciendo mal, Si alguien me puede ayudar se lo agradeceria. Este es el codigo:

Código
  1. import java.rmi.RemoteException;
  2. import java.util.ArrayList;
  3. import java.rmi.Remote;
  4. import Cartas.Cartas;
  5. import Cartas.Mazo;
  6. import Cartas.Palos;
  7. import Modelo.Jugador;
  8. import ar.edu.unlu.rmimvc.observer.ObservableRemoto;
  9.  
  10. public class Juego extends ObservableRemoto implements IJuego{
  11.  
  12.  
  13.  
  14.  
  15. public ArrayList<Jugador> jugadores = new ArrayList<>();
  16.  
  17.  
  18. public Juego() {
  19. }
  20.  
  21.  
  22. @Override
  23. public void agregarJugador (String nombre) throws RemoteException {
  24. jugadores.add(new Jugador(nombre));
  25. notificarObservadores(2);
  26. }



Código
  1. package Controlador;
  2.  
  3. import java.rmi.RemoteException;
  4.  
  5. import Modelo.IJuego;
  6. import Modelo.Juego;
  7. import Modelo.Jugador;
  8. import Vista.ControlVista;
  9. import Vista.VistaGrafica;
  10. import ar.edu.unlu.rmimvc.cliente.IControladorRemoto;
  11. import ar.edu.unlu.rmimvc.observer.IObservableRemoto;
  12.  
  13.  
  14.  
  15.  
  16. public class ControladorJuego implements IControladorRemoto {
  17.  
  18.  
  19.  
  20. private static IJuego miJuego;
  21. private ControlVista miVista;
  22.  
  23. public ControladorJuego(ControlVista miVista) {
  24. this.miVista = miVista;
  25.  
  26. }
  27.  
  28. public void agregarJugador(String nombre) throws RemoteException {
  29. miJuego.agregarJugador(nombre);
  30. }
  31.  
  32. public void actualizar(IObservableRemoto modelo, Object queCambio) throws RemoteException{
  33. int cambio = (int) queCambio;
  34. switch (cambio) {
  35. case 1:
  36. miVista.menu();
  37. break;
  38. case 2:
  39. this.miVista.jugadorAgregado();
  40. break;
  41. }
  42. }
  43.  
  44. @Override
  45. public <T extends IObservableRemoto> void setModeloRemoto(T modeloRemoto) throws RemoteException {
  46. this.miJuego = (IJuego) modeloRemoto;
  47.  
  48.  
  49. }
  50. }



Código
  1. package Vista;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.Font;
  7. import java.awt.Rectangle;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.rmi.RemoteException;
  11.  
  12. import javax.swing.*;
  13. import javax.swing.border.EmptyBorder;
  14.  
  15. import Controlador.ControladorJuego;
  16. import Modelo.Juego;
  17. import Modelo.Jugador;
  18.  
  19.  
  20.  
  21.  
  22. public class VistaGrafica extends JFrame implements ControlVista{
  23.  
  24. private JPanel contentPane;
  25. private JTextField txtAgregarJugador;
  26. private JButton boton1;
  27. private JButton boton2;
  28. private static JPanel panel;
  29. private static ControladorJuego miControl;
  30. private static Juego miJuego;
  31. private static int indice=0;
  32. private static int indice2=0;
  33. private static int r=0;
  34. private static int r2=0;
  35. private static JFrame frame;
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42. public void menu() throws RemoteException{
  43. frame = new JFrame();
  44. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  45. frame.setBounds(400, 50, 700, 500);
  46. frame.setTitle("Escoba de 15");
  47. frame.setLayout(null);
  48. JPanel contentPane = new JPanel();
  49. contentPane.setBounds(0,0,700,500);
  50. contentPane.setBackground(Color.black);
  51. contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  52. contentPane.setVisible(true);
  53.  
  54. frame.getContentPane().add(contentPane);
  55.  
  56.  
  57.  
  58. panel = new JPanel();
  59. panel.setBounds(0,0,700, 500);
  60. panel.setBackground(Color.LIGHT_GRAY);
  61. panel.setBorder(new EmptyBorder(5, 5, 5, 5));
  62.  
  63.  
  64. panel2 = new JPanel();
  65. panel2.setBounds(0,0,700,500);
  66. panel2.setBackground(Color.pink);
  67. panel2.setBorder(new EmptyBorder(5, 5, 5, 5));
  68.  
  69.  
  70.  
  71. JTextField txtAgregarJugador = new JTextField();
  72. txtAgregarJugador.setBounds(250, 200, 179, 33);
  73. txtAgregarJugador.setHorizontalAlignment(SwingConstants.CENTER);
  74. txtAgregarJugador.setBackground(new Color(192, 192, 192));
  75. txtAgregarJugador.setText("Nombre jugador");
  76. txtAgregarJugador.setColumns(10);
  77.  
  78.  
  79. JButton boton1 = new JButton("Agregar jugador");
  80. boton1.setBackground(new Color(218, 112, 214));
  81. boton1.setBounds(new Rectangle(250, 250, 179, 31));
  82. contentPane.setLayout(null);
  83. contentPane.add(txtAgregarJugador);
  84. contentPane.add(boton1);
  85. boton1.addActionListener(new ActionListener() {
  86. public void actionPerformed(ActionEvent e) {
  87. try {
  88. miControl.agregarJugador(txtAgregarJugador.getText());
  89. } catch (RemoteException e1) {
  90. // TODO Auto-generated catch block
  91. e1.printStackTrace();
  92. }
  93.  
  94. }
  95.  
  96.  
  97.  
  98. });
  99.  
  100.  
  101. frame.setVisible(true);
  102.  
  103.  
  104.  
  105. }
  106.  
  107. public void jugadorAgregado() throws RemoteException {
  108. JOptionPane.showMessageDialog(null, "Jugador agregado con exito");
  109. };
  110.  
  111. @Override
  112. public void setControlador(ControladorJuego controlador) {
  113. this.miControl = controlador;
  114.  
  115. };
  116.  
  117. public void iniciar() throws RemoteException {
  118. menu();
  119. }
  120. }



Código
  1. import java.rmi.RemoteException;
  2. import java.util.ArrayList;
  3.  
  4. import javax.swing.JOptionPane;
  5.  
  6. import Modelo.Juego;
  7. import ar.edu.unlu.rmimvc.RMIMVCException;
  8. import ar.edu.unlu.rmimvc.Util;
  9. import ar.edu.unlu.rmimvc.servidor.Servidor;
  10.  
  11. public class AppServidor {
  12.  
  13. public static void main(String[] args) throws RemoteException {
  14. ArrayList<String> ips = Util.getIpDisponibles();
  15. String ip = (String) JOptionPane.showInputDialog(
  16. null,
  17. "Seleccione la IP en la que escuchará peticiones el servidor", "IP del servidor",
  18. JOptionPane.QUESTION_MESSAGE,
  19. null,
  20. ips.toArray(),
  21. null
  22. );
  23. String port = (String) JOptionPane.showInputDialog(
  24. null,
  25. "Seleccione el puerto en el que escuchará peticiones el servidor", "Puerto del servidor",
  26. JOptionPane.QUESTION_MESSAGE,
  27. null,
  28. null,
  29. 8888
  30. );
  31.  
  32. Juego modelo = new Juego();
  33. Servidor servidor = new Servidor(ip, Integer.parseInt(port));
  34. try {
  35. servidor.iniciar(modelo);
  36. } catch (RemoteException e) {
  37. // TODO Auto-generated catch block
  38. e.printStackTrace();
  39. } catch (RMIMVCException e) {
  40. // TODO Auto-generated catch block
  41. e.printStackTrace();
  42. }
  43. }
  44. }



Código
  1. import java.util.ArrayList;
  2.  
  3.  
  4.  
  5. import java.rmi.RemoteException;
  6. import java.util.ArrayList;
  7.  
  8. import javax.swing.JOptionPane;
  9. import Controlador.ControladorJuego;
  10. import Vista.ControlVista;
  11. import Vista.VistaGrafica;
  12. import ar.edu.unlu.rmimvc.RMIMVCException;
  13. import ar.edu.unlu.rmimvc.cliente.Cliente;
  14. import ar.edu.unlu.rmimvc.Util;
  15. import Modelo.IJuego;
  16. import Modelo.Juego;
  17.  
  18.  
  19.  
  20.  
  21. //import cliente.Cliente;
  22.  
  23. public class AppCliente {
  24.  
  25. public static IJuego miJuego;
  26.  
  27. public static void main(String[] args) throws RemoteException {
  28. ArrayList<String> ips = Util.getIpDisponibles();;
  29. String ip = (String) JOptionPane.showInputDialog(
  30. null,
  31. "Seleccione la IP en la que escuchará peticiones el cliente", "IP del cliente",
  32. JOptionPane.QUESTION_MESSAGE,
  33. null,
  34. ips.toArray(),
  35. null
  36. );
  37. String port = (String) JOptionPane.showInputDialog(
  38. null,
  39. "Seleccione el puerto en el que escuchará peticiones el cliente", "Puerto del cliente",
  40. JOptionPane.QUESTION_MESSAGE,
  41. null,
  42. null,
  43. 9999
  44. );
  45. String ipServidor = (String) JOptionPane.showInputDialog(
  46. null,
  47. "Seleccione la IP en la corre el servidor", "IP del servidor",
  48. JOptionPane.QUESTION_MESSAGE,
  49. null,
  50. null,
  51. null
  52. );
  53. String portServidor = (String) JOptionPane.showInputDialog(
  54. null,
  55. "Seleccione el puerto en el que corre el servidor", "Puerto del servidor",
  56. JOptionPane.QUESTION_MESSAGE,
  57. null,
  58. null,
  59. 8888
  60. );
  61.  
  62. ControlVista vista = new VistaGrafica();
  63. ControladorJuego controlador = new ControladorJuego(vista);
  64. Cliente c = new Cliente(ip, Integer.parseInt(port), ipServidor, Integer.parseInt(portServidor));
  65. vista.setControlador(controlador);
  66. vista.iniciar();
  67. try {
  68. c.iniciar(controlador);
  69. } catch (RemoteException e) {
  70. // TODO Auto-generated catch block
  71. e.printStackTrace();
  72. } catch (RMIMVCException e) {
  73. // TODO Auto-generated catch block
  74. e.printStackTrace();
  75. }
  76. }
  77. }

MOD: Agregadas etiquetas GeSHi.
13  Programación / Java / java.lang.NoClassDefFoundError Ayuda! en: 8 Marzo 2021, 22:19 pm
Hola! Buenas tardes! me sale el error Error: java.lang.NoClassDefFoundError Alguien sabe cual puede ser la causa y como solucionarlo?
14  Programación / Java / Error con arraylist en: 5 Marzo 2021, 17:33 pm
Hola buenas tardes, me sale el siguiente error:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 1


Cuando ejecuto este codigo:

public void menuJugador() {
JLabel cartaNum = new JLabel();
cartaNum.setBounds(420,250,120,120);


ImageIcon imagen = new ImageIcon(miControl.getJugador().cartasEnMano.get(indice)+".jpg");
JLabel btn = new JLabel();
btn.setBounds(270,350,120,180);

JLabel turno = new JLabel("Turno de: "+miControl.getJugador().getNombre());
turno.setBounds(0,0,200,20);
panel.add(turno);


JButton boton = new JButton("Siguiente");
boton.setBounds(420,360,100,30);


JButton boton3 = new JButton("Tirar");
boton3.setBounds(420,410,100,30);

JButton boton4 = new JButton("Agrupar");
boton4.setBounds(420,460,100,30);



btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));
panel.add(btn);
panel.add(boton);
panel.add(boton3);
panel.add(boton4);
panel.add(cartaNum);
boton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (indice < miControl.getJugador().cartasEnMano.size()) {
r=indice;
ImageIcon imagen = new ImageIcon(miControl.getJugador().cartasEnMano.get(indice)+".jpg");
cartaNum.setText("Carta numero: "+ indice);
btn.setIcon(new ImageIcon(imagen.getImage().getScaledInstance(btn.getWidth(),btn.getHeight(),Image.SCALE_SMOOTH)));
indice++;

} else {
indice=0;
r=0;
}

}

} );

boton3.addActionListener(new ActionListener() { //al presionar este boton salta el error
public void actionPerformed(ActionEvent e) {
miControl.tirarCarta(r,miControl.getJugador()); ¿
indice=0;
r=0;


}




});

------------------------------------------------------------------------------------------------------------------------------------------


public void tirarCarta( int op, Jugador j) {
//op va a ser la carta a tirar y jugador va a ser el jugador que la tira
mesa.add(j.cartasEnMano.get(op)); //mesa es un arrayList y cartas en mano es un arraylist que
esta en la clase Jugador
j.cartasEnMano.remove(j.cartasEnMano.get(op));


}


Si alguien me puede ayudar se lo agradeceria
15  Programación / Java / java.lang.UnsupportedClassVersionError en: 17 Febrero 2021, 23:31 pm
Hola, estoy tratando de compilar un codigo y me sale el siguiente error:

Error: LinkageError occurred while loading main class Menu
java.lang.UnsupportedClassVersionError: Menu (class file version 58.65535) was compiled with preview features that are unsupported. This version of the Java Runtime only recognizes preview features for class file version 59.65535

Nose como hacer para solucionarlo, alguien podria ayudarme?

Muchas gracias
16  Programación / Java / Error occurred during initialization of boot layer en: 10 Febrero 2021, 21:00 pm
Hola.Me sale el error "Package jdk.internal.jimage in both module java.base and module jrt.fs" cuando quiero ejecutar este codigo y nose porque:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;

import net.miginfocom.swing.MigLayout;
import java.awt.CardLayout;
import javax.swing.JTextArea;

public class Menu extends JFrame {

   private JPanel contentPane;
   private JTextField txtAgregarJugador;
   private JButton boton1;
   private JPanel panel;
   static ArrayList<String> vectorNombres = new ArrayList<String>();

   /**
    * Launch the application.
    */
   public static void main(String[] args) {
      /*EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {*/
               Menu frame = new Menu();
               frame.setVisible(true);
            /*} catch (Exception e) {
               e.printStackTrace();
            }
         }
      });*/
      //elementosVector();
   }

   public static void elementosVector() {
      vectorNombres.add("Carta 1");
      vectorNombres.add("Carta 2");
      vectorNombres.add("Carta 3");
      vectorNombres.add("Carta 4");
   }
   /**
    * Create the frame.
    */
   public Menu() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setBounds(200, 200, 634, 460);
      contentPane = new JPanel();
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);
     
      txtAgregarJugador = new JTextField();
      txtAgregarJugador.setBounds(new Rectangle(0, 0, 25, 23));
      txtAgregarJugador.setBounds(122, 28, 179, 33);
      txtAgregarJugador.setHorizontalAlignment(SwingConstants.CENTER);
      txtAgregarJugador.setBackground(new Color(192, 192, 192));
      txtAgregarJugador.setEnabled(false);
      txtAgregarJugador.setFont(new Font("Arial", Font.ITALIC, 13));
      txtAgregarJugador.setText("Nombre jugador");
      txtAgregarJugador.setToolTipText("Agregar jugador");
      txtAgregarJugador.setColumns(10);
     
      boton1 = new JButton("Agregar jugador");
      boton1.setForeground(new Color(255, 0, 255));
      boton1.setBackground(new Color(218, 112, 214));
      boton1.setBounds(new Rectangle(122, 85, 179, 31));
      boton1.setFont(new Font("Trebuchet MS", Font.PLAIN, 11));
      contentPane.setLayout(null);
      contentPane.add(txtAgregarJugador);
      contentPane.add(boton1);
     
      JTextArea textArea = new JTextArea();
      textArea.setBackground(new Color(255, 245, 238));
      textArea.setForeground(new Color(255, 105, 180));
      textArea.setToolTipText("mostrarJugadores");
      textArea.setBounds(10, 263, 419, 185);
      contentPane.add(textArea);
     
      JButton boton2 = new JButton("Iniciar juego");
      boton2.setBackground(new Color(255, 0, 255));
      boton2.setForeground(new Color(255, 0, 255));
      boton2.setBounds(318, 219, 108, 33);
      contentPane.add(boton2);
     
      panel = new JPanel();
      panel.setBounds(0, 0, 436, 252);
      contentPane.add(panel);
     
      for(int i=0;i<vectorNombres.size();i++) {
          JButton btn = new JButton("");
          btn.setIcon(new ImageIcon(Class.class.getResource("C:\\Users\\54232\\Documents\\Cartas" + vectorNombres.get(i) + ".pjg")));
          panel.add(btn);
      }

   }
}

Si alguien puede ayudarme se lo agradeceria!
17  Programación / Programación General / Error en java en: 10 Febrero 2021, 20:58 pm
Hola! buenas tardes. Me sale el error "Package jdk.internal.jimage in both module java.base and module jrt.fs" cuando quiero ejecutar este codigo:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;

import net.miginfocom.swing.MigLayout;
import java.awt.CardLayout;
import javax.swing.JTextArea;

public class Menu extends JFrame {

   private JPanel contentPane;
   private JTextField txtAgregarJugador;
   private JButton boton1;
   private JPanel panel;
   static ArrayList<String> vectorNombres = new ArrayList<String>();

   /**
    * Launch the application.
    */
   public static void main(String[] args) {
      /*EventQueue.invokeLater(new Runnable() {
         public void run() {
            try {*/
               Menu frame = new Menu();
               frame.setVisible(true);
            /*} catch (Exception e) {
               e.printStackTrace();
            }
         }
      });*/
      //elementosVector();
   }

   public static void elementosVector() {
      vectorNombres.add("Carta 1");
      vectorNombres.add("Carta 2");
      vectorNombres.add("Carta 3");
      vectorNombres.add("Carta 4");
   }
   /**
    * Create the frame.
    */
   public Menu() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setBounds(200, 200, 634, 460);
      contentPane = new JPanel();
      contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
      setContentPane(contentPane);
      
      txtAgregarJugador = new JTextField();
      txtAgregarJugador.setBounds(new Rectangle(0, 0, 25, 23));
      txtAgregarJugador.setBounds(122, 28, 179, 33);
      txtAgregarJugador.setHorizontalAlignment(SwingConstants.CENTER);
      txtAgregarJugador.setBackground(new Color(192, 192, 192));
      txtAgregarJugador.setEnabled(false);
      txtAgregarJugador.setFont(new Font("Arial", Font.ITALIC, 13));
      txtAgregarJugador.setText("Nombre jugador");
      txtAgregarJugador.setToolTipText("Agregar jugador");
      txtAgregarJugador.setColumns(10);
      
      boton1 = new JButton("Agregar jugador");
      boton1.setForeground(new Color(255, 0, 255));
      boton1.setBackground(new Color(218, 112, 214));
      boton1.setBounds(new Rectangle(122, 85, 179, 31));
      boton1.setFont(new Font("Trebuchet MS", Font.PLAIN, 11));
      contentPane.setLayout(null);
      contentPane.add(txtAgregarJugador);
      contentPane.add(boton1);
      
      JTextArea textArea = new JTextArea();
      textArea.setBackground(new Color(255, 245, 238));
      textArea.setForeground(new Color(255, 105, 180));
      textArea.setToolTipText("mostrarJugadores");
      textArea.setBounds(10, 263, 419, 185);
      contentPane.add(textArea);
      
      JButton boton2 = new JButton("Iniciar juego");
      boton2.setBackground(new Color(255, 0, 255));
      boton2.setForeground(new Color(255, 0, 255));
      boton2.setBounds(318, 219, 108, 33);
      contentPane.add(boton2);
      
      panel = new JPanel();
      panel.setBounds(0, 0, 436, 252);
      contentPane.add(panel);
      
      for(int i=0;i<vectorNombres.size();i++) {
          JButton btn = new JButton("");
          btn.setIcon(new ImageIcon(Class.class.getResource("C:\\Users\\54232\\Documents\\Cartas" + vectorNombres.get(i) + ".pjg")));
          panel.add(btn);
      }

   }
}

Si alguien puede ayudarme se lo agradeceria.
18  Programación / Java / Mostrar cartas GUI en: 10 Febrero 2021, 06:15 am
Hola buenas tardes. Estoy haciendo un juego de cartas y necesito mostrar todas las cartas que tengo en un mazo y nosé como hacer. Los nombres de las cartas están cargados en un array. Por ejemplo: "2 de oro", "1 de espada". Necesito vincular el nombre con la imagen de la carta.
Si alguien me puede ayudar se lo agradecería mucho

[MOD] No esta permitido publicar el mismo post en distintos subforos. Seran borrados directamente.

Leer las Reglas del Foro.
19  Programación / Java / Problema con archivos en: 23 Octubre 2020, 01:34 am
Hola buenas tardes, estoy haciendo un programa en java con archivos, directorios, tengo que agregar el nombre de los archivos por teclado y validar que ese mismo nombre no exista en el directorio, para eso cree un array de archivos, donde guardo los nombres de los archivos y su correspondiente ubicacion.
El problema es que la validacion tira un resultado incorrecto cuando pongo dos archivos con el mismo nombre, no me tendria que dejar agregar el mismo nombre de archivo al array archi y sin embargo lo agrega igual,  si alguien me podria ayudar se lo agradeceria.

public class Archivo {

   String nombre;
   int longitud;
   String ubicacion;
   int bloqueInicial;
   int bloqueFinal;
   
   
   public void setNombre(String nombre) {
      this.nombre=nombre;
   }
   
   public void setLongitud(int l) {
      this.longitud=l;
   }
   
   public void setUbicacion(String ubicacion) {
      this.ubicacion=ubicacion;
   }
   
   public void setBloqueInicial(int bloque) {
      this.bloqueInicial=bloque;
   }
   
   public void setBloqueFinal(int bloque) {
      this.bloqueFinal=bloque;
   }
   
   public String getNombre() {
      return this.nombre;
   }
   
   public int getLongitud() {
   return this.longitud;
   }

    public String getUbicacion() {
    return this.ubicacion;
    }
   
    public int getBloqueInicial() {
       return this.bloqueInicial;
    }
   
    public int getBloqueFinal() {
       return this.bloqueFinal;
    }
-----------------------------------------------------------------------------------------

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Directorio {
  static File directorio;
  static File archivo;
  int bloqueS=0;
  static int iArchivo=0;

 static ArrayList<Archivo> archi = new ArrayList<>();
private Scanner nombre;
 

public void crearDirectorio () {
   
     directorio = new File("directorio2");
   directorio.mkdir();
}


public boolean verificar (String nombre) {
boolean t=true;

   for (int i=0; i<archi.size();i++) {
      if (archi.get(i).getNombre()==nombre) {
         t=false;
         System.out.println("es igual");
      }
   }
   return t;
}


public void agregarArchivo () {   //agrega el archivo al directorio y al array
   boolean c;
       for (int i=0; i<3;i++) {
      System.out.println("Ingrese nombre de archivo");
      Scanner nom= new Scanner(System.in);
      String nombre= nom.nextLine();
      c=verificar(nombre);
      if (c!=false) {
       try {
      archivo = new File(directorio,nombre);
      archivo.createNewFile();
   
      Archivo aux = new Archivo();
     aux.setNombre(archivo.getName());
     aux.setUbicacion(archivo.getAbsolutePath());
     aux.setLongitud((int)archivo.length());
     archi.add(aux);
    
   } catch (IOException e) {
      e.printStackTrace();
   }
      
   } else
      System.out.println("El nombre con ese archivo ya existe");
   
   }
}

public static void mostrarArchivos() {
   System.out.println("                           FAT                             ");
   for (int i=0; i<archi.size(); i++) {
    System.out.println(" ");
   System.out.println("**********************************************************************");
   System.out.println("     Numero de bloque: "+i);
   //System.out.println("     Bloque sig: "+archi.get(i).bloqueSig);
   System.out.println("     Longitud: "+archi.get(i).longitud);
   System.out.println("     Nombre de archivo:   "+archi.get(i).getNombre());
   //System.out.println("     Estado bloque: "+archi.get(i).getEstado());
   System.out.println("     Ubicacion en disco: "+archi.get(i).getUbicacion());
    System.out.println("***********************************************************************");
   System.out.println(" ");
   
 
       
   }
   }

public static void main(String[] args) {
   Directorio d = new Directorio();
   d.crearDirectorio();
   d.agregarArchivo();
   d.mostrarArchivos();
    }
   
   
}
   
20  Programación / Java / Problemas con directorio en: 16 Octubre 2020, 00:39 am
Hola buenas noches, tengo un problema al mostrar la longitud del directorio, aunque haya archivos dentro de el me muestra que la longitud es 0 y nose porque, si alguien me puede ayudar se lo agradecería.

import java.io.*;
import java.util.ArrayList;

public class Directorio {
static File directorio;


public void crearDirectorio () {

try {
File directorio = new File("directorio");
directorio.mkdir();
File archivo = new File(directorio,"archivo.txt");
File archivo2 = new File(directorio,"archivo2.txt");
archivo.createNewFile();
archivo2.createNewFile();
System.out.println(directorio.length()); //aqui quiero mostrar la longitud del directorio, tiene dos archivos dentro
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



public static void mostrarDirectorio() {
File mostrar = new File(directorio.getAbsolutePath());
String[] archivos = mostrar.list();
for (int i=0; i<archivos.length; i++) {
System.out.println(archivos);
}
}




public static void main(String[] args) {
Directorio d = new Directorio();
d.crearDirectorio();
//d.mostrarDirectorio();
}


}
Páginas: 1 [2] 3 4
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines