Regra de validação com Swing

7 respostas
PaduaAlves

Boa tarde Pessoal. Comecei a trabalhar com SWING e estou com dúvida para fazer uma validação. Tenho uma tela com 3 JRadioButton, 3 JTextField, uma JTextArea e 2 JButtons. Gostaria de uma idéia de como fazer a seguinte regra de validação: A tela deve iniciar com os 3 JRadioButton desabilitados. Dependendo da escolha do JRadioButton um botão ou outro deve ser habilitado. Grato pela ajuda.

7 Respostas

ViniGodoy

http://download.oracle.com/javase/tutorial/uiswing/components/buttongroup.html
http://download.oracle.com/javase/tutorial/uiswing/components/button.html#radiobutton

For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup takes care of unselecting the previously selected button when the user selects another button in the group.

You should generally initialize a group of radio buttons so that one is selected. However, the API doesn’t enforce this rule ? a group of radio buttons can have no initial selection. Once the user has made a selection, exactly one button is selected from then on.

PaduaAlves

Obrigado pelos links, mas a minha dúvida principal é como habilitar ou desabilitar um botão de acordo com o Raddio Button escolhido. Não consigo ver como um componente vai descobrir o estado do outro para saber quando habilitar/desabilitar.

ViniGodoy

Como explicam os links, é só colocar os botões dentro de um ButtonGroup:

ButtonGroup bgGroup = new ButtonGroup(); bgGroup.add(radButton1); bgGroup.add(radButton2); bgGroup.add(radButton3);

ViniGodoy

Se você quiser fazer com que cada radio habilite ou desabilite um botão, basta sobrescrever o actionPerformed do radio button. Os links também explicam como fazer isso.

Jose111

Você cria um actionEvent no radioButton e depois dentro dele você faz :

Edit: não tinha visto os posts do Vini

PaduaAlves

Consegui resolver. Eu implemente a interface ActionListener na própria classe que representa a tela e fiz a validação dentro do método actionPerformed(). O correto é fazer assim mesmo ou eu deveria deixar outra classe responsável pela validação?

PaduaAlves

Tô com receio de estar fazendo tudo gambiarrado agora no começo e ter problemas depois ja q esse código certamente vai crescer. Não tenho experiência com swing. Como está a estrutura do meu código?

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class TelaPrincipal extends JFrame implements ActionListener {

	private JPanel panelCima = new JPanel();
	private JPanel panelBaixo = new JPanel();
	private JPanel panelCentro = new JPanel();
	private JTextField campoUrl = new JTextField();
	private JTextField campoNome = new JTextField();
	private ButtonGroup grupoRadio = new ButtonGroup();
	private JRadioButton radioProd = new JRadioButton("Banco de Produção");
	private JRadioButton radioHomo = new JRadioButton("Banco de Homologação");
	private JRadioButton radioDev = new JRadioButton("Banco de Desenvolvimento");
	private JLabel labelUrl = new JLabel("URL de conexão:");
	private JLabel labelNome = new JLabel("Usuário:");
	private JLabel labelSenha = new JLabel("Senha:");
	private JLabel labelLog = new JLabel("Log:");
	private JButton botaoGerar = new JButton("Gerar script INSERT!");
	private JButton botaoExecutar = new JButton("Executar script INSERT!");
	private JPasswordField campoSenha = new JPasswordField();
	private JTextArea areaLog = new JTextArea(9, 39);
	private JScrollPane scroll = new JScrollPane(areaLog);

	public TelaPrincipal() {
		super("Programa para carregar scripts!");
		this.initComponents();

	}

	public void initComponents() {
		this.grupoRadio.add(radioProd);
		this.grupoRadio.add(radioHomo);
		this.grupoRadio.add(radioDev);
		this.radioDev.addActionListener(this);
		this.radioHomo.addActionListener(this);
		this.radioProd.addActionListener(this);

		this.scroll
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		this.scroll
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		this.areaLog.setLineWrap(true);

		// Adição dos componentes nos seus painéis
		this.panelCima.add(radioProd);
		this.panelCima.add(radioHomo);
		this.panelCima.add(radioDev);
		this.panelCima.add(labelUrl);
		this.panelCima.add(campoUrl);
		this.panelCima.add(labelNome);
		this.panelCima.add(campoNome);
		this.panelCima.add(labelSenha);
		this.panelCima.add(campoSenha);
		this.panelCima.setLayout(new BoxLayout(panelCima, BoxLayout.Y_AXIS));
		this.panelCentro.add(labelLog);
		this.panelCentro.add(scroll);
		this.panelBaixo.add(botaoGerar);
		this.panelBaixo.add(botaoExecutar);

		// Adição e organização dos painéis no Frame.
		this.add(BorderLayout.NORTH, panelCima);
		this.add(BorderLayout.CENTER, panelCentro);
		this.add(BorderLayout.SOUTH, panelBaixo);
		this.setSize(455, 415);
		this.setVisible(true);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		if ((this.radioDev.isSelected() || this.radioHomo.isSelected() || this.radioProd
				.isSelected()) == false) {
			this.botaoExecutar.setEnabled(false);
			this.botaoGerar.setEnabled(false);
		}

	}

	public JTextField getCampoUrl() {
		return campoUrl;
	}

	public void setCampoUrl(JTextField campoUrl) {
		this.campoUrl = campoUrl;
	}

	public JTextField getCampoNome() {
		return campoNome;
	}

	public void setCampoNome(JTextField campoNome) {
		this.campoNome = campoNome;
	}

	public JRadioButton getRadioProd() {
		return radioProd;
	}

	public void setRadioProd(JRadioButton radioProd) {
		this.radioProd = radioProd;
	}

	public JRadioButton getRadioHomo() {
		return radioHomo;
	}

	public void setRadioHomo(JRadioButton radioHomo) {
		this.radioHomo = radioHomo;
	}

	public JRadioButton getRadioDev() {
		return radioDev;
	}

	public void setRadioDev(JRadioButton radioDev) {
		this.radioDev = radioDev;
	}

	public JPasswordField getCampoSenha() {
		return campoSenha;
	}

	public void setCampoSenha(JPasswordField campoSenha) {
		this.campoSenha = campoSenha;
	}

	public JTextArea getAreaLog() {
		return areaLog;
	}

	public void setAreaLog(JTextArea areaLog) {
		this.areaLog = areaLog;
	}

	public JButton getBotaoGerar() {
		return botaoGerar;
	}

	public void setBotaoGerar(JButton botaoGerar) {
		this.botaoGerar = botaoGerar;
	}

	public JButton getBotaoExecutar() {
		return botaoExecutar;
	}

	public void setBotaoExecutar(JButton botaoExecutar) {
		this.botaoExecutar = botaoExecutar;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(this.radioDev.isSelected()){
			this.botaoExecutar.setEnabled(true);
			this.botaoGerar.setEnabled(false);
		}
		if(this.radioHomo.isSelected()) {
			this.botaoExecutar.setEnabled(true);
			this.botaoGerar.setEnabled(true);
		}
		if(this.radioProd.isSelected()){
			this.botaoExecutar.setEnabled(false);
			this.botaoGerar.setEnabled(true);
		}
		
	}

}
Criado 23 de agosto de 2010
Ultima resposta 23 de ago. de 2010
Respostas 7
Participantes 3