Seguidores

MIS WEBS



sábado, 31 de marzo de 2018

Ejercicio con Layout Libre parte 4

Poner a la escucha diferentes laminas de mi aplicación


¿Que hemos hecho hasta ahora?


En anteriores capítulos de nuestro ejercicio hemos creado la parte visual de una aplicación java para crear JOptionPame, Pusimos a la escucha nuestras láminas utilizando Eventos de ratón MouseListener, Con ello conseguíamos que al hacer clic en la lámina se hiciera mas grande. Ahora lo que he hecho Poner a la escucha cada uno de los elementos de nuestras láminas (JRadioButon, JButton,JComboBox...).




¿Como poner a las escucha  JRadioButonJButton,JComboBox  de diferentes láminas en java?


En mí caso decidí crear varias láminas y luego sobre ponerlas encima de la lámina principal, ahora lo que hago es llamar a cada uno de los objetos lámina (JFrame) y ponerlos a la escucha para saber cual se acciona en cada instante.





       public Marco_practicaCreadorDeMensajes() {
            
             setTitle("CREADOR DE MENSAJES");
            
              PRINCIPAL = new Lamina_PrincipaldelMarco();
                     TipoBotones = new Lamina_TipoMensaje();
                     Seleccion = new Lamina_IconoSleccionado();
                     Confirmacion = new Lamina_TipoMensajeConfirmacion();
                     Menu = new Lamina_Menu_Superior();
                     BotonesAccion = new L_bott_creaMarcos();
            
             PRINCIPAL.setLayout(null);
                           TipoBotones.addMouseMotionListener(new oyente_raton());
                           Seleccion.addMouseMotionListener(new oyente_raton());
                           Confirmacion.addMouseListener(new oyente_raton());
                           BotonesAccion.addMouseListener(new oyente_raton());
                           TipoBotones.addMouseListener(new oyente_raton());
                           Seleccion.addMouseListener(new oyente_raton());
                           Confirmacion.addMouseListener(new oyente_raton());
                           BotonesAccion.addMouseListener(new oyente_raton());
                    PRINCIPAL.add(Menu);
                    PRINCIPAL.add(TipoBotones);
                    PRINCIPAL.add(Seleccion);
                    PRINCIPAL.add(Confirmacion);
                    PRINCIPAL.add(BotonesAccion);
      //utilizamos la nomenclatura del punto para poner a la escucha todos los objetos
      //de las diferentes láminas.
                   
     BotonesAccion.CrearMesaje.addActionListener(new elquetodoloescucha());
     BotonesAccion.Cancelar.addActionListener(new elquetodoloescucha());
     Seleccion.PORDEFECTO.addActionListener(new elquetodoloescucha());
     Seleccion.SICANCELAR.addActionListener(new elquetodoloescucha());
     Seleccion.SiNO.addActionListener(new elquetodoloescucha());
     Seleccion.SINOCANCELAR.addActionListener(new elquetodoloescucha());
     Confirmacion.ERROR.addActionListener(new elquetodoloescucha());
     Confirmacion.NA.addActionListener(new elquetodoloescucha());
     Confirmacion.PELIGRO.addActionListener(new elquetodoloescucha());
     Confirmacion.INFORMACION.addActionListener(new elquetodoloescucha());
      //para poner a la escucha un item del comboTipoMensaje
     TipoBotones.comboTipoMensaje.addItemListener(new elquetodoloescucha());
                          
                   
             add(PRINCIPAL);            
       }






¿Como crear el evento JRadioButonJButton,JComboBox  de diferentes láminas en java?



En cuanto a JRadioButon y  JButton no tuve mucho problema utilizando ActionListener, de momento tal y como podéis ver tan solo saldrá un mensaje por consola de Eclipse, lo que me interesa en este instante es confirmar que todos ellos se ponen a la escucha, más a delante le daremos la funcionalidad adecuada.


class elquetodoloescucha implements ActionListener,ItemListener{

            
             public void actionPerformed(ActionEvent e2) {
                   
                   
                    System.out.println(e2.getActionCommand());
             }
}


¿Como obtener el valor de un JCoboBox?

Ahora viene cuando la matan, en el caso de JComboBox   me dio algún quebradero de cabeza. Al final tirando de Googel encontré la respuesta, ¿que sería de nosotros sin San Google?.

 El problema que me daba JComboBox  es que cuando lo ponía a la escucha con ItemListener, este nos regresaba dos Item (el que deja y el que adquiere).

¿Como conseguir que JComboBox  nos regrese el registro seleccionado?

Tendremos que utilizar un if para seleccionar el que pasa a ser seleccionado en este instante.

public void itemStateChanged(ItemEvent e) {
                   
                    String item;
                   
                     if(e.getStateChange() == ItemEvent.SELECTED){ 
                          item = (String) e.getItem();System.out.println(item);
                             
                             }  




Por lo que este sería nuestro código completo por ahora:


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import  java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class practicaCreadorDeMensajes {

       public static void main(String[] args) {
             Marco_practicaCreadorDeMensajes Marco = new  Marco_practicaCreadorDeMensajes();
             Marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             Marco.setVisible(true);
             //Marco.setExtendedState(JFrame.MAXIMIZED_BOTH);
            
            
             Marco.setBounds(900, 30, 400, 800);
            
       }

}
class Marco_practicaCreadorDeMensajes extends JFrame {
      
       public Marco_practicaCreadorDeMensajes() {
            
             setTitle("CREADOR DE MENSAJES");
            
              PRINCIPAL = new Lamina_PrincipaldelMarco();
                     TipoBotones = new Lamina_TipoMensaje();
                     Seleccion = new Lamina_IconoSleccionado();
                     Confirmacion = new Lamina_TipoMensajeConfirmacion();
                     Menu = new Lamina_Menu_Superior();
                     BotonesAccion = new L_bott_creaMarcos();
            
             PRINCIPAL.setLayout(null);
                           TipoBotones.addMouseMotionListener(new oyente_raton());
                           Seleccion.addMouseMotionListener(new oyente_raton());
                           Confirmacion.addMouseListener(new oyente_raton());
                           BotonesAccion.addMouseListener(new oyente_raton());
                           TipoBotones.addMouseListener(new oyente_raton());
                           Seleccion.addMouseListener(new oyente_raton());
                           Confirmacion.addMouseListener(new oyente_raton());
                           BotonesAccion.addMouseListener(new oyente_raton());
                    PRINCIPAL.add(Menu);
                    PRINCIPAL.add(TipoBotones);
                    PRINCIPAL.add(Seleccion);
                    PRINCIPAL.add(Confirmacion);
                    PRINCIPAL.add(BotonesAccion);
 //utilizamos la nomenclatura del punto para poner a la escucha todos los objetos
                    //de las diferentes láminas.
                   
BotonesAccion.CrearMesaje.addActionListener(new elquetodoloescucha());
BotonesAccion.Cancelar.addActionListener(new elquetodoloescucha());
Seleccion.PORDEFECTO.addActionListener(new elquetodoloescucha());
Seleccion.SICANCELAR.addActionListener(new elquetodoloescucha());
Seleccion.SiNO.addActionListener(new elquetodoloescucha());
Seleccion.SINOCANCELAR.addActionListener(new elquetodoloescucha());
Confirmacion.ERROR.addActionListener(new elquetodoloescucha());
Confirmacion.NA.addActionListener(new elquetodoloescucha());
Confirmacion.PELIGRO.addActionListener(new elquetodoloescucha());
Confirmacion.INFORMACION.addActionListener(new elquetodoloescucha());
                           //para poner a la escucha un item del comboTipoMensaje
TipoBotones.comboTipoMensaje.addItemListener(new elquetodoloescucha());
                          
                   
             add(PRINCIPAL);
            
            
       }
      
       class elquetodoloescucha implements ActionListener,ItemListener{

            
             public void actionPerformed(ActionEvent e2) {
                   
                   
                    System.out.println(e2.getActionCommand());
             }
             public void itemStateChanged(ItemEvent e) {
                   
                    // ********  primero tenemos que escojer entre los dos que nos regeresa el Selecionado   **********  //////
                    String item;
                   
                     if(e.getStateChange() == ItemEvent.SELECTED){ item = (String) e.getItem();System.out.println(item);} 
       ///////////**********_______________________________**********////////
                     
            
             }
            
            
            

                   
       }

       JOptionPane pnelaccion;
       Lamina_Menu_Superior Menu ;
       Lamina_TipoMensaje TipoBotones;
       Lamina_IconoSleccionado Seleccion;
       Lamina_TipoMensajeConfirmacion Confirmacion ;
       L_bott_creaMarcos BotonesAccion;
       Lamina_PrincipaldelMarco PRINCIPAL;
      
private class oyente_raton implements MouseMotionListener,MouseListener{
       public void mouseDragged(MouseEvent e) {}
       public void mouseMoved(MouseEvent e) {}
       public void mouseClicked(MouseEvent e) {
                           if (e.getSource()==TipoBotones) {TipoBotones.         setBounds(10,60,300,500);
                                        Seleccion.setVisible(false);
                                        Confirmacion.setVisible(false);
                                        BotonesAccion.setVisible(false);}
                           else if (e.getSource()==Seleccion) {Seleccion.               setBounds(10,60,300,500);
                                        TipoBotones.setVisible(false);
                                        Confirmacion.setVisible(false);
                                        BotonesAccion.setVisible(false);}
                           else if (e.getSource()==Confirmacion) {Confirmacion.         setBounds(10,60,300,500);
                                        TipoBotones.setVisible(false);
                                        Seleccion.setVisible(false);
                                        BotonesAccion.setVisible(false);}
                           else if (e.getSource()==BotonesAccion) {BotonesAccion.       setBounds(10,60,300,500);
                                        TipoBotones.setVisible(false);
                                        Confirmacion.setVisible(false);
                                        Seleccion.setVisible(false);}

       }
       public void mouseEntered(MouseEvent e) {}
       public void mouseExited(MouseEvent e) {}
       public void mousePressed(MouseEvent e) {}
       public void mouseReleased(MouseEvent e) {
                           if (e.getSource()==TipoBotones) {TipoBotones.         setBounds(10, 60,300,100);
                                  Seleccion.setVisible(true);
                                  Confirmacion.setVisible(true);
                                  BotonesAccion.setVisible(true);}
                           else if (e.getSource()==Seleccion) {Seleccion.               setBounds(10,170,300,150);
                                  TipoBotones.setVisible(true);
                                  Confirmacion.setVisible(true);
                                  BotonesAccion.setVisible(true);}
                           else if (e.getSource()==Confirmacion) {Confirmacion.         setBounds(10,330,300,200);
                                  TipoBotones.setVisible(true);
                                  Seleccion.setVisible(true);
                                  BotonesAccion.setVisible(true);}
                           else if (e.getSource()==BotonesAccion) {BotonesAccion.       setBounds(10,550,300,150);
                                  TipoBotones.setVisible(true);
                                  Confirmacion.setVisible(true);
                                  Seleccion.setVisible(true);}
             }
      
      
       }
}
      
  
class Lamina_Menu_Superior extends JPanel{
        public Lamina_Menu_Superior() {
                    setBackground(Color.DARK_GRAY);
                    setBounds(10,10,1340,35);
                    //setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.RED),"TIPO DE MENSAJE"));
                                  BarraDelMenu = new JMenuBar();
ImageIcon ImageIcon_ERROR = new ImageIcon("C:\\Users\\dagip\\Desktop\\ddddddddddd\\src/ImageIcon_warning_1.jpg");
ImageIcon ImageIcon_INFORMACION = new ImageIcon("C:\\Users\\dagip\\Desktop\\x\\src/ImageIcon_informacion.jpg");
ImageIcon ImageIcon_PELIGRO= new ImageIcon("C:\\Users\\dagip\\Desktop\\ddddddddddd\\src/ImageIcon_herror.png");
ImageIcon ImageIcon_NA= new ImageIcon("C:\\Users\\x\\x\\x\\src/ImageIcon_Preguntas_2.jpg");
                                 
                                 
                   
BarraDelMenu.add(Inicio=new JMenu("INICIO"));
Inicio.add(Salir = new JMenuItem("Salir",new ImageIcon("C:\\Users\\dagip\\Desktop\\x\\src/SALIR.jpg")));
//ponemos a la escucha el menú salir
                                                                                 Salir.addActionListener(new ActionListener(){
                                                                                       public void actionPerformed(ActionEvent e) {
                                                                                              System.exit (0);//salir del sistema//
                                                                                       }
                                                                                 });
                            BarraDelMenu.add(TipMensaje = new JMenu("TIPO MENSAJE"));
TipMensaje.add(ENT_DATOS =      new JMenuItem("ENTRADA DATOS POR CONSOLA"));
TipMensaje.add(MENSAJE =              new JMenuItem("MENSAJES"));
TipMensaje.add(COFIRMACI =      new JMenuItem("MENSAJE ESTANDAR "));
TipMensaje.add(OPCIONES =       new JMenuItem("MENSAJE OPCIONES "));

BarraDelMenu.add(SubTipo = new JMenu("SUB TIPO MENSAJE"));
SubTipo.add(ERROR =      new JMenuItem("ERROR",ImageIcon_ERROR));
SubTipo.add(PELIGRO =    new JMenuItem("PELIGRO",ImageIcon_PELIGRO));
SubTipo.add(INFORMACION =       new JMenuItem("INFORMACION",ImageIcon_INFORMACION));
SubTipo.add(NAnew JMenuItem("PORDEFECTO",ImageIcon_NA));
                                                       
BarraDelMenu.add(BotConfirmacion = new JMenu("MENSAJE CONFIRMACIÓN"));  
grupotipo = new ButtonGroup();  
                                                                    grupotipo.add(PORDEFECTO =  new JRadioButton("PORDEFECTO"));
 grupotipo.add(SiNO =             new JRadioButton("SI / NO"));
                                                                    grupotipo.add(SICANCELAR =    new JRadioButton("SI / CANCELAR"));
                                                                    grupotipo.add(SINOCANCELAR =  new JRadioButton("SI / NO / CANCELAR"));
                                                                           BotConfirmacion.add(PORDEFECTO)   ;
                                                                          BotConfirmacion.add(SiNO);
                                                                           BotConfirmacion.add(SICANCELAR)   ;
                                                                           BotConfirmacion.add(SINOCANCELAR);
                                                             
                    add(BarraDelMenu);
        }
        
       private JMenu Inicio,TipMensaje,SubTipo,BotConfirmacion,CargaJMenu ;
       private JMenuItem Salir,ERROR,PELIGRO,INFORMACION,NA,
                           ENT_DATOS,MENSAJE,COFIRMACI,OPCIONES;
       private ButtonGroup grupotipo;
       private JRadioButton PORDEFECTO,SiNO,SICANCELAR,SINOCANCELAR;
       private JMenuBar BarraDelMenu;
}
class Lamina_PrincipaldelMarco extends JPanel{
                   
                    public Lamina_PrincipaldelMarco() {
                           setBackground(Color.BLACK);
}
}
class Lamina_TipoMensaje extends JPanel{
      
       JComboBox comboTipoMensaje ;
       public Lamina_TipoMensaje() {
             setBackground(Color.WHITE);
             setBounds(10,60,300,100);
              setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.RED),"TIPO DE MENSAJE"));
            
            
              comboTipoMensaje = new JComboBox();
            
                           comboTipoMensaje.addItem("MENSAJE AVISO");
                           comboTipoMensaje.addItem("MENSAJE DE ENTRADA DATOS");
                           comboTipoMensaje.addItem("MENSAJE CONFIRMACION");
                           comboTipoMensaje.addItem("MENSAJE OPCIONES");

      
             add(new JLabel("TIPOMENSAJE"));
             add(comboTipoMensaje);
       }
      
}


class Lamina_IconoSleccionado extends JPanel{
      
       public Lamina_IconoSleccionado() {
             setBackground(Color.WHITE);
             setBounds(10,170,300,150);
              setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.RED),"TIPO DE ICONO"));
             setLayout(new GridLayout(4,1));
             TIP_MEN_CONFIRM = new ButtonGroup();
             PORDEFECTO = new JRadioButton("ESTANDAR");
             SiNO = new JRadioButton("SI / NO");
             SICANCELAR = new JRadioButton("SI / CANCELAR");
             SINOCANCELAR = new JRadioButton("SI / NO / CANCELAR");
                          
                           TIP_MEN_CONFIRM.add(PORDEFECTO);
                           TIP_MEN_CONFIRM.add(SiNO);
                           TIP_MEN_CONFIRM.add(SICANCELAR);
                           TIP_MEN_CONFIRM.add(SINOCANCELAR);

             add(PORDEFECTO);add(SiNO);add(SICANCELAR);add(SINOCANCELAR);



            
       }
       JRadioButton PORDEFECTO,SiNO,SICANCELAR,SINOCANCELAR;
       ButtonGroup TIP_MEN_CONFIRM;
}

class Lamina_TipoMensajeConfirmacion extends JPanel{
      
       public Lamina_TipoMensajeConfirmacion() {
             setBackground(Color.WHITE);
             setBounds(10,330,300,200);
             setLayout(new GridLayout(3,1));
              setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.RED),"TIPO DE MENSAJE CONFIRMACIÓN"));
            
ImageIcon_ERROR = new ImageIcon("C:\\Users\\dagip\\x\\x\\src/ImageIcon_warning_1.jpg");
ImageIcon_INFORMACION=new ImageIcon("C:\\Users\\dagip\\x\\x\\src/ImageIcon_informacion.jpg");
ImageIcon_PELIGRO= new ImageIcon("C:\\Users\\dagip\\x\\x\\src/ImageIcon_herror.png");
ImageIcon_PREGUNTA= new ImageIcon("C:\\Users\\x\\x\\x\\src/ImageIcon_Warning_2.png");
ImageIcon_NA= new ImageIcon("C:\\Users\\x\\x\\x\\src/ImageIcon_Preguntas_2.jpg");
             Botones = new ButtonGroup();
             Array_Botones = new JButton[] {ERROR = new JButton("ERROR",ImageIcon_ERROR),
                          INFORMACION = new JButton("INFORMACION",ImageIcon_INFORMACION),
                          PELIGRO = new JButton("PILIGRO",ImageIcon_PELIGRO),
                          PREGUNTA = new JButton("PREGUNTA",ImageIcon_NA),
                          NA = new JButton("N/A",ImageIcon_PREGUNTA)
                                                               };
                                                                  


             for (int i =0;i<Array_Botones.length;i++) {
                    Botones.add(Array_Botones[1]);
                    add(Array_Botones[i]);
                   
             }
            
       }
      
       JButton ERROR,INFORMACION,PELIGRO,PREGUNTA,NA,Array_Botones[];
       ButtonGroup Botones;
ImageIcon ArraydeIcono[],ImageIcon_ERROR,ImageIcon_INFORMACION,ImageIcon_PELIGRO,ImageIcon_PREGUNTA,ImageIcon_NA;
      

}


class L_bott_creaMarcos extends JPanel{
      
       public L_bott_creaMarcos() {
            
             setBackground(Color.WHITE);
             setBounds(10,550,300,130);
             setLayout(new GridLayout(1,1));
              setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.RED),"TIPO DE MENSAJE CONFIRMACIÓN"));
            
add(CrearMesaje=new JButton("CREARMENSAJE",new ImageIcon("C:\\Users\\x\\x\\x\\src/ImageIcon_BIEN.png")));
add(Cancelar=new JButton("CANCELAR",new ImageIcon("C:\\Users\\x\\x\\v\\src/ImageIcon_Aspa.png")));
            
      
       }
JButton Cancelar,CrearMesaje;
}



Si te gusta y deseas continuar







No hay comentarios:

Publicar un comentario

Buscar este blog

Sandisk y Western Digital