Ajuda com JRadioButton - RESOLVIDO

18 respostas
R
Tenho um código simples que em um form funciona e em outro o mesmo código não funciona, acredito que deva ser algo no código do form mais implementado, mas não consegui descobrir o que está impedindo de funcionar.

O código é simples, tenho dois radiobuttom, quando marco um, automaticamente o outro é desmarcado.

Alguém pode me ajudar?

Segue o código do form

public class CalcularNota extends javax.swing.JFrame

{

private int posicao = 05;
private List<JTextField> listInput;

private List<ParametroNotaVO> listParametroNota;

/** Creates new form CalcularNota */
public CalcularNota() 
{
    this.setIcon();
    initComponents();
    
    this.getListFundamentos();
}

public void setIcon()
{
    URL url = this.getClass().getResource("/imagens/icone/icon_frame_32x32.png");
    Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url);
    this.setIconImage(imagemTitulo);
}

private void getListFundamentos()
{
    
    try
    {
        this.setListParametroNota(this.getParametroNotaDAO().loadAll());
        this.setListInput(new ArrayList<>());
        
        for (int i = 0; i < this.getListParametroNota().size(); i++)
        {
            this.addLabel(this.getListParametroNota().get(i).getNome(), this.getListParametroNota().get(i).getFormula());
        }
        
        
    }
    catch (SQLException e)
    {
        System.out.println(e.getMessage());
    }
}

private void addLabel(String nome, String toolTip)
{
    JLabel label;
    posicao += 40;
    
    label = new JLabel(nome);
    label.setVisible(true);
    label.setToolTipText(toolTip);
    label.setSize(300, 22);
    label.setFont(new Font("Times New Roman", Font.BOLD, 18));
    label.setForeground(Color.BLACK);
    label.setLocation(20, posicao);
    
    this.getContentPane().add(label);
    initComponents();
    
    this.addTextField(nome, posicao);
}

private void addTextField(String nome, int posicao)
{
    JTextField input;
    
    input = new JTextField();
    input.setVisible(true);
    //input.setText("Teste");
    input.setSize(60, 23);
    input.setFont(new Font("Times New Roman", Font.PLAIN, 18));
    input.setName("input_" + nome);
    input.setLocation(350, posicao);
    
    this.getContentPane().add(input);
    initComponents();
    
    this.getListInput().add(input);
}

private boolean validaDados(List<JTextField> list)
{
    for (int i = 0; i < list.size(); i++)
    {
        if (list.get(i).getText().isEmpty())
        {
            return false;
        }
    }
    
    return true;
}

private void formulaNota()
{
    Double nota;
    Double aux;
    
    nota = new Double("0.0");
    
    for (int i = 0; i < this.getListParametroNota().size(); i++)
    {
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("CAGR LUCRO 5 ANOS"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux > 0)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
        } 
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("DIVIDENDO - DY"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux >= 5)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
            else
            {
                if (aux >= 3.65)
                {
                    nota = nota + 0.75;
                }
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("DIVIDENDO CONSTANTE"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux == 1)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("EDIVIDAMENTO"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux <= 2)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
            else
            {
                if (aux <= 3)
                {
                    nota = nota + 0.75;
                }
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("LUCRO ÚLTIMOS 5 ANOS"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux == 5)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
            else
            {
                if (aux >= 3)
                {
                    nota = nota + 0.75;
                }
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("MARGEM LÍQUIDA"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux >= 15)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
            else
            {
                if (aux >= 10)
                {
                    nota = nota + 0.75;
                }
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("ROE"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux >= 15)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
            else
            {
                if (aux >= 10)
                {
                    nota = nota + 0.75;
                }
            }
        }
        if(this.getListParametroNota().get(i).getNome().equalsIgnoreCase("VALOR DE MERCADO"))
        {
            aux = new Double(buscaTextField(this.getListParametroNota().get(i).getNome()).getText().replaceAll( "," , "." ));
            
            if (aux >= 6)
            {
                nota = nota + this.getListParametroNota().get(i).getPeso();
            }
        }
    }
    
    this.getInput_nota().setText(nota.toString());
}

private JTextField buscaTextField(String busca)
{
    for (int i = 0; i < this.getListInput().size(); i++)
    {
        if(this.getListInput().get(i).getName().equalsIgnoreCase("input_" + busca))
        {
            return this.getListInput().get(i);
        }
    }
    
    return new JTextField();
}

private void salvar()
{

}

private void calcularNota(java.awt.event.ActionEvent evt)                              
{                                  
    // TODO add your handling code here:
    if (this.validaDados(this.getListInput()))
    {
        this.formulaNota();
    }
    else
    {
        JOptionPane.showMessageDialog(null, "É necessário preencher todos os campos", "Calcula Nota v1", JOptionPane.INFORMATION_MESSAGE);
    }
}                             

private void seleciona2T(java.awt.event.MouseEvent evt)                             
{                                 
    // TODO add your handling code here:
    
    this.getRadio1T().setSelected(false);
}                            

private void seleciona1T(java.awt.event.MouseEvent evt)                             
{                                 
    // TODO add your handling code here:
    
    this.getRadio2T().setSelected(false);
}

Esse código do método seleciona1T e seleciona2T não funciona aqui, o mesmo código funciona em qualquer outro form que crio para testar

18 Respostas

rodriguesabner

Vc pode simplesmente adicionar um GroupButton no seu form que resolve o problema… Mas o que não funciona? Da erro? Só não desmarca o jradio?

E esse tipo de evento tem que ser o “ItemStateChanged”

R

Não dá erro, mas o código não funciona, não desmarca.
Tentei usar o ItemStateChanged mas também não funcionou

rodriguesabner

Ok, vc gerou esse evento via GUI do Netbeans ou criou manualmente? Pq não tô vendo esses métodos sendo chamados em canto algum

R

Foi criado via GUI do Netbeans
Mas o engraçado é que o mesmo código, exatamente idêntico funciona em outro form.
Não sei se é algo no código que fiz para criar label e textfield dinâmicos que está de alguma forma impedindo que os eventos chamem os métodos do radiobuttom

R

O evento funciona, entra no método sem erro, mas o que aparentemente não funciona são os get e set, ele não atribui false no “this.getRadio2T().setSelected(false);”

rodriguesabner

Mas pq vc tá fazendo um getter e setter pra isso? Acessa o componente diretamente

staroski

É só você adicionar os rádios dentro do mesmo ButtonGroup.

R

Já tentei fazer assim mas não funcionou, não consigo alterar a propriedade setSelected

R

Valeu, vou tentar fazer isso

rodriguesabner

Cara, se vc fizer isso só agora eu vou ficar muito puto, na boa.


Eu falei pra vc fazer isso no começo

staroski

Kkkkk

R

Cara só estava tentando ser simpático com o colega pela atenção dele, como já tinha dito antes não funcionou, o ButtomGroup desmarca um radio quando outro é marcado, mas quando tento fazer isso: radio1T.isSelected(), mesmo ele estando selecionado, sempre retorna falso

rodriguesabner

Não é esse oobjetivo?

staroski

Posta o seu código

R

quando tento fazer isso: radio1T.isSelected(), mesmo ele estando selecionado, sempre retorna falso

staroski

Tem certeza de que está chamando o método na instância correta?
Posta seu código.

R

Eu pego o mesmo código e coloco em um Jframe novo, aí funciona tudo certo, dentro desse Jframe não funciona, não consigo descobrir o pq, o isSelected do radiobuttom retorna sempre false

R
Resolvido

O problema estava aqui :

this.getContentPane().add(label);

initComponents();

Quando eu estava adicionando os labels eu estava também usando o initComponents, retirei e agora está funcionando da maneira que eu precisava

Obrigado pela ajuda de todos
Criado 7 de junho de 2020
Ultima resposta 10 de jun. de 2020
Respostas 18
Participantes 3