martes, 23 de enero de 2018

Interface MouseMotionListener

La interfaz del oyente para recibir eventos de movimiento del mouse en un componente


Presenta dos metodos 

mouseDragged(MouseEvent me)
nos abisa cuando se esta arrastrando el mouse o llevando algun texto en el caso de que se programe
mouseMoved(MouseEvent me)
nos abisa cuando el mouse esta moviendo en el frame correspondiente


Ejemplo

package graficos;

import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;

public class Event_Mouse {

    public static void main(String[] args) {
        moueveEvent nuevo = new moueveEvent();
        nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class moueveEvent extends JFrame {

    JPanel panel;
    JButton boton;

    public moueveEvent() {
        panel = new JPanel();
        boton = new JButton();
        boton.setSize(400, 200);
        panel.add(boton);
        add(panel);
        setVisible(true);
        setBounds(700, 300, 600, 350);

        addMouseListener(new eventosRaton());
        addMouseMotionListener(new controlarLaSeleccionMouse());
    }

}

class eventosRaton extends MouseAdapter {

    private Point punto = new Point();
    private int contadoClick = 0;

    @Override
    public void mouseClicked(MouseEvent me) {
        System.out.println("ha hecho click en la pantalla");
        contadoClick += me.getClickCount();// tambien puede ser para ver si el usuario ha hecho doblke click contar
        System.out.println("van :" + contadoClick + " click");
        System.out.println("ha hecho click en +" + me.getX() + " y y " + me.getY());

    }

    public void mousePressed(MouseEvent me) {
        //  System.out.println("ha precionado en el boton");
        if (me.getModifiersEx() ==MouseEvent.BUTTON1_DOWN_MASK) {
            System.out.println("Ha preciona el click");
        } else if (me.getModifiersEx() == MouseEvent.BUTTON2_DOWN_MASK) {//botonn la rueda del raton
            System.out.println("ha precionado la rueda del raton");
        } else if (me.getModifiersEx() == MouseEvent.BUTTON3_DOWN_MASK) {
            System.out.println("Ha precionado el anticlick");
        }

    }

    @Override
    public void mouseReleased(MouseEvent me) {
        System.out.println("ha soltado la precion del mouse");
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        System.out.println("ha uniciado el incio del boton esta dentro del boton");
    }

    @Override
    public void mouseExited(MouseEvent me) {
        System.out.println("ha salido del boton");
        punto = me.getLocationOnScreen();
    }

}


class controlarLaSeleccionMouse implements MouseMotionListener {

    @Override
    public void mouseDragged(MouseEvent me) {
      System.out.println("Esta arrastrando el mouse");
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        System.out.println("Esta moviendo el mouse");
    }

}

Share:

Interface MouseListener(MouseAdapter)


Permite tener un control total de todos los movimientos que realice el mouse dentro de cada uno de las interfaces

algunos componentes claves:

getClickCount() , permite contrar el todal de click que realiza en todo su recorrido o ejecucion en el programa

getModifiersEx(); controla los tres componentes de lo conforman al mouse click, anticlick y el desplazador:

 if (me.getModifiersEx() == 1024){} compara si se ha precionado un click (1024)  es el numero que representa al click  o tambien se puede hacer de otra forma(MouseEvent.BUTTON1_DOWN_MASK) con este forma seria igual :

if (me.getModifiersEx() == MouseEvent.BUTTON2_DOWN_MASK)  compara si se esta desplazando con el scroll

 if (me.getModifiersEx() == MouseEvent.BUTTON3_DOWN_MASK) compara si esta precionando el anticlick en alguna parte de los componentes



MouseListener tiene estos metodos como predeterminados que se tienen que implementar en el caso de que no se utilice la clase adaptadora que es el MouseAdapter();


mousePressed(MouseEvent me) Cuando se ha precionado pero aun no se suelta

mouseReleased(MouseEvent me)Cuando se ha soltado el click que se ha hecho

mouseClicked(MouseEvent me) Este metodo es llamado cuando ya se ha precionado y soltado el mouse del boton, o otro objeto

mouseEntered(MouseEvent me) Cuando el mouse esta dentro de un componente

mouseExited(MouseEvent me)Cuando el mouse ya ha salido del componente en la cual habia entrado

PARA MAS INFORMACION VISITAR LA PAGINA DE LA API DE JAVA 

EJEMPLO

package graficos;

import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;

public class Event_Mouse {

    public static void main(String[] args) {
        moueveEvent nuevo = new moueveEvent();
        nuevo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class moueveEvent extends JFrame {

    JPanel panel;
    JButton boton;

    public moueveEvent() {
        panel = new JPanel();
        boton = new JButton();
        boton.setSize(400, 200);
        panel.add(boton);
        add(panel);
        setVisible(true);
        setBounds(700, 300, 600, 350);

        addMouseListener(new eventosRaton());
    }

}

class eventosRaton extends MouseAdapter {

    private Point punto = new Point();
    private int contadoClick = 0;

    @Override
    public void mouseClicked(MouseEvent me) {
        System.out.println("ha hecho click en la pantalla");
        contadoClick += me.getClickCount();// tambien puede ser para ver si el usuario ha hecho doblke click contar
        System.out.println("van :" + contadoClick + " click");
        System.out.println("ha hecho click en +" + me.getX() + " y y " + me.getY());

    }

    public void mousePressed(MouseEvent me) {
        //  System.out.println("ha precionado en el boton");
        if (me.getModifiersEx() ==MouseEvent.BUTTON1_DOWN_MASK) {
            System.out.println("Ha preciona el click");
        } else if (me.getModifiersEx() == MouseEvent.BUTTON2_DOWN_MASK) {//botonn la rueda del raton
            System.out.println("ha precionado la rueda del raton");
        } else if (me.getModifiersEx() == MouseEvent.BUTTON3_DOWN_MASK) {
            System.out.println("Ha precionado el anticlick");
        }

    }

    @Override
    public void mouseReleased(MouseEvent me) {
        System.out.println("ha soltado la precion del mouse");
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        System.out.println("ha uniciado el incio del boton esta dentro del boton");
    }

    @Override
    public void mouseExited(MouseEvent me) {
        System.out.println("ha salido del boton");
        punto = me.getLocationOnScreen();
    }

}


class controlarLaSeleccionMouse implements MouseMotionListener {

    @Override
    public void mouseDragged(MouseEvent me) {
      System.out.println("Esta arrastrando el mouse");
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        System.out.println("Esta moviendo el mouse");
    }

}


PARA SABER QUE VENTANA SE HA CERRADO


package graficos;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;

public class primeraClaseEventWindowVentana {

    public static void main(String[] args) {
        main nuevo1 = new main("nuevo1");
        nuevo1.setTitle("fame1");
        main nuevo2 = new main("nuevo2");
        nuevo2.setTitle("fame2");
    }
}

class main extends JFrame {

    public main(String nombre) {
        setTitle(nombre);
        setSize(400, 500);
        setLocation(200, 300);
        setVisible(true);
        /* laminaWindow lamina = new laminaWindow();
        addWindowListener(lamina);*/
        addWindowListener(new laminaWindow(nombre));

    }

    private class laminaWindow extends WindowAdapter {

        String nombre;

        public laminaWindow(String nombre) {
            this.nombre = nombre;
        }

        @Override
        public void windowOpened(WindowEvent we) {
        }

        @Override
        public void windowClosing(WindowEvent we) {
            Object miVentana = we.getSource();

            System.out.println("Esta cerrando la venta");
            System.out.println("Ha cesarro la ventana" +nombre);
        }

        @Override
        public void windowClosed(WindowEvent we) {
            System.out.println("Ha cerrado la ventana");
        }

        @Override
        public void windowIconified(WindowEvent we) {
            Object miVentana = we.getSource();
            System.out.println("Se minimizo la venta");
            System.out.println("Ha minimizado la ventana" +nombre);

        }

    }
}



Share:

Interface FocuListener

La interfaz del oyente para recibir eventos de enfoque del teclado en un componente. La clase que está interesada en procesar un evento de enfoque implementa esta interfaz (y todos los métodos que contiene) o amplía la clase abstracta FocusAdapter (anulando solo los métodos de interés). El objeto detector creado a partir de esa clase se registra luego con un componente utilizando el método addFocusListener del componente. Cuando el componente gana o pierde el foco del teclado, se invoca el método relevante en el objeto oyente y se le pasa el FocusEvent

Permite que el oyente este escuchando en cada momento al hacer un click en cualquier para del JPanel, JFrame, JButton, etc esto comprende dos metodos focusGained(), o focusLost()


focusGained(focusEvent e), cuando el componente ha ganado el keyboard focus

focusLost(focusEvent e), cuando el componente ha perdido el keyBoard focus

PARA MAS INFORMACION VISITAR LA PAGINA DE LA API DE JAVA 

EJEMPLO

package graficos;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author USUARIO
 */
public class Event_Foco {
   
    public static void main(String[] args) {
        principal prin = new principal();
        prin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
    }
}

class principal extends JFrame {
   
    public principal() {
       
        setBounds(300, 200, 500, 500);
        setVisible(true);
        add(new focoBotonoes());
       
    }
   
    private class focoBotonoes extends JPanel {
       
        JButton boton1;
        JButton boton2;
        JTextField texto1;
        JTextField texto2;
        JLabel respuesta;
       
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            setLayout(null);
            dibujarBotones();
            Rectangle2D rectangulo = new Rectangle2D.Double(120, 120, 192, 374);
            g2.draw(rectangulo);
            texto1.addFocusListener(new lanzarFocus());
            texto2.addFocusListener(new lanzarFocus());
        }
       
        void dibujarBotones() {
            boton1 = new JButton("buton 1");
            texto1 = new JTextField();
            boton1.setBounds(40, 90, 80, 40);
            texto1.setBounds(136, 90, 96, 40);
           
            boton2 = new JButton("boton 2");
            texto2 = new JTextField();
            boton2.setBounds(40,150,80,40);
            texto2.setBounds(136,150,96,40);
           
            add(boton1);
            add(boton2);
            add(texto1);
            add(texto2);
           
        }
       
       private class lanzarFocus implements FocusListener {
           
            public void focusGained(FocusEvent fe) {
             
                if (fe.getSource() == texto1) {
                    System.out.println("El texto 1 ha ganado el foco");
                } else if (fe.getSource() == texto2) {
                    System.out.println("El texton 2 ha ganadado el foco");
                }
            }
           
            @Override
            public void focusLost(FocusEvent fe) {
             
                if (fe.getSource() == texto1) {
                    System.out.println("El texto 1 ha perdido el foco");
                    if (!revisisarContenido(texto1.getText())) {
                        crearLabelRevisador(texto1.getX(), texto1.getY(), "falta arroba");
                    }
                } else if (fe.getSource() == texto2) {
                    System.out.println("El texto 2 ha perdido el foco");
                    if (!revisisarContenido(texto2.getText())) {
                        crearLabelRevisador(texto2.getX(), texto2.getY(), "falta arroba");
                    }
                }
            }
           
            boolean revisisarContenido(String texto) {
                char[] separad = texto.toCharArray();
                boolean comprobador = false;
                for (char letra : separad) {
                    if (letra == '@') {
                        comprobador = true;
                    }
                }
                return comprobador;
               
            }
           
            void crearLabelRevisador(int x, int y, String respues) {
                respuesta = new JLabel();
                respuesta.setBounds(y, y + 20, 80, 40);
                respuesta.setText(respues);
                add(respuesta);
            }
        }
       
    }
}


Share:

JRadioButton

Es un componente que nos permite estar seleccionado o deseleccionado y utiliza un buttonGroup como objecto para ajuntar los jradioButton para que hayan solo uno seleccionado esto se va trabajando con eventos

isselected(); verifica si el radioButtton ha sido seleccionado retorna true, false
setSelected(); selecionado el radioButton y deselecciona el otro que haya sido seleccionado esto es porque esta trabajando con buttonGroupo que esta agrupado

PARA MAS INFORMACION VISITAR LA PAGINA DE LA API

Un ejemplo de la utilizacion de radioButton y otros componentes , el programa consiste en un espejo que si se selecciona en una parte el otro tambien sera seleccionado

package desarrolloejemplos;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

/**
 *
 * @author USUARIO
 */
public class espejoEvento extends javax.swing.JFrame {

    /**
     * Creates new form espejoEvento
     */
    public espejoEvento() {
        initComponents();
        setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        ButtonGroup grupo1 = new ButtonGroup();
        panel.setEnabled(false);
        grupo1.add(opcion1);
        grupo1.add(opcion2);
        grupo1.add(opcion3);

        opcion1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                opcion7.setSelected(true);
            }
        });
        opcion2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                opcion8.setSelected(true);
            }
        });
        opcion3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                opcion9.setSelected(true);
            }
        });

        opcion4.addActionListener(new ActionListener() {
            boolean verifica = false;

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (opcion4.isSelected()) {
                    opcion10.setSelected(true);
                } else if (!opcion4.isSelected()) {
                    opcion10.setSelected(false);
                }
            }
        });

        texto1.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent ke) {
            }

            @Override
            public void keyPressed(KeyEvent ke) {
                texto2.setText(texto1.getText());
            }

            @Override
            public void keyReleased(KeyEvent ke) {
            }
        }
        );

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        opcion1 = new javax.swing.JRadioButton();
        opcion2 = new javax.swing.JRadioButton();
        opcion3 = new javax.swing.JRadioButton();
        opcion4 = new javax.swing.JCheckBox();
        opcion5 = new javax.swing.JCheckBox();
        opcion6 = new javax.swing.JCheckBox();
        texto1 = new javax.swing.JTextField();
        combobox = new javax.swing.JComboBox<>();
        spiner = new javax.swing.JSpinner();
        panel = new javax.swing.JPanel();
        opcion7 = new javax.swing.JRadioButton();
        opcion8 = new javax.swing.JRadioButton();
        opcion9 = new javax.swing.JRadioButton();
        opcion10 = new javax.swing.JCheckBox();
        opcion11 = new javax.swing.JCheckBox();
        opcion12 = new javax.swing.JCheckBox();
        texto2 = new javax.swing.JTextField();
        combobox1 = new javax.swing.JComboBox<>();
        spiner1 = new javax.swing.JSpinner();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Original"));

        opcion1.setText("opcion 1");

        opcion2.setText("opcion 2");

        opcion3.setText("opcion 3");

        opcion4.setText("opcion 4");

        opcion5.setText("opcion 5");

        opcion6.setText("opcion 6");

        combobox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        combobox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                comboboxMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                comboboxMouseEntered(evt);
            }
        });

        spiner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spinerStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(opcion1)
                    .addComponent(opcion2)
                    .addComponent(opcion3))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(opcion6)
                        .addGap(18, 18, 18)
                        .addComponent(spiner))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(opcion5)
                        .addGap(18, 18, 18)
                        .addComponent(combobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(opcion4)
                        .addGap(18, 18, 18)
                        .addComponent(texto1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion1)
                    .addComponent(opcion4)
                    .addComponent(texto1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion2)
                    .addComponent(opcion5)
                    .addComponent(combobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion3)
                    .addComponent(opcion6)
                    .addComponent(spiner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(54, Short.MAX_VALUE))
        );

        panel.setBorder(javax.swing.BorderFactory.createTitledBorder("Espejo"));

        buttonGroup1.add(opcion7);
        opcion7.setText("opcion 1");

        buttonGroup1.add(opcion8);
        opcion8.setText("opcion 2");

        buttonGroup1.add(opcion9);
        opcion9.setText("opcion 3");

        opcion10.setText("opcion 4");

        opcion11.setText("opcion 5");

        opcion12.setText("opcion 6");

        combobox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(opcion7)
                    .addComponent(opcion8)
                    .addComponent(opcion9))
                .addGap(10, 10, 10)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(opcion12)
                        .addGap(18, 18, 18)
                        .addComponent(spiner1))
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(opcion11)
                        .addGap(18, 18, 18)
                        .addComponent(combobox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(opcion10)
                        .addGap(18, 18, 18)
                        .addComponent(texto2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion7)
                    .addComponent(opcion10)
                    .addComponent(texto2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion8)
                    .addComponent(opcion11)
                    .addComponent(combobox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(opcion9)
                    .addComponent(opcion12)
                    .addComponent(spiner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(150, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void comboboxMouseClicked(java.awt.event.MouseEvent evt) {                                     


    }                                   

    private void comboboxMouseEntered(java.awt.event.MouseEvent evt) {                                     
        combobox1.setSelectedIndex(combobox.getSelectedIndex());
    }                                   

    private void spinerStateChanged(javax.swing.event.ChangeEvent evt) {                                   
        spiner1.setValue((Integer) spiner.getValue());
    }                                 

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(espejoEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(espejoEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(espejoEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(espejoEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new espejoEvento().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JComboBox<String> combobox;
    private javax.swing.JComboBox<String> combobox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton opcion1;
    private javax.swing.JCheckBox opcion10;
    private javax.swing.JCheckBox opcion11;
    private javax.swing.JCheckBox opcion12;
    private javax.swing.JRadioButton opcion2;
    private javax.swing.JRadioButton opcion3;
    private javax.swing.JCheckBox opcion4;
    private javax.swing.JCheckBox opcion5;
    private javax.swing.JCheckBox opcion6;
    private javax.swing.JRadioButton opcion7;
    private javax.swing.JRadioButton opcion8;
    private javax.swing.JRadioButton opcion9;
    private javax.swing.JPanel panel;
    private javax.swing.JSpinner spiner;
    private javax.swing.JSpinner spiner1;
    private javax.swing.JTextField texto1;
    private javax.swing.JTextField texto2;
    // End of variables declaration                 
}

Share:

JSlider

JSlider para permitir que el usuario introduzca un valor numérico limitado por una valor máximo y un valor mínimo. Mediante la utilización de un Slider en vez de text field, se eliminan errores de entrada. 

slider.getValue(); permite saber el valor actual del slider

PARA MAS INFORMACION VISITAR LA PAGINA DE LA API DE JAVA

Share:

clase AbstractAction

su clase proporciona implementaciones predeterminadas para la interfaz de acción JFC. Los comportamientos estándar como los métodos get y set para las propiedades del objeto Action (icono, texto y habilitado) se definen aquí. El desarrollador solo necesita subclasificar esta clase abstracta y definir el método actionPerformed.

tambien tiene la funcionalidad de operar cuando se tiene multiples enventos

cuenta con diferentes metodos de la interfas Action y que programadores se dieron el tiempo de convertirlo en una clase abstracta para no poder utilizar todos los metodos si no se requieren:

putValue(Action.NAME,nombre); putValue(); nos permite guardar el parametro que pasa como nombre para luego utilizarlo

getValue(Action.NAME); nos permite recuperar la informacion que se guardo en Action.NAME

PARA MAS INFORMACION VISTAR LA PAGINA DE LA API DE JAVA 


EJEMPLO

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cursojava;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.security.Principal;
import javafx.scene.layout.GridPane;
import javax.swing.*;

/**
 *
 * @author USUARIO
 */
public class CursoJava {

    public static void main(String[] args) {
        new PrincipalC();

    }
}

class PrincipalC extends JFrame {

    public PrincipalC() {
        setVisible(true);
        setBounds(100, 200, 500, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new PaintAction());
    }
}

class PaintAction extends JPanel {

    PaintAction a;

    public PaintAction() {
        AccionColor accionAmarillo = new AccionColor("Amarillo", new ImageIcon("src/cursojava/1.png"), Color.YELLOW);
        AccionColor accionVerde = new AccionColor("Verde", new ImageIcon("src/cursojava/2.png"), Color.GREEN);
        AccionColor accionRojo = new AccionColor("Rojo", new ImageIcon("src/cursojava/icono.png"), Color.RED);

        add(new JButton(accionAmarillo));
        add(new JButton(accionRojo));
        add(new JButton(accionVerde));

        /*
        JButton amarillo = new JButton("Amarillo");
        JButton rojo = new JButton("Rojo");
        JButton verde = new JButton("Verde");
        add(amarillo);
        add(rojo);
        add(verde);*/
    }

    private class AccionColor extends AbstractAction {

        public AccionColor(String nombre, Icon icono, Color color_Boton) {
            putValue(Action.NAME, nombre);
            putValue(Action.SMALL_ICON, icono);
            putValue(Action.SHORT_DESCRIPTION, "Poner la lamina de color " + nombre);
            putValue("color de fondo", color_Boton);

        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            Color c = (Color) getValue("color de fondo");
            setBackground(c);
        }

    }

}

Share:

TENER EN CUENTA

SIRVE PARA PODER SACAR LAS MEDIDAS DE LA CUALQUIER PANTALLA

        Toolkit miPantalla = Toolkit.getDefaultToolkit();
        Dimension dimensionPantalla = miPantalla.getScreenSize();
        int ancho = dimensionPantalla.width;
        int altura = dimensionPantalla.height;
        this.setSize(ancho / 3, altura / 3);
        this.setLocation(ancho / 4, altura / 4);


PARA ESCOGER UN ARCHIVO DE LA PC

 //creamos una instancia de jfilechooser
        JFileChooser fc = new JFileChooser();

        //escribimos el nombre del titulo
        fc.setDialogTitle("Elige un fichero");
        //indicamos que solo se puedan elegir ficheros
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        ///creamos un filtro para jfilechoose
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("*.txt", "txt");
        fc.setFileFilter(filtro);
        int eleccion = fc.showSaveDialog(this);
        if (eleccion == JFileChooser.APPROVE_OPTION) {
            texto.setText(fc.getSelectedFile().getPath());
        }

PARA CREAR CUADRADOS DENTRO DEL JPANEL AUTOMATICAMENTE
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package graficos;

import java.awt.*;
import javax.swing.*;


/**
 *
 * @author USUARIO
 */
public class Graficos {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        marcoColor marco = new marcoColor();
        marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        marco.setVisible(true);
    }

}

class marcoColor extends JFrame {

    public marcoColor() {
        setTitle("Prueba de colores");
        Toolkit miPantalla = Toolkit.getDefaultToolkit();
        Dimension dimension = miPantalla.getScreenSize();
        double ancho = dimension.getWidth();
        double altura = dimension.getHeight();
        System.out.println("altura " + altura + " ancho " + ancho);

        setSize(800, 500);
        setLocation(200, 200);

        laminaConColor lamina = new laminaConColor();
        panelMenu panelMenu = new panelMenu();
        add(lamina);

        add(panelMenu);
        panelMenu.setBackground(Color.gray);
        lamina.setFont(new Font("Courier", Font.ITALIC, 20));
    }
}

class laminaConColor extends JPanel {

    @Override

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Rectangle2D rectangulo = new Rectangle2D.Double(200, 200, 200, 200);
        g2.draw(rectangulo);
        g2.draw(new Line2D.Double(200, 200, 400, 400));
        Ellipse2D eclipse = new Ellipse2D.Double();
        eclipse.setFrame(rectangulo);
        g2.draw(eclipse);

        //dibujar encima del cuadrado+
        double altura = rectangulo.getCenterY();
        double ancho = rectangulo.getCenterX();
        int radio = 200;

        Ellipse2D eclipseGrande = new Ellipse2D.Double();
        eclipseGrande.setFrameFromCenter(ancho, altura, ancho + radio, altura + radio);
        g2.draw(eclipseGrande);
    }

}

class panelMenu extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        dibujarMenuAbove(g2);
        //    Font miFuente = new Font("Courier", Font.BOLD, 15);
        //g2.setFont(miFuente);
        g2.setColor(Color.blue);
        g2.drawString("hola como estas", 300, 200);

        //  g2.setFont(new Font("Arial", Font.ITALIC, 15));
        //g2.setColor(new Color(12, 114, 21).brighter());
        g2.drawString("hola que tal tu dia ", 400, 500);
        dibujarPanelPadre(g2);
        dibujarDentroPadre(g2);

    }

    void dibujarMenuAbove(Graphics2D g2) {
        Rectangle2D rectangulo;
        double x = 30;
        double y = 30;

        double ancho = 207.6666;
        double altura = 40;

        for (int i = 0; i < 6; i++) {
            rectangulo = new Rectangle2D.Double(x, y, ancho, altura);
            g2.setPaint(Color.BLUE);
            g2.draw(rectangulo);
            g2.setPaint(Color.WHITE);
            g2.fill(rectangulo);
            x += ancho + 10;
        }
    }

    void dibujarPanelPadre(Graphics2D g2) {

        Rectangle2D rectanble = new Rectangle2D.Double(30, 100, 237.7, 768);
        g2.draw(rectanble);
    }

    void dibujarDentroPadre(Graphics2D g2) {
        Rectangle2D rectangulo;
        double x = 98.8;
        double y = 130;

        double ancho = 100;
        double altura = 107.6;
        for (int i = 0; i < 6; i++) {
            rectangulo = new Rectangle2D.Double(x, y, ancho, altura);
            g2.setPaint(Color.RED);
            g2.fill(rectangulo);
            y += altura + 20;

        }
    }

}


PARA SABER LAS LETRAS QUE TIENE EL SISTEMA OPERATIVO

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package graficos;

import java.awt.GraphicsEnvironment;

/**
 *
 * @author USUARIO
 */
public class paraSaberLetrasEnLaPcQueTienes {

    public static void main(String[] args) {
        String[] letrasSistema = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        for (String nombre : letrasSistema) {
            System.out.println(nombre);
        }
    }

}




CREANDO UN RELOJ

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reloj;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 *
 * @author USUARIO
 */
public class Reloj {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Reloj1 hora = new Reloj1();
        hora.enMarcha(3000, true);
        JOptionPane.showMessageDialog(null, "Pulse aceptar para finalizar");
        System.exit(0);

    }

}

class Reloj1 {

    public void enMarcha(int intervalo, final boolean sonido) {

        class DameHora implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Date hora = new Date();
                System.out.println("La hora es :" + hora);
                if (sonido) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        }

        ActionListener oyente = new DameHora();

        Timer tiempo = new Timer(1000, oyente);
        tiempo.start();
    }

}




Share:

BTemplates.com

Buscar este blog

Archivo del Blog

Con tecnología de Blogger.