Por que componente não aparece?

5 respostas Resolvido
Thallysson

Olá, eu possuo uma classe component que eu criei, ela está assim:
`

package Objects;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;

import javax.swing.JComponent;

public class Sol extends JComponent{  
     private int x = 0;        
     private int y = 0;  
     protected void paintComponent(Graphics g) {     
        Graphics2D g2d = (Graphics2D) g.create();     
           
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        Color color1 = Color.orange;
        Color color2 = Color.yellow;
        GradientPaint gp = new GradientPaint(0,0, color1, 0,90, color2);
        g2d.setPaint(gp);  
        g2d.fill (new Ellipse2D.Double(0,0, 100, 100));
        g2d.dispose();  
    }  
public int getX() {  
    return x;  
}  
public void setX(int x) {  
    this.x = x;  
}  
public int getY() {  
    return y;  
}  
public void setY(int y) {  
    this.y = y;  
}     

   
}

`
Porém em outra classe eu tentei adiciona-la ao JPanel coisas que possui o gerenciador de layout flowlayout assim:

Sol s = new Sol(); coisas.add(s);
Porque que a bolinha não é exibida?

5 Respostas

D

O panel provavelmente possui tamanho zero

panel.setPreferredSize(new Dimension(100, 100));
panel.setSize(new Dimension(100, 100));
Thallysson

Eu acho que não, pois eu fiz isso e continuou sem aparecer, minha intenção inicial era adicionar o component no canto superior direito, o problema é que ele nem aparece.

Thallysson

Eu acho melhor postar meu código completo das classes, meu objetivo era emular um céu com pássaros, nuvens e sol, somente invocando a classe Ceu que estende de jpanel,minhas classes são as seguintes:
Classe sol - era pra ser um simples circulo com preenchimento degradê que seria adicionado no canto superior direito da classe Ceu

package Objects;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;

import javax.swing.JComponent;

public class Sol extends JComponent{  
     private int x = 0;        
     private int y = 0;  
     protected void paintComponent(Graphics g) {     
        Graphics2D g2d = (Graphics2D) g.create();     
           
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        Color color1 = Color.orange;
        Color color2 = Color.yellow;
        GradientPaint gp = new GradientPaint(0,0, color1, 0,90, color2);
        g2d.setPaint(gp);  
        g2d.fill (new Ellipse2D.Double(0,0, 100, 100));
        g2d.dispose();
    }  
public int getX() {  
    return x;  
}  
public void setX(int x) {  
    this.x = x;  
}  
public int getY() {  
    return y;  
}  
public void setY(int y) {  
    this.y = y;  
}     

   
}

Classe Ceu, era pra cer uma classe que estende de jpanel que deveria ter um background azul, e deveria conter um objeto sol no canto superior direito alem dos objetos que se locomovem pela tela
`

package Objects;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.AlphaComposite;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Ceu extends JPanel{ 
  Random rdm = new Random();
  boolean bo;
  int passquant;
  int nquant;
  boolean bo2;

   Ceu(boolean passaros,boolean nuvens,boolean dia,boolean noite,Color fundodia,Color fundonoite,int windowwidth, int windowheight){
     if(passaros==true){
	new Thread(new Runnable(){
     public void run(){
    	System.out.println("com passaros");
    	
    	 int width = windowwidth;

  	   passquant = rdm.nextInt(2);
  	 while(true){
  	  for(int i = 0; i<=passquant; ++i){
  	   bo = rdm.nextBoolean();
  	   int direcao;
  	   int xInicial;
  	   String imagem;
  	   if(bo==true){ 
  	     direcao = 1;
  	     xInicial = 0;
  	     imagem = "/Assets/pássaro-i.gif";
  	   }else{
  	     direcao = -1;
  	     xInicial = windowwidth-100;
  	     imagem = "/Assets/pássaro.gif";
  	   }
  	   ImageIcon img = new ImageIcon(getClass().getResource(imagem));
  	   img.setImage(img.getImage().getScaledInstance(img.getIconWidth()-500,img.getIconHeight()-400, Image.SCALE_DEFAULT));
  	   int largura = img.getIconWidth();
  	   int altura = img.getIconHeight();
  	   JLabel p = new JLabel(img);
  	   p.setBounds(xInicial,rdm.nextInt(windowheight),largura,altura);
       add(p);
       repaint();
       new Thread(new Runnable(){
  	    	 public void run(){
  	    	   int speed = rdm.nextInt(4)+2;
  	    	   speed = direcao * speed;
  	    	   URL urlsompassaro = getClass().getResource("/Assets/Som pássaro.wav");
  	  		    AudioClip sompassaro = Applet.newAudioClip(urlsompassaro);
  	   		    sompassaro.loop();
  	    		while(true){
  	       		 if(p.getX() > width || p.getX() < -largura){
  	       			remove(p);
  	       			sompassaro.stop();
  	       			return;
  	       		 }else{
  	       		    p.setBounds(p.getX()+speed,p.getY(),largura,altura);
  	       		 }
  		       		 try {
  						Thread.sleep(10);
  					} catch (InterruptedException e) {
  						e.printStackTrace();
  					}
  		    		}
  	    	 }
  	     }).start();
  	   
  	     passquant = rdm.nextInt(2);
  	    }
  	  try {
  			Thread.sleep(7000);
  		} catch (InterruptedException e) {
  			e.printStackTrace();
  		}
  	    }	     }
	}).start();
	
  }
 if(nuvens==true){
	new Thread(new Runnable(){
		public void run(){
			System.out.println("com nuvens");

			 
		 	   int width = windowwidth;
		 	   nquant = rdm.nextInt(2);
		 	 while(true){
		 	  for(int i = 0; i<=nquant; ++i){
		 	   bo2 = rdm.nextBoolean();
		 	   int direcao;
		 	   int xInicial;
		 	   if(bo2==true){ 
		 	     direcao = 1;
		 	     xInicial = 0;
		 	   }else{
		 	     direcao = -1;
		 	     xInicial = windowwidth-100;
		 	   }
		 	   BufferedImage buffer = null;
		 	   int qual = rdm.nextInt(3);
		 	   if(qual==0){
		 			try {
		 				buffer = ImageIO.read(getClass().getResource("/Assets/Nuvem.png"));
		 			} catch (IOException e) {
		 				e.printStackTrace();
		 			}
		 	   }else if(qual==1){
		 		   try {
		 				buffer = ImageIO.read(getClass().getResource("/Assets/Nuvem2.png"));
		 			} catch (IOException e) {
		 				e.printStackTrace();
		 			}
		 	   }else if(qual==2){
		 		   try {
		 				buffer = ImageIO.read(getClass().getResource("/Assets/Nuvem3.png"));
		 			} catch (IOException e) {
		 				e.printStackTrace();
		 			}
		 	   }
		 	    BufferedImage completa = applyAlpha(buffer,1.0f);
		 	    Image image = completa.getScaledInstance(completa.getWidth(),completa.getHeight(),Image.SCALE_DEFAULT);
		 	    ImageIcon icon = new ImageIcon(image);
		 	    int altura = icon.getIconHeight();
		 	    int largura = icon.getIconWidth();
		 		JLabel l = new JLabel(icon);
		 	   l.setBounds(xInicial,rdm.nextInt(windowheight),largura,altura);
		 	   add(l);
		 	   repaint();
		 	     new Thread(new Runnable(){
		 	    	 public void run(){
		 	    	   int speed = 1;
		 	    	   speed = direcao * speed;
		 	    		while(true){
		 	       		 if(l.getX() > width || l.getX() < -largura){
		 	       			remove(l);
		 	       			return;
		 	       		 }else{
		 	       		    l.setBounds(l.getX()+speed,l.getY(),largura,altura);
		 	       		 }
		 		       		 try {
		 						Thread.sleep(50);
		 					} catch (InterruptedException e) {
		 						e.printStackTrace();
		 					}
		 		    		}
		 	    	 }
		 	     }).start();
		 	   
		 	     nquant = rdm.nextInt(2);
		 	    }
		 	  try {
		 			Thread.sleep(7000);
		 		} catch (InterruptedException e) {
		 			e.printStackTrace();
		 		}
		 	    }
			
		}
	}).start();
 }
 if(dia==true){
	new Thread(new Runnable(){
		public void run(){
		 Sol s = new Sol();
		 add(s);
	  }
	}).start(); 
 }
  }
    private BufferedImage applyAlpha(BufferedImage pb, float alpha) {
    BufferedImage img = new BufferedImage(pb.getWidth(), pb.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = (Graphics2D) img.getGraphics().create();
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.drawImage(pb, 0, 0, null);
        g2.dispose();
        return img;
    }

  }

`
E então a classe TestaCeu, onde eu simplesmente invoco Ceu para ver no que dá.

`

package Objects;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class TestaCeu extends JFrame{
   TestaCeu(){
    setTitle("Testa ceu");
	setVisible(true);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setLocationRelativeTo(null);
	setExtendedState(JFrame.MAXIMIZED_BOTH);
    
    Ceu ce = new Ceu(true,true,true,false,new Color(242,252,255),null,this.getWidth(),this.getHeight());
    
	add(ce);
	repaint();
   }
  public static void main(String[]args){
  TestaCeu c = new TestaCeu();
 }

}
`
Como que você acha que eu posso adicionar o component sol?

D
Solucao aceita

Na classe ceu:

Ceu(boolean passaros,boolean nuvens,boolean dia,boolean noite,Color fundodia,Color fundonoite,int windowwidth, int windowheight){
     setLayout(null);
     if(passaros==true){

e

if(dia==true){
	new Thread(new Runnable(){
		public void run(){
		 Sol s = new Sol();
		 add(s);
             // Verifique se adicionando a seguinte linha funciona
		 s.setBounds(150, 300, 100, 100);
	  }
	}).start(); 
 }

Na classe Sol,o jComponent já tem xy, então deixe assim:

public class Sol extends JComponent{  
     protected void paintComponent(Graphics g) {     
        Graphics2D g2d = (Graphics2D) g.create();     
           
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        Color color1 = Color.orange;
        Color color2 = Color.yellow;
        GradientPaint gp = new GradientPaint(0,0, color1, 0,90, color2);
        g2d.setPaint(gp);  
        g2d.fill (new Ellipse2D.Double(0,0, 100, 100));
        g2d.dispose();  
    } 
}
Thallysson

OK, muito obrigado, funcionou perfeitamente :slightly_smiling:

Criado 16 de março de 2016
Ultima resposta 17 de mar. de 2016
Respostas 5
Participantes 2