Autor Tema: Java JTextField JButton JPanel JTextArea implements ActionListener setLayout  (Leído 5101 veces)

ESOJ

  • Intermedio
  • ***
  • APR2.COM
  • Mensajes: 143
    • Ver Perfil
Hola. Aquí dejo un programa realizado con los conocimientos adquiridos gracias al curso.
Me gustaria que alguien más avanzado que yo lo echara un vistazo a ver en qué lo puedo mejorar.

Los textos de los temas no los pongo porque ocuparia mucho espacio.

Gracias
Código: [Seleccionar]
public class Inicio {
 
    public static void main(String[] args) {
       
           
           
             new TeoriaOEjercicios();}
        }

Código: [Seleccionar]
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.*;

/**
 * Write a description of class prueba1 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class TeoriaOEjercicios extends gg implements  ActionListener{
    private JTextField pO;
    private JButton  p1;
    private JButton  p2;
    private JPanel pS,pC;
    private JTextArea p3;
    private String textoCentro="    \n          Objetivos \n\n    Java es uno de los lenguajes de programación más utilizados en el mundo,"+
            "enmarcado en el grupo de lenguajes \n orientados a objetos. Este curso permite aprender los fundamentos de la programación Java"+
            " y de la programación orientada\n a objetos."+"\n\n      Destinatarios\n\n    Cualquier persona con interés en aprender fundamentos de"+
            " programación Java con vistas al desarrollo de aplicaciones.\n Es recomendable, aunque no imprescindible, que el alumno tenga conocimientos básicos de"+
            " algoritmia y de algún otro \nlenguaje de programación.\n\n          Contenidos\n\n INTRODUCCIÓN A JAVA. QUÉ ES JAVA. INSTALACIÓN Y PRIMEROS PASOS CON "+
            "JAVA.\n OBJETOS, CLASES Y CONSTRUCTORES EN JAVA. INSTANCIAS. TIPOS DE DATOS.\n SINTAXIS BÁSICA Y CONDICIONALES EN JAVA. OPERADORES.\n EL API DE JAVA."+
            "BIBLIOTECAS DE CLASES. ¿QUÉ ES Y PARA QUÉ SIRVE EL API DE JAVA?\n CREAR UN PROGRAMA CON JAVA. ABSTRACCIÓN. MODULARIZACIÓN. MÉTODOS. MAIN.\n ESTRUCTURAS DE"+
            " REPETICIÓN O BUCLES, COLECCIONES DE OBJETOS Y RECORRIDOS.\n HERENCIA EN JAVA. ¿QUÉ ES LA HERENCIA EN PROGRAMACIÓN ORIENTADA A OBJETOS?\n PROGRESAR COMO"+
            " PROGRAMADORES JAVA: SWING, GESTIÓN DE ERRORES Y OTROS\n\n          Duración\n\n 150 horas de dedicación efectiva, incluyendo lecturas, estudio y ejercicios.\n"+
            "\n\n         Dirección, modalidades y certificados\n\n El curso está dirigido por Mario Rodríguez Rancel, Jefe de Proyectos de aprenderaprogramar.com."+
            "Se oferta bajo las \nmodalidades web (gratuito), con tickets de soporte y tutorizado on-line (material + soporte). A los alumnos que"+" sigan \nel curso tutorizado"+
            " on-line y cumplan el programa de trabajo se les expedirá certificado acreditativo de la realización del curso.";
     
    /**
     * Constructor for objects of class prueba1
     */
    public TeoriaOEjercicios ()
    {   
       super("                 CURSO DE JAVA de APRENDER A PROGRAMAR");
       
      sur();
      centro();
    oeste();
add(pS,BorderLayout.SOUTH);
add(pC,BorderLayout.CENTER);
add(pO,BorderLayout.WEST);
       
    }
     public void oeste(){
        pO = new JTextField("          ");
        pO.setBackground(Color.green);
        pO.setBorder(BorderFactory.createLineBorder(Color.blue));
        setVisible(true);
        pO.setEditable(false);
    }
public void centro(){
        pC = new JPanel(null); 
        pC.setLayout(new FlowLayout());
        p3 = new JTextArea(textoCentro,100,1);

        pC.setBorder(BorderFactory.createLineBorder(Color.red));
        p3.setEditable(false);
        pC.add(p3);
    }
    public void sur(){
        pS = new JPanel(null); 
        pS.setLayout(new GridLayout(1,2));

        p1 = new JButton("Teoria  ");
        p1.addActionListener(this);
        p2 = new JButton("Ejercicios   ");
        p2.addActionListener(this);
        pS.setBorder(BorderFactory.createLineBorder(Color.green));
        pS.add(p1);pS.add(p2);
    }
    public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("Teoria  ") ) {
            new Teoria();}
        if(e.getActionCommand().equals("Ejercicios   ") ) {
            new Ejercicios();} 

    }
   }

Código: [Seleccionar]
import java.awt.*;
import javax.swing.*;
/**
 * Write a description of class prueba1 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
abstract class gg extends JFrame
{
    private JTextField pE;
    String titulo="";
 
    /**
     * Constructor for objects of class prueba1
     */
    public  gg (String titulo)
    { 
        super(titulo);
       
        setLayout(new BorderLayout(0,0));
        setLocation(350, 50);
        setResizable(false);
        setVisible(true);
        setSize(770,650);
           
        este();
       
        add(pE,BorderLayout.EAST);
    }   


    public void este(){
        pE = new JTextField("          ");
        pE.setBackground(Color.blue);
        pE.setBorder(BorderFactory.createLineBorder(Color.red));
        setVisible(true);
        pE.setEditable(false);
    }
 }

Código: [Seleccionar]
public class Ejercicios
{
    String[] temas1 = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17",
        "18","19","20","21","22","23","24","25"};
     String[] temas2 = {"26","27","28","29","30","31","32","33","34","35","36","37","38","39","40",
         "41","42","43","44","45","46","47","48","49","50"};
    String[] temas3 = {"51","52","53"};
     String[] temas4 = {""};
    String [ ] capitulos = {
                "                         1-25",
                "                         26-50",
                "                         51-53",
               
            };
   
    public Ejercicios()
    {
     new ii(temas1,temas2,temas3,temas4,capitulos,3,3);
    }

   
}

Código: [Seleccionar]
import java.io.IOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
/**
 * Write a description of class prueba1 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */

public class Temas extends gg implements  ActionListener
{
    JTextField jt[];
    private JButton  boton[];
    private JPanel pC,pO,pN;
    private int x,numeroDeTemas;
    String[] temas ;
    /**
     * Constructor for objects of class prueba1
     */
    public  Temas(String[] temas,int numeroDeTemas,int x )
    { 
        super("                 CURSO DE JAVA de APRENDER A PROGRAMAR");
       
        this.temas=temas;
        this.x=x;
        this.numeroDeTemas=numeroDeTemas;
        centro();
        oeste();
        este();
        norte();

        add(pC,BorderLayout.CENTER);
        add(pO,BorderLayout.WEST);
        add(pN,BorderLayout.NORTH);
    }

    public void centro (){
        pC = new JPanel(null);
        pC.setLayout(new GridLayout(25, 1));
        pC.setBorder(BorderFactory.createLineBorder(Color.red));
        pC.setBackground(Color.red);
        pC.setVisible(true);
        pC.setSize(510, 680);

        jt = new JTextField[25];
        for (int i=0; i<numeroDeTemas; i++)
        {   jt[i] = new JTextField("     "+temas[i]);
            jt[i].setEditable(false);
            jt[i].setBackground(Color.green);
            pC.add(jt[i]);
        }
    }         

    public void oeste(){
        pO = new JPanel(null); 
        pO.setLayout(new GridLayout(25,1));
        pO.setBorder(BorderFactory.createLineBorder(Color.red));
        pO.setBackground(Color.red);
        boton = new JButton[numeroDeTemas+1];
        for (int i=0; i<numeroDeTemas; i++)
        {   boton[i] = new JButton(""+(i+x));
            pO.add(boton[i]);
            boton[i].addActionListener(this); }
    } 

   
    public void norte(){
        JTextField b;
        pN = new JPanel(null);
        b = new JTextField("TEMAS "+x+"-"+ (x+(numeroDeTemas-1)));
        b.setVisible(true);
        b.setEditable(false);
        pN.add(b);
        pN.setLayout(new FlowLayout(FlowLayout.LEFT));
        pN.setVisible(true);
        pN.setBorder(BorderFactory.createLineBorder(Color.red));
        pN.setBackground(Color.red);
    }

    public void Archivo (String archivo){
        try {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + archivo);
        } catch (IOException a) {
            a.printStackTrace();
        }
    }

    public void actionPerformed(ActionEvent e){
        String ruta="C:/Users/Pc/Desktop/JAVA/PROGRAMAS/APRENDER A PROGRAMAR/TEXTOS/";
        int i=0;
        for (i=x; i<(x+25) ; i++){
            if(e.getActionCommand().equals(""+i) ) {
                Archivo(ruta+temas[i-x]+".rtf");}
               if(e.getActionCommand().equals(""+i) ) {
                Archivo(ruta+temas[i-x]+".txt");}

        }     
    } 
}


Código: [Seleccionar]
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
/**
 * Write a description of class prueba1 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class ii extends gg implements  ActionListener{

    private JPanel pO,pC,pN;
    private JTextArea p3,p4;
    private JTextField jt[];
    private JButton  boton[];
    String[] temas1={};String[] temas2={};String[] temas3={};String[] temas4={};
    String[] capitulos;
    int x=0;int y=0;
    public  ii(String[] temas1,String[] temas2,String[] temas3,String[] temas4,String[] capitulos,int x,int y)
    {   
        super("                 CURSO DE JAVA de APRENDER A PROGRAMAR");

        this.temas1= temas1;
        this.temas2= temas2;
        this.temas3= temas3;
        this.temas4= temas4;
        this.capitulos=capitulos;
        this.x=x;
        this.y=y;
        centro();
        oeste();
        norte();
        add(pN,BorderLayout.NORTH);
        add(pC,BorderLayout.CENTER);
        add(pO,BorderLayout.WEST);

    }

    public void norte(){
        JTextField b;
        pN = new JPanel(null);

        b = new JTextField(" TEMAS ");
        b.setFont(new Font("Arial", Font.BOLD, 31));

        pN.add(b);
        pN.setLayout(new FlowLayout());
        pN.setVisible(true);
        pN.setBackground(Color.red);
        b.setEditable(false);
    }

    public void oeste(){

        pO = new JPanel(null); 
        pO.setLayout(new GridLayout(x,1));
        pO.setBorder(BorderFactory.createLineBorder(Color.red));
        pO.setBackground(Color.red);
        boton = new JButton[x+1];
        for (int i=1; i<=x; i++)
        {   boton[i] = new JButton(""+i);
            boton[i].setFont(new Font("Arial", Font.ITALIC, 31));
            pO.add(boton[i]);
            boton[i].addActionListener(this); }
    } 

    public void centro (){

        pC = new JPanel(null);
        pC.setLayout(new GridLayout(x, 1));
        pC.setBorder(BorderFactory.createLineBorder(Color.red));
        pC.setBackground(Color.red);
        pC.setVisible(true);
        pC.setSize(510, 680);

        jt = new JTextField[x+1];
        for (int i=0; i<x; i++){

            jt[i] = new JTextField(capitulos[i]);
            jt[i].setEditable(false);
            jt[i].setBackground(Color.green);
            jt[i].setBorder(BorderFactory.createLineBorder(Color.black));
            jt[i].setFont(new Font("Arial", Font.BOLD, 31));

            pC.add(jt[i]);
        }
    }

    public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("1") ) {
            new Temas(temas1,25,1);}
        if(e.getActionCommand().equals("2") ) {
            new Temas(temas2,25,26);}
        if(e.getActionCommand().equals("3") ) {
            new Temas(temas3,y,51);}
        if(e.getActionCommand().equals("4") ) {
            new Temas(temas4,10,76);}

    }
}

Código: [Seleccionar]
/**
 * Write a description of class kkk here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Teoria   
{
    String[] temas1 = {"COMENTARIOS JAVA. CONCEPTO DE BLOQUE DE CÓDIGO","CONCEPTO DE OBJETOS Y CLASES EN JAVA. DEFINICIÓN DE INSTANCIA",
            "TIPOS DE DATOS (VARIABLES) EN JAVA","QUÉ ES UNA CLASE JAVA","MÉTODOS PROCEDIMIENTO (VOID) Y FUNCIÓN (RETURN)",
            "MÉTODOS EN JAVA CON Y SIN PARÁMETROS","MÉTODOS CONSULTORES (GET) Y MODIFICADORES (SET)",
            "ESTADO DE UN OBJETO","PARÁMETROS FORMALES Y PARÁMETROS ACTUALES","CONCEPTO Y FILOSOFÍA DE MÉTODOS Y CLASES EN JAVA",
            "SIGNATURA DE UN MÉTODO. INTERFAZ O INTERFACE","IMPRIMIR POR CONSOLA EN JAVA (SYSTEM.OUT). CONCATENAR CADENAS",
            "OPERADORES ARITMÉTICOS EN JAVA. EL OPERADOR % (MOD) O RESTO" ,"OPERADORES LÓGICOS PRINCIPALES EN JAVA",
            "ASIGNACIÓN Y ASIGNACIÓN COMPUESTA EN JAVA","ESTRUCTURA O ESQUEMA DE DECISIÓN EN JAVA. IF ELSE , IF ELSE IF",
            "CONDICIONAL DE SELECCIÓN SWITCH EN JAVA. EJEMPLO DE APLICACIÓN","VARIABLES LOCALES. SOBRECARGA DE NOMBRES",
            "CÓMO CREAR CONSTRUCTORES EN JAVA. EJERCICIOS EJEMPLOS RESUELTOS", "SOBRECARGA DE CONSTRUCTORES O MÉTODOS",
            "CLASES QUE UTILIZAN OBJETOS. RELACIÓN DE USO ENTRE CLASES. DIAGRAMAS DE CLASES",
            "PASO DE OBJETOS COMO PARÁMETROS A UN MÉTODO O CONSTRUCTOR EN JAVA",
            "LA SENTENCIA NEW COMO INVOCACIÓN DE UN CONSTRUCTOR EN JAVA",
            "LA CLASE VISTA COMO PAQUETE DE CÓDIGO.OBJETOS DEL MUNDO REAL Y ABSTRACTOS",
            "QUÉ ES Y PARA QUÉ SIRVE EL API DE JAVA",
        };
        String[] temas2 = {"ORGANIZACIÓN Y FORMA DE NOMBRAR LAS LIBRERÍAS DEL API DE JAVA",
                "IMPORTAR Y USAR CLASES DEL API DE JAVA. EJEMPLO CON LA CLASE MATH",
                "QUÉ ES UNA INTERFACE DE CLASE JAVA CONCEPTO",
                "ESTUDIANDO EL CONCEPTO DE MÉTODO JAVA. EL MÉTODO SUBSTRING DE LA CLASE STRING",
                "USAR MÉTODOS PARA EVITAR ERRORES. EJEMPLO", "ABSTRACCIÓN Y MODULARIZACIÓN EN JAVA",
                "UN EJEMPLO DE CÓDIGO JAVA BÁSICO. CREAR CLASES CON CAMPOS, CONSTRUCTOR Y MÉTODOS",
                "CONCEPTO O DEFINICIÓN DE MÉTODO INTERNO Y MÉTODO EXTERNO EN JAVA",
                "PALABRA CLAVE THIS EN JAVA. CONTENIDO NULL POR DEFECTO DE UN OBJETO",
                "CLASE CON EL MÉTODO MAIN: CLASE PRINCIPAL, INICIADORA O “PROGRAMA PRINCIPAL",
                "SINTAXIS Y CÓDIGO EJEMPLO DE USO DEL MÉTODO MAIN","PEDIR DATOS POR CONSOLA (TECLADO) EN JAVA",
                "CONCEPTO GENERAL DE BUCLE","BUCLE CON INSTRUCCIÓN WHILE EN JAVA. EJEMPLO USO DE BREAK",
                "BUCLE CON INSTRUCCIÓN DO … WHILE. EJEMPLO DE USO","EL DEBUGGER DE BLUEJ. DETENER UN PROGRAMA EN EJECUCIÓN",
                "PENSAR EN OBJETOS EN JAVA. UNA ENTRADA DE TECLADO COMO OBJETO",
                "EL MÉTODO EQUALS EN JAVA. DIFERENCIA ENTRE IGUALDAD E IDENTIDAD DE OBJETOS",
                "ASIGNACIÓN DE IGUALDAD CON TIPOS PRIMITIVOS Y OBJETOS",
                "COLECCIONES DE OBJETOS DE TAMAÑO VARIABLE. CONTENEDORES",
                "LA CLASE ARRAYLIST DEL API DE JAVA. LISTAS REDIMENSIONABLES",
                "EL FOR EXTENDIDO O BUCLES FOR EACH EN JAVA","TIPO ITERATOR Y MÉTODO ITERATOR EN JAVA",
                "TIPOS DE BUCLES O CICLOS EN JAVA (RESUMEN)","OBJETOS NULL Y JAVA.LANG.NULLPOINTEREXCEPTION",};
    String[] temas3 = {"AUTOBOXING Y UNBOXING","OBJETOS ANÓNIMOS",
        "ARRAYS, ARREGLOS O FORMACIONES EN JAVA",
    "CONVERSIÓN DE TIPOS DE DATOS EN JAVA",
    "GET Y REMOVE DE ARRAYLIST. EJEMPLO CONVERSIÓN DE TIPOS",
    "GENERAR NÚMEROS ALEATORIOS EN JAVA",
    "PALABRAS CLAVE STATIC Y FINAL. CONSTANTES EN JAVA",
    "PROYECTOS JAVA EN PAQUETES (PACKAGES)",
    "COPIAR ARRAYS Y COMPARAR ARRAYS. IDENTIDAD E IGUALDAD",
    "LA CLASE ARRAYS DEL API DE JAVA. EQUALS, COPYOF, FILL",
    "CONCEPTO DE INTERFAZ O INTERFACE JAVA. AMPLIACIÓN",
    "CONCEPTO DE POLIMORFISMO EN JAVA. ¿QUÉ ES",
    "TRANSFORMAR ARRAY EN UNA LISTA. MÉTODO ASLIST",
    "DOCUMENTAR PROYECTOS JAVA CON JAVADOC",
    "TIPOS ENUMERADOS (ENUM) EN JAVA",
    "ENUMERADOS CLASES CON CAMPOS Y CONSTRUCTORES. MÉTODOS VALUES",
    "MÉTODOS DE CLASE O STATIC FRENTE A MÉTODOS DE INSTANCIA",
    "QUÉ ES LA HERENCIA EN PROGRAMACIÓN ORIENTADA A OBJETOS",
    "JERARQUÍAS DE HERENCIA EN JAVA. SUPERCLASES Y SUBCLASES",
    "EJEMPLO DE HERENCIA EN JAVA. EXTENDS Y SUPER",
    "EJERCICIO RESUELTO DE HERENCIA SIMPLE EN JAVA",
    "TIPOS Y SUBTIPOS. POLIMORFISMO Y VARIABLES POLIMÓRFICAS",
    "CONVERSIÓN DE TIPOS. CASTING",
    "SOBREESCRIBIR MÉTODOS EN JAVA. MÉTODOS POLIMÓRFICOS",
    "EJERCICIO EJEMPLO RESUELTO CON HERENCIA"};
    String[] temas4 = {
        "USO DE SUPER PARA LLAMAR A MÉTODOS DE SUPERCLASE. EJEMPLO",
        "MODIFICADORES DE ACCESO JAVA PUBLIC, PRIVATE, PROTECTED",
        "SOBREESCRIBIR MÉTODOS TOSTRING Y EQUALS EN JAVA",
        "CLASES Y MÉTODOS ABSTRACTOS EN JAVA",
        "CLASES ABSTRACTAS EN EL API DE JAVA",
        "CONCEPTO DE INTERFACE Y HERENCIA MÚLTIPLE EN JAVA. IMPLEMENTS",
        "PARA QUÉ SIRVEN LAS INTERFACES EN JAVA",
        "IMPLEMENTAR UNA INTERFACE DEL API JAVA. EJEMPLO",
        "RESUMEN DE HERENCIA EN JAVA",
        "PROGRESAR COMO PROGRAMADORES JAVA"};
        String [ ] capitulos = {
                "                         1-25",
                "                         26-50",
                "                         51-75",
                "                         76-85",

            };
       
    public Teoria()
    {
     new ii(temas1,temas2,temas3,temas4,capitulos,4,25);
    }

   
}
« Última modificación: 15 de Marzo 2016, 17:35 por Alex Rodríguez »

Alex Rodríguez

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2050
    • Ver Perfil
Hola ESOJ

En primer lugar felicitarte porque se ve un código que demuestra conocimientos y que ha requerido dedicación. También se ve que estás trabajando bien con el diseño orientado a objetos.

Te comento algunos detalles

Nada más ver el código en un IDE salta una cosa a la vista: las clases no tienen nombres adecuados. Los nombres de las clases deben ser descriptivos del cometido de la clase o qué representa la clase. Además debe seguirse la convención de que los nombres de las clases comiencen por mayúsculas. Nombres como gg ó ii no dicen nada sobre el cometido de estas clases.

Lo mismo te ocurre con atributos y métodos. Todos los nombres deben ser autodescriptivos en la medida de lo posible. Nombres de método como este() no son autodescriptivos.

Nombres de atributos como pC,pO,pN tampoco son autodescriptivos

Las clases deben contener comentarios útiles. Por ejemplo

Código: [Seleccionar]
/**
 * Write a description of class prueba1 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */

no tiene ninguna utilidad.


Parece que estás usando espacios para centrar texto ¿? p1 = new JButton("Teoria  "); y  if(e.getActionCommand().equals("Teoria  ") )

parece que tienen unos espacios después de la palabra Teoria. Esto yo diría que es algo no recomendable, de hecho con facilidad hará que se incurra en inconsistencias (por ejemplo que cuando se haga el mantenimiento del programa quede en un sitio con un espacio más o menos que en otro sitio).

Hay otros sitios donde ocurre también esto.

Ya desde el punto de vista del usuario encuentro algunas cosas mejorables: las ventanas se abren una encima de otra y la de abajo queda oculta. Pareciera que se estuviera en la misma ventana (aunque en realidad se ha abierto una nueva). Quizás hiciera el programa más usable si cuando abres una ventana cierras la anterior e incluyes un botón o enlace "Volver" que permita cerrar la ventana actual y pasar a la anterior.


Saludos

ESOJ

  • Intermedio
  • ***
  • APR2.COM
  • Mensajes: 143
    • Ver Perfil
Hola de nuevo.

En primer lugar agradecerte el tiempo dedicado en revisar mi codigo y sobre todo tus correcciones.

He reecho el codigo siguiendo tus indicaciones. No he puesto comentarios porque ya seria mucho el espacio que ocuparia,pero tambien he tenido en cuenta tu consejo.

Llevo mes y medio con esto del Java.Antes habia visto algo de linux y hace mucho tiempo algo de Pascal.¿Que tal progreso llevo?

He vuelto a revisar el codigo y creo que asi quedaria mas claro y menos extenso:

Código: [Seleccionar]
public class Inicio {
 
    public static void main(String[] args) {
       
           
           
             new Portada();}
        }
Código: [Seleccionar]
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;

public class Portada extends JFramePrincipal implements  ActionListener
{
    private JButton[] botones;
    private JButton botonSurSalir,botonSurEmpezar;
    private String[] intro={"Objetivos:","            Java es uno de los lenguajes de programación más utilizados en el mundo,enmarcado en el grupo de lenguajes","         orientados a objetos. Este curso permite aprender los fundamentos de la programación Java y de la programación",
        "         orientada a objetos.","Destinatarios","            Cualquier persona con interés en aprender fundamentos de programación Java con vistas al desarrollo de aplicaciones",
        "         Es recomendable, aunque no imprescindible, que el alumno tenga conocimientos básicos de algoritmia y de algún","         otro \nlenguaje de programación","Contenidos:",
        "            INTRODUCCIÓN A JAVA. QUÉ ES JAVA. INSTALACIÓN Y PRIMEROS PASOS CON JAVA","            OBJETOS, CLASES Y CONSTRUCTORES EN JAVA. INSTANCIAS. TIPOS DE DATOS",
        "            SINTAXIS BÁSICA Y CONDICIONALES EN JAVA. OPERADORES,","            EL API DE JAVA.BIBLIOTECAS DE CLASES. ¿QUÉ ES Y PARA QUÉ SIRVE EL API DE JAVA","            CREAR UN PROGRAMA CON JAVA. ABSTRACCIÓN. MODULARIZACIÓN. MÉTODOS. MAIN.",
        "            ESTRUCTURAS DE REPETICIÓN O BUCLES, COLECCIONES DE OBJETOS Y RECORRIDOS","            HERENCIA EN JAVA. ¿QUÉ ES LA HERENCIA EN PROGRAMACIÓN ORIENTADA A OBJETOS?",
        "            PROGRESAR COMO PROGRAMADORES JAVA: SWING, GESTIÓN DE ERRORES Y OTROS","Duración:","            150 horas de dedicación efectiva, incluyendo lecturas, estudio y ejerciciosn",
            "Dirección, modalidades y certificados","            El curso está dirigido por Mario Rodríguez Rancel, Jefe de Proyectos de aprenderaprogramar.com.",
            "Se oferta bajo las \nmodalidades web (gratuito), con tickets de soporte y tutorizado on-line (material + soporte). A los alumnos que"+" sigan \nel curso tutorizado",
            " on-line y cumplan el programa de trabajo se les expedirá certificado acreditativo de la realización del curso."};
   
   
    public Portada ()
    {  super("hola");
               
                       
        PanelCentro ventanaCentro = new PanelCentro(intro,23);
        ventanaCentro.setBorder(BorderFactory.createLineBorder(Color.yellow));
        ventanaCentro.setBackground(Color.green);
        PanelSur ventanaSur = new PanelSur(2);
        botonSurSalir =new JButton("Salir");
        botonSurSalir.addActionListener(this);
        botonSurEmpezar =new JButton("Indice");
        botonSurEmpezar.addActionListener(this);
        ventanaSur.add(botonSurSalir);
        ventanaSur.add(botonSurEmpezar);
       
       
       
        add(ventanaCentro,BorderLayout.CENTER);
         add(ventanaSur,BorderLayout.SOUTH);
    }
   
        public void actionPerformed(ActionEvent e){
       if(e.getActionCommand().equals("Salir") ) {setVisible(false);}
       if(e.getActionCommand().equals("Indice") ) {setVisible(false);new GestorIndice();}
       
    }
}


Código: [Seleccionar]
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;

public class GestorIndice extends JFramePrincipal implements  ActionListener
{
    private JButton[] botones;
    private JButton botonSur;
    private String[] tituloTemas={};
    String [ ] capitulos = {
                "                         1-25",
                "                         26-50",
                "                         51-75",
                "                         76-85",};
   
    public GestorIndice ()
    {  super("hola");
               
        PanelOeste ventanaOeste = new PanelOeste();
        ventanaOeste.setLayout(new GridLayout(4,1));
        ventanaOeste.setBorder(BorderFactory.createLineBorder(Color.black));
        ventanaOeste.setBackground(Color.cyan);
       botones = new JButton[5];
        for (int i=1; i<=4; i++)

        {   botones[i] = new JButton(""+(i));
            ventanaOeste.add(botones[i]);
            botones[i].addActionListener(this);
        }
       
        PanelCentro ventanaCentro = new PanelCentro(capitulos,4);
       
        PanelSur ventanaSur = new PanelSur(1);
        botonSur =new JButton("Atras");
        ventanaSur.add(botonSur);
        botonSur.addActionListener(this);
       
        add(ventanaOeste,BorderLayout.WEST);
        add(ventanaCentro,BorderLayout.CENTER);
         add(ventanaSur,BorderLayout.SOUTH);
    }
   
        public void actionPerformed(ActionEvent e){
       if(e.getActionCommand().equals("Atras") ) {setVisible(false);new Portada();}
        if(e.getActionCommand().equals("1") ) {setVisible(false);new temas1a25();}
         if(e.getActionCommand().equals("2") ) {setVisible(false);new temas26a50();}
          if(e.getActionCommand().equals("3") ) {setVisible(false);new temas51a75();}
           if(e.getActionCommand().equals("4") ) {setVisible(false);new temas76a85();}
    }
}


Código: [Seleccionar]
public class temas76a85
{
  String[] temas76a85 = {
        "USO DE SUPER PARA LLAMAR A MÉTODOS DE SUPERCLASE. EJEMPLO",
        "MODIFICADORES DE ACCESO JAVA PUBLIC, PRIVATE, PROTECTED",
        "SOBREESCRIBIR MÉTODOS TOSTRING Y EQUALS EN JAVA",
        "CLASES Y MÉTODOS ABSTRACTOS EN JAVA",
        "CLASES ABSTRACTAS EN EL API DE JAVA",
        "CONCEPTO DE INTERFACE Y HERENCIA MÚLTIPLE EN JAVA. IMPLEMENTS",
        "PARA QUÉ SIRVEN LAS INTERFACES EN JAVA",
        "IMPLEMENTAR UNA INTERFACE DEL API JAVA. EJEMPLO",
        "RESUMEN DE HERENCIA EN JAVA",
        "PROGRESAR COMO PROGRAMADORES JAVA"};
    public temas76a85()
    {
        new GestorDeTemas(temas76a85,10,76);
    }

   
}

Código: [Seleccionar]
public class temas51a75
{
  String[] temas51a75 = {"AUTOBOXING Y UNBOXING","OBJETOS ANÓNIMOS",
        "ARRAYS, ARREGLOS O FORMACIONES EN JAVA",
    "CONVERSIÓN DE TIPOS DE DATOS EN JAVA",
    "GET Y REMOVE DE ARRAYLIST. EJEMPLO CONVERSIÓN DE TIPOS",
    "GENERAR NÚMEROS ALEATORIOS EN JAVA",
    "PALABRAS CLAVE STATIC Y FINAL. CONSTANTES EN JAVA",
    "PROYECTOS JAVA EN PAQUETES (PACKAGES)",
    "COPIAR ARRAYS Y COMPARAR ARRAYS. IDENTIDAD E IGUALDAD",
    "LA CLASE ARRAYS DEL API DE JAVA. EQUALS, COPYOF, FILL",
    "CONCEPTO DE INTERFAZ O INTERFACE JAVA. AMPLIACIÓN",
    "CONCEPTO DE POLIMORFISMO EN JAVA. ¿QUÉ ES",
    "TRANSFORMAR ARRAY EN UNA LISTA. MÉTODO ASLIST",
    "DOCUMENTAR PROYECTOS JAVA CON JAVADOC",
    "TIPOS ENUMERADOS (ENUM) EN JAVA",
    "ENUMERADOS CLASES CON CAMPOS Y CONSTRUCTORES. MÉTODOS VALUES",
    "MÉTODOS DE CLASE O STATIC FRENTE A MÉTODOS DE INSTANCIA",
    "QUÉ ES LA HERENCIA EN PROGRAMACIÓN ORIENTADA A OBJETOS",
    "JERARQUÍAS DE HERENCIA EN JAVA. SUPERCLASES Y SUBCLASES",
    "EJEMPLO DE HERENCIA EN JAVA. EXTENDS Y SUPER",
    "EJERCICIO RESUELTO DE HERENCIA SIMPLE EN JAVA",
    "TIPOS Y SUBTIPOS. POLIMORFISMO Y VARIABLES POLIMÓRFICAS",
    "CONVERSIÓN DE TIPOS. CASTING",
    "SOBREESCRIBIR MÉTODOS EN JAVA. MÉTODOS POLIMÓRFICOS",
    "EJERCICIO EJEMPLO RESUELTO CON HERENCIA"};
    public temas51a75()
    {
        new GestorDeTemas(temas51a75,25,51);
    }

   
}

Código: [Seleccionar]

public class temas26a50
{
String[] temas26a50 = {"ORGANIZACIÓN Y FORMA DE NOMBRAR LAS LIBRERÍAS DEL API DE JAVA",
                "IMPORTAR Y USAR CLASES DEL API DE JAVA. EJEMPLO CON LA CLASE MATH",
                "QUÉ ES UNA INTERFACE DE CLASE JAVA CONCEPTO",
                "ESTUDIANDO EL CONCEPTO DE MÉTODO JAVA. EL MÉTODO SUBSTRING DE LA CLASE STRING",
                "USAR MÉTODOS PARA EVITAR ERRORES. EJEMPLO", "ABSTRACCIÓN Y MODULARIZACIÓN EN JAVA",
                "UN EJEMPLO DE CÓDIGO JAVA BÁSICO. CREAR CLASES CON CAMPOS, CONSTRUCTOR Y MÉTODOS",
                "CONCEPTO O DEFINICIÓN DE MÉTODO INTERNO Y MÉTODO EXTERNO EN JAVA",
                "PALABRA CLAVE THIS EN JAVA. CONTENIDO NULL POR DEFECTO DE UN OBJETO",
                "CLASE CON EL MÉTODO MAIN: CLASE PRINCIPAL, INICIADORA O “PROGRAMA PRINCIPAL",
                "SINTAXIS Y CÓDIGO EJEMPLO DE USO DEL MÉTODO MAIN","PEDIR DATOS POR CONSOLA (TECLADO) EN JAVA",
                "CONCEPTO GENERAL DE BUCLE","BUCLE CON INSTRUCCIÓN WHILE EN JAVA. EJEMPLO USO DE BREAK",
                "BUCLE CON INSTRUCCIÓN DO … WHILE. EJEMPLO DE USO","EL DEBUGGER DE BLUEJ. DETENER UN PROGRAMA EN EJECUCIÓN",
                "PENSAR EN OBJETOS EN JAVA. UNA ENTRADA DE TECLADO COMO OBJETO",
                "EL MÉTODO EQUALS EN JAVA. DIFERENCIA ENTRE IGUALDAD E IDENTIDAD DE OBJETOS",
                "ASIGNACIÓN DE IGUALDAD CON TIPOS PRIMITIVOS Y OBJETOS",
                "COLECCIONES DE OBJETOS DE TAMAÑO VARIABLE. CONTENEDORES",
                "LA CLASE ARRAYLIST DEL API DE JAVA. LISTAS REDIMENSIONABLES",
                "EL FOR EXTENDIDO O BUCLES FOR EACH EN JAVA","TIPO ITERATOR Y MÉTODO ITERATOR EN JAVA",
                "TIPOS DE BUCLES O CICLOS EN JAVA (RESUMEN)","OBJETOS NULL Y JAVA.LANG.NULLPOINTEREXCEPTION",};

    public temas26a50 ()
    {
      new GestorDeTemas(temas26a50,25,26);
    }
}
   

Código: [Seleccionar]
public class temas1a25
{
  String[] temas1a25 = {"COMENTARIOS JAVA. CONCEPTO DE BLOQUE DE CÓDIGO","CONCEPTO DE OBJETOS Y CLASES EN JAVA. DEFINICIÓN DE INSTANCIA",
            "TIPOS DE DATOS (VARIABLES) EN JAVA","QUÉ ES UNA CLASE JAVA","MÉTODOS PROCEDIMIENTO (VOID) Y FUNCIÓN (RETURN)",
            "MÉTODOS EN JAVA CON Y SIN PARÁMETROS","MÉTODOS CONSULTORES (GET) Y MODIFICADORES (SET)",
            "ESTADO DE UN OBJETO","PARÁMETROS FORMALES Y PARÁMETROS ACTUALES","CONCEPTO Y FILOSOFÍA DE MÉTODOS Y CLASES EN JAVA",
            "SIGNATURA DE UN MÉTODO. INTERFAZ O INTERFACE","IMPRIMIR POR CONSOLA EN JAVA (SYSTEM.OUT). CONCATENAR CADENAS",
            "OPERADORES ARITMÉTICOS EN JAVA. EL OPERADOR % (MOD) O RESTO" ,"OPERADORES LÓGICOS PRINCIPALES EN JAVA",
            "ASIGNACIÓN Y ASIGNACIÓN COMPUESTA EN JAVA","ESTRUCTURA O ESQUEMA DE DECISIÓN EN JAVA. IF ELSE , IF ELSE IF",
            "CONDICIONAL DE SELECCIÓN SWITCH EN JAVA. EJEMPLO DE APLICACIÓN","VARIABLES LOCALES. SOBRECARGA DE NOMBRES",
            "CÓMO CREAR CONSTRUCTORES EN JAVA. EJERCICIOS EJEMPLOS RESUELTOS", "SOBRECARGA DE CONSTRUCTORES O MÉTODOS",
            "CLASES QUE UTILIZAN OBJETOS. RELACIÓN DE USO ENTRE CLASES. DIAGRAMAS DE CLASES",
            "PASO DE OBJETOS COMO PARÁMETROS A UN MÉTODO O CONSTRUCTOR EN JAVA",
            "LA SENTENCIA NEW COMO INVOCACIÓN DE UN CONSTRUCTOR EN JAVA",
            "LA CLASE VISTA COMO PAQUETE DE CÓDIGO.OBJETOS DEL MUNDO REAL Y ABSTRACTOS",
            "QUÉ ES Y PARA QUÉ SIRVE EL API DE JAVA",
        };
    public temas1a25()
    {
        new GestorDeTemas(temas1a25,25,1);
    }

   
}

Código: [Seleccionar]
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.io.IOException;
public class GestorDeTemas extends JFramePrincipal implements  ActionListener
{

    private JButton botonSur;
    private JButton[] botones;
    private String[] tituloTemas={};
    private int numeroBotones,inicioBotones;
   
    public GestorDeTemas (String [] tituloTemas,int numeroBotones,int inicioBotones)
    {  super("hola");
        this.tituloTemas=tituloTemas;
        this.numeroBotones=numeroBotones;
        this.inicioBotones=inicioBotones;
       
        PanelOeste ventanaOeste = new PanelOeste();
        ventanaOeste.setLayout(new GridLayout(numeroBotones,1));
        ventanaOeste.setBorder(BorderFactory.createLineBorder(Color.black));
        ventanaOeste.setBackground(Color.cyan);
        botones = new JButton[numeroBotones+inicioBotones];
        for (int i=inicioBotones; i<=numeroBotones+(inicioBotones-1); i++)

        {   botones[i] = new JButton(""+(i));
            ventanaOeste.add(botones[i]);
            botones[i].addActionListener(this);
        }

        PanelCentro ventanaCentro = new PanelCentro(tituloTemas,numeroBotones);
       
        PanelSur ventanaSur = new PanelSur(1);
        botonSur =new JButton("Atras");
        ventanaSur.add(botonSur);
        botonSur.addActionListener(this);
       
        add(ventanaOeste,BorderLayout.WEST);
        add(ventanaCentro,BorderLayout.CENTER);
         add(ventanaSur,BorderLayout.SOUTH);
    }

    public void Archivo (String archivo){
        try {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + archivo);
        } catch (IOException a) {
            a.printStackTrace();
        }
    }

    public void actionPerformed(ActionEvent e){
        String ruta="C:/Users/Pc/Desktop/JAVA/PROGRAMAS/APRENDER A PROGRAMAR/TEXTOS/";
       int i=0;
        for (i=inicioBotones; i<inicioBotones+numeroBotones; i++){
            if(e.getActionCommand().equals(""+i) ) {
                Archivo(ruta+tituloTemas[i-inicioBotones]+".rtf");}

        }
        if(e.getActionCommand().equals("Atras") ) {setVisible(false);new GestorIndice();}
    }
}


Código: [Seleccionar]
import java.awt.BorderLayout;
import javax.swing.JFrame ;

public class JFramePrincipal extends JFrame
{   
    String titulo="";
   
    /**
     * Constructor for objects of class prueba1
     */
    public  JFramePrincipal (String titulo)
    { 
        super(titulo);
       
        setLayout(new BorderLayout(0,0));
        setLocation(350, 20);
        setResizable(false);
        setVisible(true);
        setSize(770,700);
           
    }   

    }

Código: [Seleccionar]
import javax.swing.*;
import java.awt.*;

public class PanelCentro extends JPanel
{
   private JTextField temas[];
   private String[] tituloTemas;
   private int numeroDeTemas;
 
   public PanelCentro (String[]tituloTemas,int numeroDeTemas){
        super();
        this.numeroDeTemas=numeroDeTemas;
        this.tituloTemas=tituloTemas;
        centro(tituloTemas,numeroDeTemas);
       
    } 
    public void centro (String[]tituloTemas,int numeroDeTemas){
       
        setLayout(new GridLayout(numeroDeTemas, 1));
        setBorder(BorderFactory.createLineBorder(Color.green));
        setBackground(Color.cyan);
        setVisible(true);
        setSize(510, 680);

        temas = new JTextField[numeroDeTemas];
        for (int i=0; i<numeroDeTemas; i++)
        {   temas[i] = new JTextField("     "+tituloTemas[i]);
            temas[i].setEditable(false);
            temas[i].setBackground(Color.green);
            temas[i].setBorder(BorderFactory.createLineBorder(Color.green));
            add(temas[i]);
        }
       
    }         
    }

Código: [Seleccionar]
import javax.swing.*;
import java.awt.*;

public class PanelSur extends JPanel 
{
 
    public PanelSur(int numeroBotones){
       super();
        setLayout(new GridLayout(1,numeroBotones));
        setBorder(BorderFactory.createLineBorder(Color.black));
        setBackground(Color.cyan);
    } 
   
    }

Código: [Seleccionar]
import javax.swing.*;
import java.awt.*;

public class  PanelOeste extends JPanel
{
    public PanelOeste()
    {
        super();
       
       
       
    }
   
}
« Última modificación: 23 de Marzo 2016, 11:14 por Alex Rodríguez »

Alex Rodríguez

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2050
    • Ver Perfil
Hola ahora los nombres de las clases son mucho más correctos. Yo diría que el progreso que llevas es muy bueno, más si sólo llevas mes y medio con Java, mucha gente tarda muchos más meses en poder crear un programa como este que tú has creado

Saludos

ESOJ

  • Intermedio
  • ***
  • APR2.COM
  • Mensajes: 143
    • Ver Perfil
Muchas gracias por el tiempo  que me has dedicado dedicado y muchas gracias por los animos.
Saludos.

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".