Habilitar botões

19 respostas
R

Olá pessoal.
Estou desenvolvendo um ‘sisteminha’ e não sei como fazer para quando eu clicar sobre no botão ‘Novo’ desabilitar os outros botoes como o ‘alterar’, p.ex.
Tentei desta forma:

if(botao.getName().equals(“btnNovo”)){

if(btnNovo.isSelected()){
			btnAlterar.setEnabled(true);
		}

19 Respostas

dstori

tenta assim:

btnAlterar.setEnabled(!btnNovo.isSelected()); 
btnExcluir.setEnabled(!btnNovo.isSelected()); 
.
.
.
R

Continua ocorrendo o mesmo erro e o botão “alterar” não desabilita quando pressiono o botão “novo”, tem alguma outra sugestão?
se ajudar em alguma coisa o erro é esse: Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException

dstori

Estes botões foram criados?

btnNovo = new JButton("Incluri");
btnAlterar = ...
FabricioPJ

Aqui eu faço assim:

No Action do seu botão “NOVO” ponha o seguinte código:

btExcluir.setEnabled(false); btSeuBotao.setEnabled(false);

71C4700

Cara seria bom voce criar uma enumeração pra constrolar os estados dos botões e um metodo que era chamado sempre que clicase em algum botão.
Ficaria mais ou menos assim :

private enum Status{
     NOVO,
     ALTERAR,
     EXCLUIR;
} 
// Esta enumerção  pra controlar o estado dos botões

private Status botaoAcionado = Status.NOVO;

private void verificaAcao(){
// aqui verifica o status e modifica os estados dos outros botões
 if(NOVO == botaoAcionado){
     //Faz alguma coisa
     botaoEditar.setEnable(false);
 }

}

Mas caso não resolva, eu tambem estou com este problema

R

até ki sua ideia e a do camarada ai em cima não é ruim, no entanto, não não afetou em nada em meu programa, continua da mesma forma, os botões nao desabilitam quando pressiono “Novo” i agora? ja rodei pela internet e não acho nada, não sei o que fazer. Ja tentei várias metódos i nada! :frowning:

M

Você precisa adicionar um Listener ao seu botão. O que ele fará é “prestar atenção” em todas as ações que acontecerem no seu botão(no caso do ActionListener). Lá dentro você coloca:

jButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { jButton.setEnabled(false); jButton1.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false); } });

E no botão de gravar, ou algo parecido, você muda para setEnabled(true).

R

Desculpe minha ignorancia, mas naum entendi mto bein.
Meu botao tah definido dessa forma o actionListener:

btnNovo.addActionListener(this);

e eu to fazendo a validação nesta parte [color=red][b]public void actionPerformed(ActionEvent arg0)[/b[/color]]{

Component botao = (Component)arg0.getSource();

if (botao.getName().equals("btnNovo")){

   btnAlterar.setEnabled(!btnNovo.isSelected());

}

}

Me parece estar tudo correto, so parece msm. Não sei o que fazer.

ivo_costa

Manda a stack de erro completa e o código fonte entre as tags CODE

R

[code [package forms;

import java.awt.BorderLayout;

import java.awt.Component;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.text.ParseException;

import java.util.Observable;

import java.util.Observer;
import javax.swing.BorderFactory;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFormattedTextField;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.text.MaskFormatter;

import ui.util.layouts.ParagraphLayout;

public class frmCadCliente extends JFrame implements ActionListener, Observer{

private JLabel lblNome,lblEndereco,lblNum,lblTelRes,lblTelCel,lblRG,lblCPF;
private JTextField txtNome,txtEndereco,txtNum;
private JPanel painel;
private JFormattedTextField txtCPF,txtRG,txtTelRes,txtTelCel;
private JButton btnNovo,btnAlterar,btnSalvar,btnAnterior,btnProximo,btnSair,btnExcluir;


public frmCadCliente() {
	// modelagem da tela
	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	int a=710;//largura
	int b = 400;//altura
	setSize(a,b);
	setLocation(380,200);
	setResizable (false);
	setTitle ("Cadastro de Cliente");

	// definindo gerenciador de layout
	setLayout(new BorderLayout());
	//criando um painel e colocando uma borda em volta da tela
	painel = new JPanel(new ParagraphLayout());
	add("Center",painel);
	painel.setBorder(BorderFactory.createTitledBorder( "Dados do Cliente"));

	// menus
	JMenuBar barra = new JMenuBar();
	setJMenuBar(barra);
	//inicio
	JMenu inicio = new JMenu("Inicio");
	inicio.setMnemonic('i');
	ImageIcon iconeArq = new ImageIcon(ClassLoader.getSystemResource("images/arquivo.png"));
	inicio.setIcon(iconeArq);
	barra.add(inicio);

	// ajuda
	JMenu ajuda = new JMenu("Ajuda");
	setJMenuBar(barra);
	ajuda.setMnemonic('a');
	ImageIcon iconeArq1 = new ImageIcon(ClassLoader.getSystemResource("images/help.png"));
	ajuda.setIcon(iconeArq1);
	barra.add(ajuda);

	JMenu sobre = new JMenu("Sobre");
	setJMenuBar(barra);
	sobre.setMnemonic('S');
	ImageIcon iconeArq4 = new ImageIcon(ClassLoader.getSystemResource("images/livro.png"));
	sobre.setIcon(iconeArq4);
	barra.add(sobre);

	// item novo
	JMenuItem item = new JMenuItem("Novo");
	inicio.add(item);
	item.setName("btnNovo");
	item.addActionListener(this);
	ImageIcon iconeNovo_A = new ImageIcon(ClassLoader.getSystemResource("images/novo.gif"));
	item.setIcon(iconeNovo_A);
	inicio.add(item);

	//item salvar
	JMenuItem item1 = new JMenuItem("Salvar");
	inicio.add(item1);
	item1.setName("btnSalvar");
	item1.addActionListener(this);
	ImageIcon iconeNovo_Ae = new ImageIcon(ClassLoader.getSystemResource("images/ok.png"));
	item1.setIcon(iconeNovo_Ae);
	inicio.add(item1);

	// item alterar
	JMenuItem item2 = new JMenuItem("Alterar");
	inicio.add(item2);
	item2.setName("btnAlterar");
	item2.addActionListener(this);
	ImageIcon iconeNovo_As = new ImageIcon(ClassLoader.getSystemResource("images/page_edit.png"));
	item2.setIcon(iconeNovo_As);
	inicio.add(item2);

	// item excluir
	JMenuItem item3 = new JMenuItem("Excluir");
	inicio.add(item3);
	item3.setName("btnExcluir");
	item3.addActionListener(this);
	ImageIcon iconeNovo_Aa = new ImageIcon(ClassLoader.getSystemResource("images/excluir_1.gif"));
	item3.setIcon(iconeNovo_Aa);
	inicio.add(item3);
	// item sair
	JMenuItem item4 = new JMenuItem("Sair");
	inicio.add(item4);
	item4.setName("btnSair");
	item4.addActionListener(this);
	ImageIcon iconeNovo_Ab = new ImageIcon(ClassLoader.getSystemResource("images/fechar_sair.gif"));
	item4.setIcon(iconeNovo_Ab);
	inicio.add(item4);

	inicio.insertSeparator(4);

	// campos e nomes 
	lblNome = new JLabel ("Nome :");
	lblNome .setFont (new Font ("Arial new",Font.BOLD,18));
	txtNome = new JTextField (25);
	txtNome .setFont (new Font ("Arial new",Font.BOLD,18));
	txtNome.setToolTipText("Digite o Nome Completo do Cliente");
	txtNome.setEditable(false);

	lblEndereco = new JLabel ("Endereço :");
	lblEndereco.setFont (new Font ("Arial new",Font.BOLD,18));

	txtEndereco = new JTextField (25);
	txtEndereco.setFont (new Font ("Arial new",Font.BOLD,18));
	txtEndereco.setToolTipText("Digite o Endereço do Cliente");
	txtEndereco.setEditable(false);

	lblNum = new JLabel ("Número:");
	lblNum.setFont (new Font ("Arial new",Font.BOLD,18));

	txtNum = new JTextField (25);
	txtNum.setFont (new Font ("Arial new",Font.BOLD,18));
	txtNum.setToolTipText("Digite o Número da Casa do Cliente");
	txtNum.setEditable(false);

	lblCPF = new JLabel ("CPF :");
	lblCPF.setFont (new Font ("Arial new",Font.BOLD,18));
	lblRG = new JLabel ("RG :");
	lblRG.setFont (new Font ("Arial new",Font.BOLD,18));

	lblTelRes = new JLabel ("Telefone Residencial:");
	lblTelRes.setFont (new Font ("Arial new",Font.BOLD,18));

	lblTelCel = new JLabel ("Telefone Celular:");
	lblTelCel.setFont (new Font ("Arial new",Font.BOLD,18));

	MaskFormatter CPF = null;
	MaskFormatter RG = null;
	MaskFormatter Residencial = null;
	MaskFormatter Celular = null;
	try {
		CPF = new MaskFormatter("###.###.###-##                                                                       ");
		RG = new MaskFormatter ("#.###-###-#                                                                          ");
		Celular= new MaskFormatter ("####-####                                                                            ");
		Residencial = new MaskFormatter("####-####                                                                            "); 

	} catch (ParseException e) {
		e.printStackTrace();
	}
	txtCPF = new JFormattedTextField(CPF);
	txtCPF.setEditable(false);
	txtCPF .setFont (new Font ("Arial new",Font.BOLD,18));
	txtCPF.setToolTipText("Digite o CPF Completo do Cliente");

	txtRG= new JFormattedTextField (RG);
	txtRG.setEditable(false);
	txtRG .setFont (new Font ("Arial new",Font.BOLD,18));
	txtRG.setToolTipText("Digite o RG Completo do Cliente");

	txtTelCel= new JFormattedTextField (Celular);
	txtTelCel.setEditable(false);
	txtTelCel.setFont (new Font ("Arial new",Font.BOLD,18));
	txtTelCel.setToolTipText("Digite o Telefone Celular do Cliente");

	txtTelRes = new JFormattedTextField (Residencial);
	txtTelRes.setEditable(false);
	txtTelRes.setFont (new Font ("Arial new",Font.BOLD,18));
	txtTelRes.setToolTipText("Digite o Telefone Residencial do Cliente");

	setLayout(new FlowLayout());

	//botões
	//		instanciando botao anterior	
	JButton btnAnterior= new JButton();
	btnAnterior.setName ("btnAnterior");
	btnAnterior.setFont((new java.awt.Font("Arial New", 0, 18)));
	btnAnterior.setToolTipText("Pressione para Voltar");
	ImageIcon iconeAnterior = new ImageIcon(ClassLoader.getSystemResource("images/esquerda.png"));
	btnAnterior.setIcon(iconeAnterior);
	btnAnterior.setEnabled(true);
	btnAnterior.addActionListener(this);
	add(btnAnterior);

	JButton btnNovo= new JButton("Novo");
	btnNovo.setName ("btnNovo");
	ImageIcon iconeNovo =new ImageIcon(ClassLoader.getSystemResource("images/novo.gif"));
	btnNovo.setIcon(iconeNovo);
	btnNovo.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnNovo.setToolTipText("Pressione para cadastrar o cliente");
	btnNovo.addActionListener(this);
	add(btnNovo);

	//criando,dando nome ,dando acao ao botao e addicionando ao painel

	JButton btnAlterar= new JButton("Alterar");
	btnAlterar.setName ("btnAlterar");
	ImageIcon iconeAlterar = new ImageIcon(ClassLoader.getSystemResource("images/page_edit.png"));
	btnAlterar.setIcon(iconeAlterar);
	btnAlterar.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnAlterar.setToolTipText("Pressione para alterar ou modificar dados do cliente");
	btnAlterar.setEnabled(true);
	btnAlterar.addActionListener(this);
	add(btnAlterar);

	//botao excluir
	JButton btnExcluir= new JButton("Excluir");
	ImageIcon iconeExcluir = new ImageIcon(ClassLoader.getSystemResource("images/excluir_1.gif"));
	btnExcluir.setIcon(iconeExcluir);
	btnExcluir.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnExcluir.setToolTipText("Pressione excluir o cliente");
	btnExcluir.setName ("btnExcluir");
	btnExcluir.setEnabled(true);
	btnExcluir.addActionListener(this);
	add(btnExcluir);

	//criando,dando nome ,dando acao ao botao e addicionando ao painel
	JButton btnSalvar= new JButton("Salvar");
	ImageIcon iconeSalvar = new ImageIcon(ClassLoader.getSystemResource("images/ok.png"));
	btnSalvar.setIcon(iconeSalvar);
	btnSalvar.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnSalvar.setToolTipText("Pressione para salvar um cliente");
	btnSalvar.setName ("btnSalvar");
	btnSalvar.setEnabled(true);
	btnSalvar.addActionListener(this);
	add(btnSalvar);

	//		criando,dando nome ,dando acao ao botao e addicionando ao painel
	JButton btnSair= new JButton("Sair");
	btnSair.setName ("btnSair");
	ImageIcon iconeSair = new ImageIcon(ClassLoader.getSystemResource("images/fechar_sair.gif"));
	btnSair.setIcon(iconeSair);
	btnSair.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnSair.setToolTipText("Pressione para sair");
	btnSair.addActionListener(this);
	add(btnSair);

	// instanciando botao proximo
	JButton btnProximo= new JButton();
	btnProximo.setName ("btnProximo");
	ImageIcon iconeProximo = new ImageIcon(ClassLoader.getSystemResource("images/direita.png"));
	btnProximo.setIcon(iconeProximo);
	btnProximo.setFont((new java.awt.Font("Times new roman", 0, 22)));
	btnProximo.setToolTipText("Pressione para avançar");
	btnProximo.setEnabled(true);
	btnProximo.addActionListener(this);
	add(btnProximo);

	// painel que adiciona os componentes
	painel.add(lblNome,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtNome);
	painel.add(lblEndereco,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtEndereco);
	painel.add(lblNum,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtNum);
	painel.add (lblTelRes,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtTelRes);
	painel.add(lblTelCel,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtTelCel);
	painel.add(lblCPF,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtCPF);
	painel.add(lblRG,ParagraphLayout.NEW_PARAGRAPH);
	painel.add(txtRG);

	setVisible(true);
}



public static void main(String[] args) {

	frmCadCliente  telaCadPro = new frmCadCliente();

}

public void actionPerformed(ActionEvent arg0) {

	Component botao = (Component)arg0.getSource();


	if (botao.getName().equals("btnSalvar")){

		if (txtNome.getText().length() == 0){
			JOptionPane.showMessageDialog(this, "Digite o NOME ","Atenção",JOptionPane.CANCEL_OPTION);
			return;
		}
		if (txtEndereco.getText().length() == 0){
			JOptionPane.showMessageDialog(this, "Digite o ENDEREÇO ","Atenção",JOptionPane.CANCEL_OPTION);
			return;
		}
		if (txtNum.getText().length() == 0){
			JOptionPane.showMessageDialog(this, "Digite o NÚMERO DA CASA ","Atenção",JOptionPane.CANCEL_OPTION);
			return;
		}
		if (txtCPF.getText().replaceAll("\\.*-*", "").trim().length() == 0){
			JOptionPane.showMessageDialog(this, "Digite o CPF ","Atenção",JOptionPane.CANCEL_OPTION);
			return;
		}

		if (txtRG.getText().replaceAll("\\.*-*", "").trim().length() == 0){
			JOptionPane.showMessageDialog(this, "Digite o RG ","Atenção",JOptionPane.CANCEL_OPTION);
			return;

		}
	}
	[b]if (botao.getName().equals("btnNovo")){[/b]
		txtNome.setEditable(true);
		txtEndereco.setEditable(true);
		txtNum.setEditable(true);
		txtTelRes.setEditable(true);
		txtTelCel.setEditable(true);
		txtCPF.setEditable(true);
		txtRG.setEditable(true);
		txtNome.requestFocus();

		[b]btnAlterar.setEnabled(!btnNovo.isSelected());   [/b]
		

	}
	if(botao.getName().equals("btnSair")){
		System.exit(0);
	}	

	  
		
		

}

public void update(Observable arg0, Object arg1) {
	// TODO Auto-generated method stub

}

}
]/code]

Stack de erro:

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException

at forms.frmCadCliente.actionPerformed(frmCadCliente.java:341)

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.AWTEventMulticaster.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)
M

Olhei por cima, mas não vi esses atributos sendo incializados

private JFormattedTextField txtCPF, txtRG, txtTelRes, txtTelCel;

E são chamados aqui:

if (botao.getName().equals("btnSalvar")) {
			if (txtNome.getText().length() == 0) {
				JOptionPane.showMessageDialog(this, "Digite o NOME ",
						"Atenção", JOptionPane.CANCEL_OPTION);
				return;
			}
			if (txtEndereco.getText().length() == 0) {
				JOptionPane.showMessageDialog(this, "Digite o ENDEREÇO ",
						"Atenção", JOptionPane.CANCEL_OPTION);
				return;
			}
			if (txtNum.getText().length() == 0) {
				JOptionPane.showMessageDialog(this, "Digite o NÚMERO DA CASA ",
						"Atenção", JOptionPane.CANCEL_OPTION);
				return;
			}
			if (txtCPF.getText().replaceAll("\\.*-*", "").trim().length() == 0) {
				JOptionPane.showMessageDialog(this, "Digite o CPF ", "Atenção",
						JOptionPane.CANCEL_OPTION);
				return;
			}

			if (txtRG.getText().replaceAll("\\.*-*", "").trim().length() == 0) {
				JOptionPane.showMessageDialog(this, "Digite o RG ", "Atenção",
						JOptionPane.CANCEL_OPTION);
				return;

			}
		}

Obs.: É preciso colocar o código entre [ code][ /code] (sem o espaço).

M

Desconsidera o que eu disse. Isso que dá confiar demais no eclipse hehe. Ele não me mostrou tudo que deveria. Vou dar mais uma olhada.

ivo_costa

O problema é que vc está declarando duas vezes a variáveis dos botões.

Mude:

para

faça o mesmo para o resto dos botões, alterar, exluir…

E mude:

para

R

O que ele não mostrou ? será que o ecipse ocultou alguma coisa? tipo assim um metodo ou algo parecido?

R

:slight_smile: vlw mesmo, deu certo. muito obrigado pela coperação, quando eu tiver experiência em java quero ser igual a vc!!!hehehehe!!! muitlo obrigado :stuck_out_tongue:

R

vlw mesmo, deu certo. muito obrigado pela coperação, quando eu tiver experiência em java quero ser igual a vc!!!hehehehe!!! muito obrigado

R

vlw mesmo, deu certo. muito obrigado pela coperação, quando eu tiver experiência em java quero ser igual a vc!!!hehehehe!!! muitlo obrigado

R

vlw!! deu certo!!! mto obrigado, quando eu tiver bastante experiencia em java quero ser igual a vc!!!hehehehehehehhe, mto obrigado!!

ivo_costa

blz, quando tiver experiência em java volta ai pro GUJ para ajudar os caras novos.
E coloca [resolvido] no título do tópico.

Criado 1 de setembro de 2008
Ultima resposta 1 de set. de 2008
Respostas 19
Participantes 6