|
Mostrar Temas
|
Páginas: [1] 2 3
|
1
|
Programación / Scripting / Ayuda para crear inputs dinámicos!
|
en: 30 Julio 2022, 22:13 pm
|
Hola! Soy principiante en javascript. Quiero crear un código que al apretar un boton me cree clones de un select y un botón para eliminar el clon que elija y nose como hacerlo! Si alguien me puede guiar se lo agradecería mucho
|
|
|
2
|
Programación / Java / Ayudaaaaa. Exception in thread "main" java.lang.NullPointerException en java
|
en: 13 Junio 2022, 03:28 am
|
Buenas noches. Estoy trabajando en un juego con MVC y rmi. Lo estoy haciendo con vista en consola y me sale el error cuando quiero agregar un jugador al array de jugadores desde la clase VistaConsola: Exception in thread "main" java.lang.NullPointerException at Vista.VistaConsola.menu(VistaConsola.java:37) at Vista.VistaConsola.iniciar(VistaConsola.java:196) at Controlador.ControladorJuego.<init>(ControladorJuego.java:53) at AppCliente.main(AppCliente.java:66) Les dejo mis clases: public class Juego extends ObservableRemoto implements IJuego{ public ArrayList<Jugador> jugadores = new ArrayList<>(); public ArrayList<Jugador> jugador public Juego() { jugadorActual = 0; ronda = 1; } estado=INICIANDO_JUEGO; jugadorActual=0; ronda=1; notificarObservadores(1); } jugadores.add(new Jugador(nombre)); notificarObservadores(2); } } public class VistaConsola implements ControlVista { private static ControladorJuego miControl; System. out. println("-------------------------"); System. out. println("- Configuración -"); System. out. println("-------------------------"); System. out. println("- M E N U -"); System. out. println("-------------------------"); System. out. println("- 1 - Agregar Jugador -"); System. out. println("- 2 - Mostrar Jugadores -"); System. out. println("- 3 - Iniciar Juego -"); System. out. println("-------------------------"); Scanner a = new Scanner (System. in); int i = a.nextInt(); switch (i) { case 1: miControl.agregarJugador(nombreJugador()); break; case 2: miControl.mostrarJugadores(); break; case 3: miControl.jugando(); break; } } System. out. println("Ingrese nombre de jugador "); Scanner sc = new Scanner (System. in); nom = sc.nextLine(); return nom; } ArrayList<Jugador> jugadores = miControl.getJugadores(); System. out. println(jugadores ); } menu(); } public void setControlador (ControladorJuego controlador ) throws RemoteException{ miControl = controlador; } } public class ControladorJuego implements IControladorRemoto ; private IJuego miJuego; private ControlVista miVista; this.miVista = miVista; miVista.iniciar(); } miJuego.agregarJugador(nombre); } return miJuego.mostrarJugadores(); } int cambio = (int) queCambio; switch (cambio) { case 1: break; case 2: System. out. println("Jugador agregado con exito"); break; } } public interface ControlVista { } public class AppCliente { public IJuego miJuego; ArrayList <String > ips = Util. getIpDisponibles();; null, "Seleccione la IP en la que escuchará peticiones el cliente", "IP del cliente", null, ips.toArray(), null ); null, "Seleccione el puerto en el que escuchará peticiones el cliente", "Puerto del cliente", null, null, 9999 ); null, "Seleccione la IP en la corre el servidor", "IP del servidor", null, null, null ); null, "Seleccione el puerto en el que corre el servidor", "Puerto del servidor", null, null, 8888 ); ControlVista vista = new VistaConsola(); 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); // TODO Auto-generated catch block e.printStackTrace(); } catch (RMIMVCException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Si alguien me puede ayudar se lo agradeceria, no tengo idea de cual puede ser el error!
|
|
|
3
|
Programación / Java / Error con Spring boot! Ayuda
|
en: 17 Febrero 2022, 20:12 pm
|
Hola! Buenas tardes. Soy nueva con Spring y me aparecio este error: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-02-17 16:02:00.613 ERROR 21000 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of method inicio in mx.com.gm.ControladorInicio required a bean of type 'org.springframework.ui.Model' that could not be found. Action: Consider defining a bean of type 'org.springframework.ui.Model' in your configuration. Alguien sabe a que se debe? Les dejo mi codigo package mx.com.gm; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; @SpringBootApplication public class HolaSpringApplication { public static void main (String[] args ) { SpringApplication.run(HolaSpringApplication.class, args); } } package mx.com.gm; import java.util.ArrayList; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; import mx.com.gm.dominio.Persona; @Controller public class ControladorInicio { private PersonaDao personadao; @GetMapping("/") @Autowired public String inicio (Model model ) { String saludar = "Adios mundo con thymeleaf"; var personas = personadao.findAll(); model.addAttribute("personas", personas); return "index"; } } package mx.com.gm.dominio; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; //import lombok.Data; //@Data private static final long SerialVersionUID= 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) return nombre; } public void setNombre (String nombre ) { this.nombre = nombre; } return apellido; } public void setApellido (String apellido ) { this.apellido = apellido; } return email; } public void setEmail (String email ) { this.email = email; } } package mx.com.gm; import org.springframework.data.repository.CrudRepository; import mx.com.gm.dominio.Persona; public interface PersonaDao extends CrudRepository<Persona, Integer>{ } mi pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>mx.com.gm</groupId> <artifactId>HolaMundoSpringData</artifactId> <version>1.0</version> <name>HolaMundoSpringData</name> <description>HolaMundo con Spring</description> <properties> <java.version>13</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> application.properti: spring.datasource.url=jdbc:mysql://localhost:3306/spring?zeroDateTimeBehavior=convertToNull&useSSL=false&useTimezone=true&serverTimezone=UTC&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123777 spring. datasource. driver-class -name =com. mysql. cj. jdbc. Driverspring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.properties.hibernate.format_sql=true logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <tr th:each="persona : ${personas}"> <td th:text="${persona.nombre}">Nombre </td> <td th:text="${persona.apellido}">Apellido </td> <td th:text="${persona.email}">Email </td>
|
|
|
4
|
Programación / Java / Ayuda para leer archivo de objetos!
|
en: 13 Noviembre 2021, 17:30 pm
|
Hola a todos! Tengo problemas para leer un archivo de objetos, si alguien me puede ayudar se lo agradeceria! Asi guardo los objetos: ganadores.add(j); if( f.exists()){ salida.writeObject(ganadores); salida.close(); } else { salida.writeObject(ganadores); salida.close(); } y asi los leo: //ObjectInputStream entrada=null; int i=0; try { ganadores = (ArrayList<Jugador>) entrada.readObject(); entrada.close(); try { while (true) { System. out. println(ganadores. get(i ). getNombre()); i++; ganadores = (ArrayList<Jugador>) entrada.readObject(); } return ganadoress; } Clase miObjectOutputStream: @Override protected void writeStreamHeader () throws IOException { //nada } super(); } // TODO Auto-generated constructor stub super(fileOutputStream); }
|
|
|
5
|
Programación / Java / Ayuda con ObjectOutputStream!
|
en: 30 Agosto 2021, 18:21 pm
|
Hola. Buenas tardes, estoy haciendo un ejercicio con persistencia. Y tengo problemas para grabar los objetos en un archivo. Voy agregando los objetos de a uno, ya que tengo un menu. Cuando agrego el primer objeto se lee bien, pero cuando agrego el segundo ya no se lee ninguno. Nose que estoy haciendo mal public class MiObjectOutputStream extends ObjectOutputStream{ //clase q hereda de objectoutputstream para no sobreescribir la cabecera public void writeStreamHeader() { //nada } super(); } // TODO Auto-generated constructor stub super(fileOutputStream); } } //Los metodos guardar y recuperar estan en otra clase if( f.exists()){ salida.writeObject(j); salida.close(); } else { salida.writeObject(j); salida.close(); } } while (true) { Jugador j = ( Jugador) entrada.readObject(); System. out. println(j. getNombre()); } } finally { try { entrada.close(); } }
MOD: Etiqueta GeSHi
|
|
|
6
|
Programación / Java / Ayuda con persistencia!
|
en: 18 Agosto 2021, 15:04 pm
|
Hola, buen dia! Tengo un problema al implementar persistencia. Lo que quiero hacer es guardar en un archivo los ganadores de un juego y ni se llega a crear el archivo. No entiendo que es lo que estoy haciendo mal.
En la clase Juego tengo este metodo:
private Persistencia p;
public Jugador mostrarGanador()throws RemoteException { //devuelve el ganador int mayor=0; Jugador j = null; for (int i=0; i<jugadores.size();i++) { if (jugadores.get(i).getPuntos() > mayor) { mayor=jugadores.get(i).getPuntos(); j=jugadores.get(i); } } try { p.guardar(j); //Este es el metodo guardar de la clase Persistencia, aqui } catch (IOException e) { quiero guardar el ganador // TODO Auto-generated catch block e.printStackTrace(); } return j; }
Clase persistencia:
public class Persistencia { public void guardar (Jugador j) throws IOException { ObjectOutputStream salida= new ObjectOutputStream(new FileOutputStream("jugador.objeto")); salida.writeObject(j); salida.close(); } public Jugador recuperar() throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream entrada = new ObjectInputStream(new FileInputStream("jugador.objeto")); Jugador j = (Jugador ) entrada.readObject(); entrada.close(); return j;
}
}
|
|
|
7
|
Programación / Java / remove no funciona
|
en: 17 Marzo 2021, 00:33 am
|
Hola buenas noches. Tengo un problema para eliminar elementos de un arraylist. Cuando llamo al metodo remove no funciona. No borra el elemento deseado. try { if (indice < miControl.jugador(nombreJ).cartasEnMano.size()) { r=indice; ImageIcon(miControl. jugador(nombreJ ). 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; } } // TODO Auto-generated catch block e1.printStackTrace(); } } }); try { miControl.tirarCarta(r,miControl.jugador(nombreJ)); indice=0; r=0; } else { } } //op va a ser la carta a tirar y jugador va a ser el jugador que la tira mesa.add(j.cartasEnMano.get(op)); j.cartasEnMano.remove(j.cartasEnMano.get(op)); }
Si alguien me puede ayudar se lo agradeceria MOD: Etiqueta GeSHi
|
|
|
8
|
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
|
|
|
9
|
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: 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<>(); public Juego() { } @Override jugadores.add(new Jugador(nombre)); notificarObservadores(2); }
package Controlador; import java.rmi.RemoteException; import Modelo.IJuego; import Modelo.Juego; import Modelo.Jugador; import Vista.ControlVista; import Vista.VistaGrafica; import ar.edu.unlu.rmimvc.cliente.IControladorRemoto; import ar.edu.unlu.rmimvc.observer.IObservableRemoto; public class ControladorJuego implements IControladorRemoto { private static IJuego miJuego; private ControlVista miVista; public ControladorJuego(ControlVista miVista) { this.miVista = miVista; } miJuego.agregarJugador(nombre); } int cambio = (int) queCambio; switch (cambio) { case 1: miVista.menu(); break; case 2: this.miVista.jugadorAgregado(); break; } } @Override public <T extends IObservableRemoto > void setModeloRemoto (T modeloRemoto ) throws RemoteException { this.miJuego = (IJuego) modeloRemoto; } }
package Vista; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.rmi.RemoteException; import javax.swing.*; import javax.swing.border.EmptyBorder; import Controlador.ControladorJuego; import Modelo.Juego; import Modelo.Jugador; public class VistaGrafica extends JFrame implements ControlVista { 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; frame. setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);frame.setBounds(400, 50, 700, 500); frame.setTitle("Escoba de 15"); frame.setLayout(null); contentPane.setBounds(0,0,700,500); contentPane. setBackground(Color. black);contentPane.setVisible(true); frame.getContentPane().add(contentPane); panel.setBounds(0,0,700, 500); panel. setBackground(Color. LIGHT_GRAY); panel2.setBounds(0,0,700,500); panel2. setBackground(Color. pink); txtAgregarJugador.setBounds(250, 200, 179, 33); txtAgregarJugador. setBackground(new Color(192, 192, 192));txtAgregarJugador.setText("Nombre jugador"); txtAgregarJugador.setColumns(10); boton1. setBackground(new Color(218, 112, 214));boton1. setBounds(new Rectangle(250, 250, 179, 31));contentPane.setLayout(null); contentPane.add(txtAgregarJugador); contentPane.add(boton1); try { miControl.agregarJugador(txtAgregarJugador.getText()); // TODO Auto-generated catch block e1.printStackTrace(); } } }); frame.setVisible(true); } JOptionPane. showMessageDialog(null, "Jugador agregado con exito"); }; @Override public void setControlador(ControladorJuego controlador) { this.miControl = controlador; }; menu(); } }
import java.rmi.RemoteException; import java.util.ArrayList; import javax.swing.JOptionPane; 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 { ArrayList <String > ips = Util. getIpDisponibles();null, "Seleccione la IP en la que escuchará peticiones el servidor", "IP del servidor", null, ips.toArray(), null ); null, "Seleccione el puerto en el que escuchará peticiones el servidor", "Puerto del servidor", null, null, 8888 ); Juego modelo = new Juego(); Servidor servidor = new Servidor (ip, Integer. parseInt(port ));try { servidor.iniciar(modelo); // 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 static IJuego miJuego; ArrayList <String > ips = Util. getIpDisponibles();;null, "Seleccione la IP en la que escuchará peticiones el cliente", "IP del cliente", null, ips.toArray(), null ); null, "Seleccione el puerto en el que escuchará peticiones el cliente", "Puerto del cliente", null, null, 9999 ); null, "Seleccione la IP en la corre el servidor", "IP del servidor", null, null, null ); null, "Seleccione el puerto en el que corre el servidor", "Puerto del servidor", 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); // TODO Auto-generated catch block e.printStackTrace(); } catch (RMIMVCException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
MOD: Agregadas etiquetas GeSHi.
|
|
|
|
|
|
|