Como enviar um valor de uma classe para uma jlabel em uma tela?

8 respostas
pauloeduardo2906

Eu já coloquei uma dúvida bem parecida com essa aqui no fórum, mas eu resolvi passando o valor para um método (como disseram) e eu coloquei em uma jtextfield com o editable em false, mas eu estou trabalhando com uma imagem de fundo e a jlabel tem o fundo transparente, se alguém souber como colocar o jtextfield transparente também serve!!! O Código:

public class TelaStatus extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;
	
        private Char c=null;  //  @jve:decl-index=0:

	private JTextField txtNome = null;

	private JLabel lblFundo = null;

	private JLabel lblNome = null;

	public void setCharStatus(Char c){

		this.c=c;
		txtNome.setText(String.valueOf(c.getNome()));

		}
	
	
	
	

	/**
	 * @param owner
	 */
	public TelaStatus(Frame owner) {
		
		super(owner,"Status");
		initialize();
		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		
		this.setSize(570, 412);
		this.setTitle("Status");
		
		this.setModal(true);
		this.setLocation(500,250);
		this.setContentPane(getJContentPane());
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			
			
			//lblFundo = new JLabel();
			lblFundo.setBounds(new Rectangle(1, -1, 555, 399));
			lblFundo.setIcon(new ImageIcon("C:/Users/Paulo Eduardo/Desktop/BloodyWar/BloodyWarProject/src/imagens/fundo.png"));
			lblFundo.setText("");
			lblNome = new JLabel();
			lblNome.setBounds(new Rectangle(353, 31, 173, 82));
			lblNome.setText("");

			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setForeground(new Color(204, 0, 0));

			jContentPane.add(getTxtNome(), null);

			jContentPane.add(lblNome, null);
			jContentPane.add(lblFundo, null);

		}
		return jContentPane;
	}

8 Respostas

InicianteJavaHenriqu

Através de get e set.

:thumbup:

pauloeduardo2906

pow cara, não chegou a funcionar, ele da um erro quando eu chamo essa classe

InicianteJavaHenriqu

E como ficou o código atualizado :?: Qual é o erro :?:

:thumbup:

pauloeduardo2906

tela principal que chama a tela de status

package visao;

import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import banco.DAO;
import controle.ControleGame;
import entidade.Char;
import javax.swing.JTextField;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

import javax.swing.JMenuItem;
import javax.swing.JLabel;
import java.awt.SystemColor;
import javax.swing.JButton;
import java.awt.Dimension;

public class TelaGame extends JFrame {

	private static final long serialVersionUID = 1L;
	

	private JPanel jContentPane = null;
	
	private ControleGame controle=null;

	private Char c;  //  @jve:decl-index=0:
	
	private DAO dao=null;

	private JTextField txtLogin = null;

	private JMenuBar menuPrincipal = null;

	private JMenu menuFile = null;

	private JMenuItem menuSair = null;

	private JMenu menuAjuda = null;

	private JMenuItem menuHistoria = null;

	private JMenuItem menuSobre = null;
	
	

	private JMenu menuOpcao = null;

	private JMenuItem menuExcluir = null;

	private JMenuItem menuSalvar = null;

	private JFrame frame=null;

	private JButton btnStatus = null;
	
	private TelaStatus status=null;



	public void setChar(Char c){
	this.c=c;
	this.setTitle("Login: "+c.getLogin());
	txtLogin.setText(c.getLogin());


	}
	/**
	 * This is the default constructor
	 */
	public TelaGame() {
		controle=new ControleGame(this);
		initialize();
		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(833, 552);
		this.setJMenuBar(getMenuPrincipal());
		this.setLocation(300,50);
		this.setResizable(false);
		this.setContentPane(getJContentPane());
		
		
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {

			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getTxtLogin(), null);
			jContentPane.add(getBtnStatus(), null);

		}
		return jContentPane;
	}
	/**
	 * This method initializes txtLogin	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTxtLogin() {
		if (txtLogin == null) {
			txtLogin = new JTextField();
			txtLogin.setBounds(new Rectangle(-1, -1, 830, 28));
			txtLogin.setBackground(SystemColor.activeCaptionText);
			txtLogin.setFont(new Font("Gabriola", Font.BOLD, 24));
			txtLogin.setForeground(new Color(204, 204, 204));
			txtLogin.setEditable(false);
			
		}
		return txtLogin;
	}
	/**
	 * This method initializes menuPrincipal	
	 * 	
	 * @return javax.swing.JMenuBar	
	 */
	private JMenuBar getMenuPrincipal() {
		if (menuPrincipal == null) {
			menuPrincipal = new JMenuBar();
			menuPrincipal.add(getMenuFile());
			menuPrincipal.add(getMenuAjuda());
		}
		return menuPrincipal;
	}
	/**
	 * This method initializes menuFile	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getMenuFile() {
		if (menuFile == null) {
			menuFile = new JMenu();
			menuFile.setText("Arquivo");
			menuFile.setMnemonic(KeyEvent.VK_A);
			menuFile.add(getMenuOpcao());
			menuFile.addSeparator();
			menuFile.add(getMenuSair());
		
		}
		return menuFile;
	}
	/**
	 * This method initializes menuSair	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getMenuSair() {
		if (menuSair == null) {
			menuSair = new JMenuItem();
			menuSair.setText("Logout");
			menuSair.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					TelaLogin login=new TelaLogin();
					login.setVisible(true);
					dispose();
				}
			});
		}
		return menuSair;
	}
	/**
	 * This method initializes menuAjuda	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getMenuAjuda() {
		if (menuAjuda == null) {
			menuAjuda = new JMenu();
			menuAjuda.setText("Ajuda");
			menuAjuda.setMnemonic(KeyEvent.VK_A);
			menuAjuda.add(getMenuHistoria());
			menuAjuda.addSeparator();
			menuAjuda.add(getMenuSobre());
		}
		return menuAjuda;
	}
	/**
	 * This method initializes menuHistoria	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getMenuHistoria() {
		if (menuHistoria == null) {
			menuHistoria = new JMenuItem();
			menuHistoria.setText("História");
			menuHistoria.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					Historia h=new Historia(frame);
					h.setVisible(true);
					
					
				}
			});
			
			
		}
		return menuHistoria;
	}
	/**
	 * This method initializes menuSobre	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getMenuSobre() {
		if (menuSobre == null) {
			menuSobre = new JMenuItem();
			menuSobre.setText("Sobre");
			
			menuSobre.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
	TelaSobre sobre=new TelaSobre(frame);
 sobre.setVisible(true);
				}
			});
		}
		return menuSobre;
	}
	/**
	 * This method initializes menuOpcao	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getMenuOpcao() {
		if (menuOpcao == null) {
			menuOpcao = new JMenu();
			menuOpcao.setText("Opções");
			menuOpcao.add(getMenuSalvar());
			menuOpcao.add(getMenuExcluir());
		}
		return menuOpcao;
	}
	/**
	 * This method initializes menuExcluir	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getMenuExcluir() {
		if (menuExcluir == null) {
			menuExcluir = new JMenuItem();
			menuExcluir.setText("Excluir Conta");

			menuExcluir.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					String senha=JOptionPane.showInputDialog(null,"INFORME A SENHA DE SUA CONTA","INFORMAR SENHA",JOptionPane.WARNING_MESSAGE);
					if(senha.equals(c.getSenha())){
					TelaLogin login=null;
					try {
						dao=new DAO();
						Object[]options={"Confirmar","Cancelar"};
						int opcao=JOptionPane.showOptionDialog(null, "DESEJA EXCLUIR SUA CONTA?", "ALERTA", JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,(Icon) null,options,options[0]);
				
						if(opcao==0){
						dao.excluir(c);
						JOptionPane.showMessageDialog(null, "SUA CONTA FOI EXCLUÍDA COM SUCESSO!!!","EXCLUSÃO",JOptionPane.INFORMATION_MESSAGE);
						login=new TelaLogin();
						login.setVisible(true);
						dispose();
						}
					} catch (SQLException q) {
						JOptionPane
								.showMessageDialog(null, "ERRO DE SQL NO BANCO:  "
										+ q.getMessage(), "SQLException",
										JOptionPane.ERROR_MESSAGE);
					} catch (Exception q) {
						JOptionPane.showMessageDialog(null,
								"ERRO DESCONHECIDO:  " + q.getMessage(),
								"Exception", JOptionPane.ERROR_MESSAGE);
					}
					
				}else{
					JOptionPane.showMessageDialog(null, "SENHA INCORRETA!!","SUA CONTA NÃO FOI DELETADA",JOptionPane.INFORMATION_MESSAGE);
				}
					
					}
				}
					
					
					
					
			
					
				
			);
		
		
		
		
		
		}
		return menuExcluir;
	}
	/**
	 * This method initializes menuSalvar	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getMenuSalvar() {
		if (menuSalvar == null) {
			menuSalvar = new JMenuItem();
			menuSalvar.setText("Salvar Jogo");
			
			menuSalvar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					JOptionPane.showMessageDialog(null, "FUNCIONOU!!!");
				}
			});
			
		}
		return menuSalvar;
	}
	/**
	 * This method initializes btnStatus	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnStatus() {
		if (btnStatus == null) {
			btnStatus = new JButton();
			btnStatus.setBounds(new Rectangle(0, 23, 72, 33));
			btnStatus.setBackground(Color.black);
			btnStatus.setFont(new Font("Gabriola", Font.BOLD, 18));
			btnStatus.setForeground(Color.white);
			btnStatus.setText("Status");
			btnStatus.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					status=new TelaStatus(frame); //aqui eu chamo a tela de status
					status.setCharStatus(c);
					status.setVisible(true);
					
				}
			});
			
		}
		return btnStatus;
	}

}

Tela que chamo

public class TelaStatus extends JDialog {  
  
    private static final long serialVersionUID = 1L;  
  
    private JPanel jContentPane = null;  
      
        private Char c=null;  //  @jve:decl-index=0:  
  
    private JTextField txtNome = null;  
  
    private JLabel lblFundo = null;  
  
    private JLabel lblNome = null;  
  
    public void setCharStatus(Char c){  
  
        this.c=c;  
        txtNome.setText(String.valueOf(c.getNome()));  
  
        }  
      
public Char getCharStatus(){
	return c;
}
      
      
      
  
    /** 
     * @param owner 
     */  
    public TelaStatus(Frame owner) {  
          
        super(owner,"Status");  
        initialize();  
          
    }  
  
    /** 
     * This method initializes this 
     *  
     * @return void 
     */  
    private void initialize() {  
          
        this.setSize(570, 412);  
        this.setTitle("Status");  
          
        this.setModal(true);  
        this.setLocation(500,250);  
        this.setContentPane(getJContentPane());  
    }  
  
    /** 
     * This method initializes jContentPane 
     *  
     * @return javax.swing.JPanel 
     */  
    private JPanel getJContentPane() {  
        if (jContentPane == null) {  
              
              
            //lblFundo = new JLabel();  
            lblFundo.setBounds(new Rectangle(1, -1, 555, 399));  
            lblFundo.setIcon(new ImageIcon("C:/Users/Paulo Eduardo/Desktop/BloodyWar/BloodyWarProject/src/imagens/fundo.png"));  
            lblFundo.setText("");  
            lblNome = new JLabel();  
            lblNome.setBounds(new Rectangle(353, 31, 173, 82));  
            lblNome.setText(""+);  
  
            jContentPane = new JPanel();  
            jContentPane.setLayout(null);  
            jContentPane.setForeground(new Color(204, 0, 0));  
  
            jContentPane.add(getTxtNome(), null);  
  
            jContentPane.add(lblNome, null);  
            jContentPane.add(lblFundo, null);  
  
        }  
        return jContentPane;  
    }

acontece esse erro:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at visao.TelaStatus.getJContentPane(TelaStatus.java:64)
	at visao.TelaStatus.initialize(TelaStatus.java:51)
	at visao.TelaStatus.<init>(TelaStatus.java:35)
	at visao.TelaGame$6.actionPerformed(TelaGame.java:347)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
pauloeduardo2906

Acabei deixando aquela label na linha 63 da tela de status em comentário para poder trabalhar com os componentes, pq com uma label com imagem na frente fica difícil, mas acontece o mesmo erro independente dessa linha

InicianteJavaHenriqu

É bastante código, por isso não cheguei a executar, mas como o erro é NullPointerException verifique se você está instanciando todos os atributos (JButton, JLabel…) antes de chamar suas propriedades e verifique também se as imagens estão sendo buscadas (existe) na pasta: C:/Users/Paulo Eduardo/Desktop/BloodyWar/BloodyWarProject/src/imagens/, verifique também se você não fez algo do tipo botao = null e depois tentou usá-lo.

Na verdade não é independente desta linha está linha comentada também é um problema, porque você não instancia a JLabel, mas logo em seguida a usa:

lblFundo.setBounds(new Rectangle(1, -1, 555, 399));    
lblFundo.setIcon(new ImageIcon("C:/Users/Paulo Eduardo/Desktop/BloodyWar/BloodyWarProject/src/imagens/fundo.png"));    
lblFundo.setText("");

:thumbup:

pauloeduardo2906

Não corro o risco de não instanciar porque ao criar uma jlabel no eclipse pelo visual editor, ele faz isso pra mim, na linha 68 da classe TelaStatus, e a linha 71 eu coloquei incompleto, no meu programa ficou assim nessa linha:

lblNome.setText(""+getCharStatus().getNome());
pauloeduardo2906

Eu estava pensando em criar uma classe de controle para um metodo realizar essa passagem de valor, mas como eu estou trabalhando com jdialog, acontece um erro que não aconteceria se eu estivesse usando jframe :?

Criado 9 de agosto de 2012
Ultima resposta 22 de ago. de 2012
Respostas 8
Participantes 2