Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
Declarar un nombre a un edit creado en tiempo de ejecucion

Hola a todos...

lo que pasa es que quiero declararle un nombre a un TEdit que estoy creando en tiempo de ejcucion pero el problema es que los estoy creando con una matriz y no se como hacer para declararle todos los nombres a todos los TEdit...
les agradesco su ayuda.

Este es el codigo.

Código Delphi [-]

unit Ejecucion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus;

type
  matriz = array of array of Integer;
  TfrmEjecucion = class(TForm)
    Button1: TButton;
    Edt: TEdit;
    Panel1: TPanel;
    Panel2: TPanel;
    Button2: TButton;
    Button3: TButton;
    MainMenu1: TMainMenu;
    Volver1: TMenuItem;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Volver1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmEjecucion: TfrmEjecucion;
  NEdits : Integer;
  Edits: TEdit;
  m : matriz;

implementation

{$R *.dfm}

procedure TfrmEjecucion.Button1Click(Sender: TObject);
var
  c,f : Integer;
begin
  //Desicion para que no sea tan grande la matriz
  if StrToInt(Edt.Text) >= 11 then
  begin
    ShowMessage('El valor tiene que ser igual o menor a 10');
    Edt.Clear;
  end
  else
  begin
    //Establece el valor de la matriz y de los TEdit
    NEdits := StrToInt(Edt.Text);
    SetLength(m, StrToInt(Edt.Text),StrToInt(Edt.Text));
    Button1.Visible := False;
    Edt.Visible := False;
  end;
  // Creo y posiciono los Edits
  for c := 1 to NEdits do
  begin
    for f := 1 to NEdits do
    begin
      Edits := TEdit.Create(Self);
      Edits.Left := 21 * (c + 1);
      Edits.Top := 21 * (f + 1);
      Edits.Width := 20;
      Edits.Height := 20;
      Edits.Enabled := False;
      Edits.Parent := Panel1;
      Button3.Visible := True;
    end;
  end;
end;

procedure TfrmEjecucion.Volver1Click(Sender: TObject);
begin
    Close;
end;

end.
Responder Con Cita
  #2  
Antiguo 24-10-2018
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
¿Para qué quieres ponerle un nombre? Normalmente, el nombre de un control se utiliza sólamente para referirnos a él en código, pero, dado que lo creas en tiempo de ejecución, no hace mucho sentido.

// Saludos
Responder Con Cita
  #3  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
roman lo que pasa es que después necesito llamar a todos los Edit creados para así llenarlos con una matriz y la única forma que se me ocurría era llamarlos por el nombre.
Responder Con Cita
  #4  
Antiguo 24-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
Hola,

Probaste hacer esto:

Código:
for f := 1 to NEdits do
    begin
      Edits := TEdit.Create(Self);
      Edits.Left := 21 * (c + 1);
      Edits.Top := 21 * (f + 1);
      Edits.Width := 20;
      Edits.Height := 20;
      Edits.Enabled := False;
      Edits.Parent := Panel1;
      Edits.name := 'Edit'+f.ToString;
      Button3.Visible := True;
    end;
Responder Con Cita
  #5  
Antiguo 24-10-2018
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
El problema es que, para encontrar un control por su nombre utilizas FindComponent. Pero este método, a su vez, es un ciclo que recorre todos los componentes del formulario para encontrar una coincidencia de nombre. Entonces, si tu rejilla es, digamos, de 10x10, estarías recorriendo el formulario 100 veces.

Dado que estás creando los controles por código, fácilmente puedes declarar una matriz de Edits:

Código Delphi [-]
var
  Edits: array[1..10,1..10] of TEdit;

y llenarla con los controles que creas. Posteriormente será mucho más fácil utilizarlos por sus coordenadas:

Código Delphi [-]
Edits[2, 8].Text := 'Algo';

// Saludos
Responder Con Cita
  #6  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
Si ramon yo lo declaro así solo que es dinámico y defino la matriz a través de un TEdit y como es una matriz cuadrada no hay problema,

Declaro la matriz asi:
Código Delphi [-]

matriz = array of array of Integer;

y defino el valor asi:

Código Delphi [-]

SetLength(m, StrToInt(Edt.Text),StrToInt(Edt.Text));
Responder Con Cita
  #7  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
Si ramon yo lo declaro así solo que es dinámico y defino la matriz a través de un TEdit y como es una matriz cuadrada no hay problema,

Declaro la matriz asi:
Código Delphi [-]

matriz = array of array of Integer;

y defino el valor asi:

Código Delphi [-]

SetLength(m, StrToInt(Edt.Text),StrToInt(Edt.Text));
Responder Con Cita
  #8  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
juniorSoft si claro ya lo intente
Responder Con Cita
  #9  
Antiguo 24-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
Amigo muchas gracias por su ayuda ya busque y pude solucionar mi error

les dejo mi solucion y me dicen que les parece

Código Delphi [-]

unit Ejecucion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus;

type
  matriz = array of array of Integer;
  TfrmEjecucion = class(TForm)
    Button1: TButton;
    Edt: TEdit;
    Panel1: TPanel;
    Panel2: TPanel;
    Button2: TButton;
    Button3: TButton;
    MainMenu1: TMainMenu;
    Volver1: TMenuItem;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Volver1Click(Sender: TObject);
  private
    { Private declarations }
  public
    NEdits : Integer;
    Edits: TEdit;
    m : matriz;
    f,c : Integer;
    con : Integer;
  end;

var
  frmEjecucion: TfrmEjecucion;


implementation

{$R *.dfm}

procedure TfrmEjecucion.Button1Click(Sender: TObject);
var
  i,j : Integer;
begin
  if Trim(Edt.Text) = '' then
  begin
    ShowMessage('Debe escribir un número');
    Exit;
  end;
  //Desicion para que no sea tan grande la matriz
  if StrToInt(Edt.Text) >= 11 then
  begin
    ShowMessage('El valor tiene que ser igual o menor a 10');
    Edt.Clear;
  end
  else
  begin
    //Establece el valor de la matriz y de los TEdit
    c := StrToInt(Edt.Text);
    f := StrToInt(Edt.Text);
    SetLength(m, StrToInt(Edt.Text),StrToInt(Edt.Text));
    Button1.Visible := False;
    Edt.Visible := False;
  end;
  //Creo y posiciono los Edits
 for i := 1 to c do
  begin
    for j := 1 to f do
    begin
      Edits := TEdit.Create(Self);
      Edits.Name := 'Edit' + IntToStr(i) + IntToStr(j);
      Edits.Text := '';
      Edits.Top := 21 * (i + 1);
      Edits.Left := 21 * (j + 1);
      Edits.Width := 20;
      Edits.Height := 20;
      Edits.AutoSize := False;
      Edits.Enabled := False;
      Edits.Parent := Panel1;
      Button3.Visible := True;
    end;
  end;
end;


procedure TfrmEjecucion.Button2Click(Sender: TObject);
begin
  m := nil;
end;

procedure TfrmEjecucion.Button3Click(Sender: TObject);
var
  i,j,c : Integer;
  Comp : TComponent;
begin
  //Agrega numeros a la matriz aleatoriamente.
  c := StrToInt(Edt.Text);
  For i := 0 to c do
  begin
    for j := 0 to c do
    begin
       Comp := FindComponent ('Edit' + IntToStr(i)+ IntToStr(j));
       if Assigned (Comp) then
       begin
         (Comp as TEdit).Text := IntToStr(Random(100));
       end;
    end;
  end;

end;

procedure TfrmEjecucion.Volver1Click(Sender: TObject);
begin
    Close;
end;

end.
Responder Con Cita
  #10  
Antiguo 25-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
Puedes probar algo como esto para no utilizar el método FindComponent
Código Delphi [-]
Const
    max = 10;
type
   TArrEdits = array[1..max, 1..max] of TEdit;

procedure CrearEdits(Edits:TArrEdits);
var
   I, J:integer;
begin
   Button1.Visible := False;
    for i:=1 to max do
        for J:=1 to max do
            begin
               Edits[I, J] := TEdit.Create(Self);
               Edits[I, J] .Text := '';
               Edits[I, J] .Top := 21 * (i + 1);
               Edits[I, J] .Left := 21 * (j + 1);
               Edits[I, J] .Width := 20;
               Edits[I, J] .Height := 20;
               Edits[I, J] .AutoSize := False;
               Edits[I, J] .Enabled := False;
               Edits[I, J] .Parent := Panel1;
               Button3.Visible := True;
            end;
end;

procedure llenarEdits(Edits:TArrEdits);
var
  I, J:integer;

begin
       for i:=1 to max do
        for J:=1 to max do
            begin
                Edits[I, J].text :=IntToStr(Random(100));
           end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ArrEdits:TArrEdits;
begin
   CrearEdits(ArrEdits);
   llenarEdits(ArrEdits);
end;

Última edición por Casimiro Notevi fecha: 25-10-2018 a las 09:37:52.
Responder Con Cita
  #11  
Antiguo 25-10-2018
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Tal como propone juniorSoft es lo más adecuado en mi opinión. No hay necesdad de utilizar el nombre de un componente cuando nosotros mismos lo creamos.

// Saludos
Responder Con Cita
  #12  
Antiguo 25-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
juniorSoft esta muy buena esa idea pero yo quiero utilizar una matriz dinamica y como veo en tu ejemplo es estatica ya que tu le pones el valor en max, como hago para que esa variable const no sea constante si no que el usuario la defina por medio de un edit.

no se si me hice entender.

gracias por vuestra ayuda.
Responder Con Cita
  #13  
Antiguo 25-10-2018
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
No hay gran problema con eso, con que sea estática, pues tú mismo fijaste un límite máximo. Puedes declarar la matriz con las dimensionaes máximas y cuando el usuario escoja el número de celdas (que deberá ser menor que el máximo) sólo creas ese número de componentes quedando el resto de entradas en nil.

De todas formas, si quieres que sea diinámica, tampoco hay problema. Declara un tipo de datos:

Código Delphi [-]
type
  TEditMatriz = array of array of TEdit;

y usas SetLength para definir las dimensiones según la elección del usuario.

// Saludos
Responder Con Cita
  #14  
Antiguo 25-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
Hola TavoBran,,


podrías hacer varios cambios

Código:
type
  TArrEdits =  array of array of TEdit;

procedure CrearEdits(var Edits:TArrEdits; MaxX, MaxY:integer);
var
   I, J:integer;
begin
   Button1.Visible := False;
    for i:=0 to MaxX-1 do
        for J:=0 to MaxY-1 do
            begin
               Edits[I, J] := TEdit.Create(Self);
               Edits[I, J] .Text := '';
               Edits[I, J] .Top := 21 * (i + 1);
               Edits[I, J] .Left := 21 * (j + 1);
               Edits[I, J] .Width := 20;
               Edits[I, J] .Height := 20;
               Edits[I, J] .AutoSize := False;
               Edits[I, J] .Enabled := False;
               Edits[I, J] .Parent := Panel1;
               Button3.Visible := True;
            end;
end;

procedure llenarEdits(var Edits:TArrEdits; MaxX, MaxY:integer);
var
  I, J:integer;

begin
       for i:=0 to MaxX-1 do
        for J:=0 to MaxY-1 do
            begin
                Edits[I, J].text :=IntToStr(Random(100));
           end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ArrEdits:TArrEdits;
  MX, MY:integer; //maximo de  columnas y filas
begin
     //pedir al usuario los valores de MX y MY
    SetLength(ArrEdits, MX, MY); //Aquí se establece las dimenciones del array en dos dimensiones
   CrearEdits(ArrEdits);
   llenarEdits(ArrEdits);
end;

Un detalle que falto en el anterior ejemplo es que los parámetros debes declararlos por referencia.

Otra observación: los Arrays dinámicos empiezan en cero(0).

Saludos,
Responder Con Cita
  #15  
Antiguo 25-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
También como dice Roman puedes establecer la constante a una cantidad limite
y pedirle al usuario que introduzca la cantidad que desea que no exceda la cantidad limite de edits.
Responder Con Cita
  #16  
Antiguo 25-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
Post

roman si eso yo lo defino como me dices solo que tengo otra duda

este es mi codigo

Código Delphi [-]

unit Ejecucion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus;

type
  TMatriz = array of array of TEdit;
  TfrmEjecucion = class(TForm)
    Button1: TButton;
    Edt: TEdit;
    Panel1: TPanel;
    Panel2: TPanel;
    Button2: TButton;
    Button3: TButton;
    MainMenu1: TMainMenu;
    Volver1: TMenuItem;
    Button4: TButton;
    Label1: TLabel;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmEjecucion: TfrmEjecucion;
  m : TMatriz;
  ma : Integer;

implementation

{$R *.dfm}

procedure CrearEdits(Edits:TMatriz);
var
  i,j :integer;
begin
  for i := 1 to ma do
  begin
    for j := 1 to ma do
    begin
      Edits[i,j]:=TEdit.Create(Self);
      Edits[i,j].Text := '';
      Edits[i,j].Top := 21 * (i + 1);
      Edits[i,j].Left := 21 * (j + 1);
      Edits[i,j].Width := 20;
      Edits[i,j].Height := 20;
      Edits[i,j].AutoSize := False;
      Edits[i,j].Enabled := False;
      Edits[i,j].Parent := Panel1;
    end;
  end;
end;


procedure llenarEdits(Edits:TMatriz);
var
  i, j:integer;
begin
  for i:=1 to ma do
  begin
    for j:=1 to ma do
    begin
      Edits[i,j].text := IntToStr(Random(100));
    end;
  end;
end;

procedure TfrmEjecucion.Button1Click(Sender: TObject);
var
  matriz:TMatriz;
  i,j : Integer;
begin
  if Trim(Edt.Text) = '' then
  begin
    ShowMessage('Debe escribir un número');
    Exit;
  end;
  //Grivera Desicion para que no sea tan grande la matriz
  if StrToInt(Edt.Text) >= 11 then
  begin
    ShowMessage('El valor tiene que ser igual o menor a 10');
    Edt.Clear;
  end
  else
  begin
    //Establece el valor de la matriz
    ma := StrToInt(Edt.Text);
    SetLength(m, StrToInt(Edt.Text),StrToInt(Edt.Text));
    Button1.Visible := False;
    Edt.Visible := False;
  end;
  CrearEdits(matriz);
  llenarEdits(matriz);
end;

end.

pero me genera dos errores que son al momento de crear los edit

Código Delphi [-]

Edits[i,j]:=TEdit.Create(Self);  // [dcc32 Error] Ejecucion.pas(46): E2003 Undeclared identifier: 'Self'
Edits[i,j].Parent := Panel1;  //[dcc32 Error] Ejecucion.pas(54): E2003 Undeclared identifier: 'Panel1'

lo tengo asi pero me genera error en esas dos lineas de codigo
Responder Con Cita
  #17  
Antiguo 25-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
Cita:
pero me genera dos errores que son al momento de crear los edit
El error esta en que estan como procedimientos sueltos, declaralos como métodos de la clase del formulario.
Responder Con Cita
  #18  
Antiguo 25-10-2018
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Eso es porque LlenarEdits y Crear Edits están declarados como procedimientos independientes. Debes declararlos como métodos del formulario:

Código Delphi [-]
TfrmEjecucion = class(TForm)
  procedure CrearEdits(Edits:TMatriz);
  procedure LlenarEdits(Edits:TMatriz);

y al momento de implementarlos, anteponer el prefijo TfrmEjecucion. al nombre del procedimiento.

// Saludos
Responder Con Cita
  #19  
Antiguo 25-10-2018
juniorSoft juniorSoft is offline
Miembro
 
Registrado: abr 2005
Posts: 178
Poder: 19
juniorSoft Va por buen camino
Disculpas porque el código lo hice directamente en el editor del foro por no tener delphi instalado en la pc que estoy utilizando.
Responder Con Cita
  #20  
Antiguo 25-10-2018
TavoBran TavoBran is offline
Miembro
NULL
 
Registrado: oct 2018
Posts: 13
Poder: 0
TavoBran Va por buen camino
JuniorSoft como asi estoy perdido.

es que no llevo mucho tiempo programando y aun hay cosas que no tengo claras si me puedes explicar te agradecería mucho.
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Asignar un evento a un componente creado en tiempo de ejecucion FGarcia OOP 7 13-09-2014 00:27:35
Evento en BitBtn creado en tiempo de ejecución newtron OOP 2 10-05-2012 17:54:14
eventos de PageControl creado en tiempo de ejecucion kaozz OOP 5 17-07-2007 16:02:10
Mostrar un texto creado en tiempo de ejecución FunBit Varios 1 10-10-2005 14:23:39
saber el nombre de un control creado en tiempo de ejecucion xxxlincexxx Varios 10 11-08-2003 00:45:54


La franja horaria es GMT +2. Ahora son las 13:26:15.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi