Ver Mensaje Individual
  #2 (permalink)  
Antiguo 07/06/2012, 13:51
alexg88
 
Fecha de Ingreso: abril-2011
Mensajes: 1.342
Antigüedad: 13 años
Puntos: 344
Respuesta: Problema con JFrame

Es posible añadir objetos en tiempo de ejecución (en tu caso JTextField), pero tendrás que definir como quieres que aparezcan en la pantalla (para eso tendrás que usar layouts).

Un pequeño ejemplo:

Código Java:
Ver original
  1. import java.awt.BorderLayout;
  2. import java.awt.Container;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.util.ArrayList;
  6. import javax.swing.*;
  7.  
  8. public class Formulario extends JFrame {
  9.  
  10.     private ArrayList<JTextField> textFields = new ArrayList<JTextField>();
  11.     private JButton button = new JButton("Crear textboxs");
  12.     private JTextField textFieldNumber = new JTextField(5);
  13.     JPanel panelTextBox = new JPanel();
  14.     JPanel panelIntroducir = new JPanel();
  15.     public Formulario() {
  16.  
  17.  
  18.         Container pane = this.getContentPane();
  19.         pane.setLayout(new BorderLayout());
  20.         panelTextBox.setLayout(new BoxLayout(panelTextBox, BoxLayout.Y_AXIS));
  21.         panelIntroducir.setLayout(new BorderLayout());    
  22.         panelIntroducir.add(new JLabel("Introduzca el número de textboxs a crear"),BorderLayout.WEST);
  23.         panelIntroducir.add(textFieldNumber,BorderLayout.EAST);
  24.        
  25.         pane.add(panelIntroducir,BorderLayout.NORTH);
  26.         pane.add(panelTextBox,BorderLayout.CENTER);
  27.         button.addActionListener(new ActionListener() {
  28.  
  29.             @Override
  30.             public void actionPerformed(ActionEvent e) {
  31.                 JTextField newText;
  32.                 int numeroTextBox = 0;
  33.                 try {
  34.                     numeroTextBox = Integer.parseInt(textFieldNumber.getText());
  35.                 } catch (NumberFormatException ex) {
  36.                     numeroTextBox = 0;
  37.                 }
  38.                 for (int i = 0; i < numeroTextBox; i++) {
  39.                     newText = new JTextField(5);
  40.                     textFields.add(newText);
  41.                     panelTextBox.add(newText);
  42.                 }
  43.                 panelTextBox.updateUI();
  44.             }
  45.         });
  46.         pane.add(button,BorderLayout.SOUTH);
  47.  
  48.     }
  49.    
  50.  
  51.     public static void main(String[] ar) {
  52.         Formulario calc = new Formulario();
  53.         calc.setBounds(800, 400, 500, 500);
  54.         //calc.setResizable(false);
  55.         calc.setVisible(true);
  56.     }
  57. }

Esto es para que veas como se puede hacer, pero luego tu puedes personalizarlo a tu gusto.

Saludos.