Foros aprenderaprogramar.com

Aprender a programar => Aprender a programar desde cero => Mensaje iniciado por: jjpalao en 07 de Marzo 2017, 12:21

Título: Java Pasar de un JTextField a otro tabulando ejemplo FocusTraversalPolicy orden
Publicado por: jjpalao en 07 de Marzo 2017, 12:21
Tengo una ventana con dos JTextField, lo que quiero es que al introducir un numero en el primer JTextField que se llama txtPrimeraFactura al tabular se posicione en el segundo JTextField que se llama textField_Segundafactura.

Código: [Seleccionar]
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.Cursor;
 
public class Pantalla extends JFrame{
private static final long serialVersionUID = 1L;
private JTextField txtPrimeraFactura;
private JTextField textField_Segundafactura;
private JLabel lblResultado;
//----------Pantalla----------------------------   
    public static void main(String[] ar) {
      Pantalla formulario1=new Pantalla();
        formulario1.setBounds(400,200,450,450);
        formulario1.setVisible(true);
        formulario1.setResizable(false);                                       
   
   }
  //--------Titulo Pantalla-------------
    public Pantalla() {
    setAutoRequestFocus(false);
   
    getContentPane().setFocusCycleRoot(true);
        setTitle("Facturas Medicas");
    setResizable(false);                                       
    setVisible(true);                                       
                                               
    //---------Tengo 429----------------------------------       
       JLabel lblTengoPara = new JLabel("Tengo 429.25 para gastar");
       lblTengoPara.setVerticalAlignment(SwingConstants.TOP);
       lblTengoPara.setVerticalTextPosition(SwingConstants.TOP);
       lblTengoPara.setBounds(122, 11, 187, 31);
       lblTengoPara.setForeground(Color.BLUE);
       getContentPane().add(lblTengoPara);
       
       
       
     //---------Entrada Datos----------------------------------           
               
       txtPrimeraFactura = new JTextField();
       txtPrimeraFactura.setToolTipText("");
       txtPrimeraFactura.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
       txtPrimeraFactura.setFocusCycleRoot(true);
       txtPrimeraFactura.setBounds(191, 53, 86, 20);
       JLabel lblPrimeraFactura = new JLabel("Primera Factura:");
       lblPrimeraFactura.setFocusCycleRoot(true);
       lblPrimeraFactura.setBounds(28, 56, 101, 14);
       getContentPane().setLayout(null);
       getContentPane().add(lblPrimeraFactura, BorderLayout.WEST);
       getContentPane().add(txtPrimeraFactura, BorderLayout.CENTER);
       
     
       textField_Segundafactura = new JTextField();
       textField_Segundafactura.setFocusCycleRoot(true);
       textField_Segundafactura.setBounds(191, 78, 86, 20);
       JLabel lblSegundaFactura = new JLabel("Segunda Factura:"); 
       lblSegundaFactura.setFocusCycleRoot(true);
       lblSegundaFactura.setBounds(28, 81, 101, 14);
       getContentPane().setLayout(null);
       getContentPane().add(lblSegundaFactura, BorderLayout.WEST);
       getContentPane().add(textField_Segundafactura, BorderLayout.CENTER);
                     
    // ---------------Restar----------------------------------------------------                         
       JButton btnRestar = new JButton("Restar");
       btnRestar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        double resto;
        double total= 429.25;
        int lblPrimeraFactura=Integer.parseInt(txtPrimeraFactura.getText());
            int lblSegundaFactura=Integer.parseInt(textField_Segundafactura.getText());
            resto= total - (lblPrimeraFactura+lblSegundaFactura);
            lblResultado.setText("Resultado:"+resto);
           
           
               if (resto<0)
                lblResultado.setText("No puede ser negativa la suma de las facturas:"+resto);
                    lblResultado.setForeground(Color.red);
                   
                }
       
       });
    // ------Resultado------------------------------------------------- 
       btnRestar.setBounds(191, 135, 89, 23);
       getContentPane().add(btnRestar);
       lblResultado= new JLabel("Resultado:");
       lblResultado.setBounds(10, 378, 384, 14);
       getContentPane().add(lblResultado);
       lblResultado.setForeground (Color.magenta);
             
      //--------Finalizar-----------------------------------------------       
                        final JButton btnFinalizar = new JButton("Finalizar");
                        btnFinalizar.setFocusCycleRoot(true);
                        btnFinalizar.setBounds(188, 222, 89, 23);
                        getContentPane().add(btnFinalizar);
                        btnFinalizar.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent arg0) {
                        System.exit(0);
}
                        });
    }
     
                         

}


Muchas Gracias y Un saludo.
Título: Re:Java Pasar de un JTextField a otro tabulando ejemplo FocusTraversalPolicy orden
Publicado por: Alex Rodríguez en 14 de Mayo 2017, 16:39
Hola, te puedes basar en la idea que se desprende de este fragmento de código basado en FocusTraversalPolicy:

Código: [Seleccionar]
List<Component> elementList = new ArrayList<Component>();
elementList.Add(element1);
elementList.Add(element2);
...
elementList.Add(elementx);
setFocusTraversalPolicy(new CustomFocusTraversalPolicy());


private class CustomFocusTraversalPolicy extends FocusTraversalPolicy {   

    public Component getComponentAfter(Container focusCycleRoot,Component aComponent)    {   
        int currentPosition = elementList.indexOf(aComponent);
        currentPosition = (currentPosition + 1) % elementList.size();   
        return (Component)elementList.get(currentPosition);   
    }   
    public Component getComponentBefore(Container focusCycleRoot,Component aComponent)    {
        int currentPosition = elementList.indexOf(aComponent);
        currentPosition = (elementList.size() + currentPosition - 1) % elementList.size();   
        return (Component)elementList.get(currentPosition);   
    }
    public Component getFirstComponent(Container cntnr) {
        return (Component)elementList.get(0);
    }
    public Component getLastComponent(Container cntnr) {
        return (Component)elementList.get(elementList.size() - 1);
    }
    public Component getDefaultComponent(Container cntnr) {
        return (Component)elementList.get(0);
    }
}

Aplicado a tu código quedaría así:

Código: [Seleccionar]
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FocusTraversalPolicy;
import java.awt.Container;
import java.awt.Component;
import java.util.List;
import java.util.ArrayList;

public class Pantalla extends JFrame{
    private static final long serialVersionUID = 1L;
    private JTextField txtPrimeraFactura;
    private JTextField textField_Segundafactura;
    private JLabel lblResultado;
    List<Component> elementList;
    //----------Pantalla----------------------------   
    public static void main(String[] ar) {
        Pantalla formulario1=new Pantalla();
        formulario1.setBounds(400,200,450,450);
        formulario1.setVisible(true);
        formulario1.setResizable(false);                                       

    }
    //--------Titulo Pantalla-------------
    public Pantalla() {
        setAutoRequestFocus(false);

        getContentPane().setFocusCycleRoot(true);
        setTitle("Facturas Medicas");
        setResizable(false);                                       
        setVisible(true);                                       

        //---------Tengo 429----------------------------------       
        JLabel lblTengoPara = new JLabel("Tengo 429.25 para gastar");
        lblTengoPara.setVerticalAlignment(SwingConstants.TOP);
        lblTengoPara.setVerticalTextPosition(SwingConstants.TOP);
        lblTengoPara.setBounds(122, 11, 187, 31);
        lblTengoPara.setForeground(Color.BLUE);
        getContentPane().add(lblTengoPara);

       
        //---------Entrada Datos----------------------------------           

        txtPrimeraFactura = new JTextField();
        txtPrimeraFactura.setToolTipText("");
        txtPrimeraFactura.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
        txtPrimeraFactura.setFocusCycleRoot(true);
        txtPrimeraFactura.setBounds(191, 53, 86, 20);
        JLabel lblPrimeraFactura = new JLabel("Primera Factura:");
        lblPrimeraFactura.setFocusCycleRoot(true);
        lblPrimeraFactura.setBounds(28, 56, 101, 14);
        getContentPane().setLayout(null);
        getContentPane().add(lblPrimeraFactura, BorderLayout.WEST);
        getContentPane().add(txtPrimeraFactura, BorderLayout.CENTER);

        textField_Segundafactura = new JTextField();
        textField_Segundafactura.setFocusCycleRoot(true);
        textField_Segundafactura.setBounds(191, 78, 86, 20);
        JLabel lblSegundaFactura = new JLabel("Segunda Factura:");
        lblSegundaFactura.setFocusCycleRoot(true);
        lblSegundaFactura.setBounds(28, 81, 101, 14);
        getContentPane().setLayout(null);
        getContentPane().add(lblSegundaFactura, BorderLayout.WEST);
        getContentPane().add(textField_Segundafactura, BorderLayout.CENTER);

        // ---------------Restar----------------------------------------------------                         
        JButton btnRestar = new JButton("Restar");
        btnRestar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    double resto;
                    double total= 429.25;
                    int lblPrimeraFactura=Integer.parseInt(txtPrimeraFactura.getText());
                    int lblSegundaFactura=Integer.parseInt(textField_Segundafactura.getText());
                    resto= total - (lblPrimeraFactura+lblSegundaFactura);
                    lblResultado.setText("Resultado:"+resto);

                    if (resto<0)
                        lblResultado.setText("No puede ser negativa la suma de las facturas:"+resto);
                    lblResultado.setForeground(Color.red);

                }

            });
        // ------Resultado-------------------------------------------------
        btnRestar.setBounds(191, 135, 89, 23);
        getContentPane().add(btnRestar);
        lblResultado= new JLabel("Resultado:");
        lblResultado.setBounds(10, 378, 384, 14);
        getContentPane().add(lblResultado);
        lblResultado.setForeground (Color.magenta);

        //--------Finalizar-----------------------------------------------       
        final JButton btnFinalizar = new JButton("Finalizar");
        btnFinalizar.setFocusCycleRoot(true);
        btnFinalizar.setBounds(188, 222, 89, 23);
        getContentPane().add(btnFinalizar);
        btnFinalizar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    System.exit(0);
                }
            });

        elementList = new ArrayList<Component>();
        elementList.add(txtPrimeraFactura);
        elementList.add(textField_Segundafactura);
        setFocusTraversalPolicy(new CustomFocusTraversalPolicy());
    }

    private class CustomFocusTraversalPolicy extends FocusTraversalPolicy {   

        public Component getComponentAfter(Container focusCycleRoot,Component aComponent)    {   
            int currentPosition = elementList.indexOf(aComponent);
            currentPosition = (currentPosition + 1) % elementList.size();   
            return (Component)elementList.get(currentPosition);   
        }   

        public Component getComponentBefore(Container focusCycleRoot,Component aComponent)    {
            int currentPosition = elementList.indexOf(aComponent);
            currentPosition = (elementList.size() + currentPosition - 1) % elementList.size();   
            return (Component)elementList.get(currentPosition);   
        }

        public Component getFirstComponent(Container cntnr) {
            return (Component)elementList.get(0);
        }

        public Component getLastComponent(Container cntnr) {
            return (Component)elementList.get(elementList.size() - 1);
        }

        public Component getDefaultComponent(Container cntnr) {
            return (Component)elementList.get(0);
        }
    }


}

Saludos