Foros del Web » Programación para mayores de 30 ;) » Java »

drawString no muestra lo escrito.

Estas en el tema de drawString no muestra lo escrito. en el foro de Java en Foros del Web. Hola gente, muy buenas a todos. Verán, soy novato en esto de java de hecho voy por el curso 60 de 276. Ps, estoy iniciandome ...
  #1 (permalink)  
Antiguo 23/02/2018, 06:21
 
Fecha de Ingreso: agosto-2015
Ubicación: Rosario - Argentina
Mensajes: 424
Antigüedad: 8 años, 8 meses
Puntos: 12
drawString no muestra lo escrito.

Hola gente, muy buenas a todos.

Verán, soy novato en esto de java de hecho voy por el curso 60 de 276.

Ps, estoy iniciandome en la parte de swing y me encuentro con dos problemas.

El primero, es que al utilizar el metodo drawString y mostrar la ventana, este texto no aparece...

Y el segundo, es que me sale una exception cuando intento crear un texto desde un metodo propio.

Aqui dejare los codigos--

Class Frame, crea la ventana:
Código Java:
Ver original
  1. package user_interface;
  2. import java.awt.Image;
  3. import java.awt.Toolkit;
  4.  
  5. import javax.swing.JFrame;
  6. class Frame extends JFrame{
  7.  
  8.     private JFrame window;
  9.     private String Icon;
  10.     private String Title;
  11.     private int[] Position = {0, 0};
  12.     private int[] Dimension = {0, 0};
  13.     private boolean Visible;
  14.     private boolean Resizable;
  15.     private int Operation;
  16.     private String Aligment;
  17.    
  18.     public Frame(String Icon, String Title, int W, int H, String Aligment, boolean Visible, boolean Resizable, int Operation){
  19.         this.Icon = Icon;
  20.         this.Title = Title;
  21.         this.Dimension[0] = W;
  22.         this.Dimension[1] = H;
  23.         this.Aligment = Aligment;
  24.         this.Resizable = Resizable;
  25.         this.Operation = Operation;
  26.         this.Visible = Visible;
  27.         this.CreateWindow();
  28.     }
  29.    
  30.     public void CreateWindow(){
  31.         this.window = new JFrame(this.Title);
  32.         this.window.setSize(this.Dimension[0], this.Dimension[1]);
  33.         this.SetPosition(this.Aligment);
  34.         this.window.setResizable(this.Resizable);
  35.         this.window.setDefaultCloseOperation(this.Operation);
  36.     }
  37.    
  38.     public void SetPosition(String pos){
  39.         switch(pos){
  40.             case "LEFT-CENTER":
  41.             case "CENTER-LEFT":
  42.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height/2)-(this.Dimension[1]/2));
  43.             break;
  44.             case "LEFT-BOTTOM":
  45.             case "BOTTOM-LEFT":
  46.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height)-(this.Dimension[1]));
  47.             break;
  48.             case "TOP-CENTER":
  49.             case "CENTER-TOP":
  50.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width/2)-(this.Dimension[0]/2));
  51.             break;
  52.             case "TOP-RIGHT":
  53.             case "RIGHT-TOP":
  54.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width)-(this.Dimension[0]));
  55.             break;
  56.             case "RIGHT-CENTER":
  57.             case "CENTER-RIGHT":
  58.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width)-(this.Dimension[0]));
  59.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height/2)-(this.Dimension[1]/2));
  60.             break;
  61.             case "RIGHT-BOTTOM":
  62.             case "BOTTOM-RIGHT":
  63.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width)-(this.Dimension[0]));
  64.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height)-(this.Dimension[1]));
  65.             break;
  66.             case "BOTTOM-CENTER":
  67.             case "CENTER-BOTTOM":
  68.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width/2)-(this.Dimension[0]/2));
  69.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height)-(this.Dimension[1]));
  70.             break;
  71.             case "CENTER-CENTER":
  72.                 this.Position[0] = ((Toolkit.getDefaultToolkit().getScreenSize().width/2)-(this.Dimension[0]/2));
  73.                 this.Position[1] = ((Toolkit.getDefaultToolkit().getScreenSize().height/2)-(this.Dimension[1]/2));
  74.             break;
  75.         }
  76.         this.window.setLocation(this.Position[0], this.Position[1]);
  77.     }
  78.    
  79.     public void SetVisible(boolean visible){
  80.         this.window.setVisible(visible);
  81.     }
  82.    
  83.     public void SetDimension(int W, int H){
  84.         this.Dimension[0] = W;
  85.         this.Dimension[1] = H;
  86.         this.window.setSize(W, H);
  87.     }
  88. }

Class Elements, no funciona como corresponde... pero es la que quiero para crear componentes.
Código Java:
Ver original
  1. package user_interface;
  2. import java.awt.Graphics;
  3. import javax.swing.JPanel;
  4.  
  5. class Elements extends JPanel{
  6.    
  7.     private Graphics Graphs;
  8.    
  9.     public void paintComponent(Graphics G){
  10.         this.Graphs = G;
  11.         super.paintComponent(this.Graphs);
  12.         this.Graphs.drawString("Hola Mundo", 10, 10); // Así debo de llamarlo para que no me de Exception alguna.
  13.     }
  14.    
  15.     public void AddText(String Text, int X, int Y){ // Este metodo tira Exception al ser llamado con la instancia de la clase "Elements".
  16.         this.Graphs.drawString(Text, X, Y);
  17.     }
  18.    
  19. }

Clase Init es la clase principal main
Código Java:
Ver original
  1. package user_interface;
  2. import javax.swing.JFrame;
  3.  
  4. public class init{
  5.     public static void main(String[] args){
  6.         Frame window = new Frame("favicon.png", "Mi Primera Ventana Java", 500, 250, "CENTER-CENTER", true, false, JFrame.EXIT_ON_CLOSE);
  7.         Elements components = new Elements();
  8.         window.add(components);
  9.         window.SetVisible(true);
  10.         // Al Ejecutar este code, muestra todo, menos el texto "Hola Mundo".
  11.     }
  12. }

¿Cual podria ser la solucion a estos dos problemas? y... ¿porque ocurre esto?
Me gustaria recibir una respuesta que sirva de aprendizaje.

Espero me ayuden y gracias de antemano!
  #2 (permalink)  
Antiguo 23/02/2018, 07:43
Avatar de Fuzzylog  
Fecha de Ingreso: agosto-2008
Ubicación: En internet
Mensajes: 2.511
Antigüedad: 15 años, 8 meses
Puntos: 188
Respuesta: drawString no muestra lo escrito.

Cita:
public void AddText(String Text, int X, int Y){ // Este metodo tira Exception al ser llamado con la instancia de la clase "Elements".
this.Graphs.drawString(Text, X, Y);
}
Tal y como lo has definido este método requiere que hayas ejecutado el método paintComponent, ya que por defecto this.Graphs está inicializado a null. Creo que el error te viene por ahí.

Tendrías que hacer un método para pasarle tú el Graphics correspondiente e inicializarlo en la clase o añadirlo a tu método AddText .

Con respecto al otro problema, no veo donde estás llamando al método paintComponent por ninguna parte. Si el hola mundo se muestra ahí, habría que llamarlo en la ejecución porque el hecho de instanciar la clase no garantiza la ejecución de todos sus métodos salvo que así lo definas en el constructor.

Mira también si tienes que realizar algún repaint() a mayores cuando efectúes cambios.

Revisa las convenciones de notación para java por favor, no da error pero chirría bastante.
__________________
if (fuzzy && smooth) {
fuzzylog = "c00l";
return true;
}
  #3 (permalink)  
Antiguo 24/02/2018, 15:34
 
Fecha de Ingreso: agosto-2015
Ubicación: Rosario - Argentina
Mensajes: 424
Antigüedad: 8 años, 8 meses
Puntos: 12
Respuesta: drawString no muestra lo escrito.

Ha... entiendo, estoy llamando a AddText() como si al momento de instanciar fuera paintComponent mi constructor, y claramente no lo es, y es por eso que siempre Graphs es null. Excelente explicacion.

El tema del drawString, despues de unos intentos, encontre que la solucion seria esta:
Código Java:
Ver original
  1. public void CreateWindow(){
  2.         this.window = new JFrame(this.Title);
  3.         this.window.setSize(this.Dimension[0], this.Dimension[1]);
  4.         this.SetPosition(this.Aligment);
  5.         this.window.setResizable(this.Resizable);
  6.         this.window.setDefaultCloseOperation(this.Operation);
  7.         this.window.add(new Elements()); // Agregamos componentes.
  8.         this.window.setVisible(this.Visible);
  9.     }

Claro que por ahora, esto me obliga a desarrollar la interfaz dentro de paintComponent, pero estoy seguro de que existe otra manera y desde luego la encontrare!

En fin, gracias por tu ayuda, me ha sido muy util! +1

Etiquetas: muestra, panel
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:21.