Criação de Radio Gráfica

7 respostas Resolvido
java
A

Bom dia, Pessoal!

Estou fazendo um programa que simula um rádio onde da para se escolher estação e tudo mais.
Até o momento consegui fazer o seguinte código.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import java.awt.event.MouseEvent;

/**
 *
 * @author André
 */
public class TelaRadio extends javax.swing.JFrame {

    /**
     * Creates new form TelaRadio
     */
    public TelaRadio() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lblEstacao = new javax.swing.JLabel();
        lblVolume = new javax.swing.JLabel();
        btnMais = new javax.swing.JButton();
        btnMenos = new javax.swing.JButton();
        btnMaisVolume = new javax.swing.JButton();
        btnMenosVolume = new javax.swing.JButton();
        btnLigaDesliga = new javax.swing.JToggleButton();
        JPanelEstacao = new javax.swing.JPanel();
        jtxtEstacao = new javax.swing.JTextField();
        jtxtVolume = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblEstacao.setText("Estação");

        lblVolume.setText("Volume");

        btnMais.setText("+");
        btnMais.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMaisActionPerformed(evt);
            }
        });

        btnMenos.setText("-");

        btnMaisVolume.setText("+");

        btnMenosVolume.setText("-");

        btnLigaDesliga.setText("LIGAR");
        btnLigaDesliga.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLigaDesligaActionPerformed(evt);
            }
        });

        JPanelEstacao.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jtxtEstacao.setEditable(false);
        jtxtEstacao.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        jtxtEstacao.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtxtEstacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtEstacaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout JPanelEstacaoLayout = new javax.swing.GroupLayout(JPanelEstacao);
        JPanelEstacao.setLayout(JPanelEstacaoLayout);
        JPanelEstacaoLayout.setHorizontalGroup(
            JPanelEstacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtxtEstacao, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
        );
        JPanelEstacaoLayout.setVerticalGroup(
            JPanelEstacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtxtEstacao, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
        );

        jtxtVolume.setEditable(false);
        jtxtVolume.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        jtxtVolume.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(lblEstacao, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnLigaDesliga, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblVolume, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(JPanelEstacao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jtxtVolume))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btnMenos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnMais, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnMaisVolume, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnMenosVolume, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(lblEstacao, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(JPanelEstacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblVolume, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnMais)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnMenos)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnMaisVolume)
                        .addGap(18, 18, 18)
                        .addComponent(btnMenosVolume))
                    .addComponent(jtxtVolume))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                .addComponent(btnLigaDesliga, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );

        pack();
    }// </editor-fold>                        

    private void btnMaisActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnLigaDesligaActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:  
        btnLigaDesliga.setText("DESLIGA");
    }                                              

    
    private void jtxtEstacaoActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaRadio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaRadio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaRadio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaRadio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaRadio().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel JPanelEstacao;
    private javax.swing.JToggleButton btnLigaDesliga;
    private javax.swing.JButton btnMais;
    private javax.swing.JButton btnMaisVolume;
    private javax.swing.JButton btnMenos;
    private javax.swing.JButton btnMenosVolume;
    private javax.swing.JTextField jtxtEstacao;
    private javax.swing.JTextField jtxtVolume;
    private javax.swing.JLabel lblEstacao;
    private javax.swing.JLabel lblVolume;
    // End of variables declaration                   
}

Criei na parte de arrastar e clicar no NetBeans

O radio tem a seguinte interface

image

Ao clicar em Ligar o Botão muda de Texto para Desligar conforme essa parte do código

private void btnLigaDesligaActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:  
        btnLigaDesliga.setText("DESLIGA");
    }

Porém eu não sei como fazer para um segundo Clique trocar para a Frase Ligar novamente.

Outra dúvida seria com os botões de mais e menos, no código eu já tenho um incrimento de estação que esta dessa forma

public void incrementarEstacao() {
    if (estacao < 110) {
        estacao++;
    } else {
        estacao = 88;
    }
}

Como eu poderia aplicar isso ao clicar em + e -, e como eu poderia configurar para ao clicar em Desligar que os text Fields ficassem em branco novamente.

Muito obrigado!

7 Respostas

L

Para esse caso, tu pode manter um boolean na sua classe para indicar se está ligado ou não.

private boolean ligado = false;

E no botão, tu usa a variável para definir o label:

btnLigaDesliga.setText(ligado ? "DESLIGAR" : "LIGAR");
ligado = !ligado;
A

Deu muito certo, irei aplicar essa solução para os outros locais e ver se ocorre tudo certinho também.
Muito obrigado! Eu to bem perdido com interface gráfica

A

Outra dúvida. Além do SetText tem alguma Função para ser tipo SetInt ? eu não cheguei a encontrar, ou eu teria que converter uma string pra um inteiro?

L

Tem que sempre fazer a conversão para o tipo que vc precisar.

A
Solucao aceita

Certo! Eu consegui fazer a conversão dessa forma

if (ligado == true) {
    jtxtEstacao.setText(String.valueOf(88));
} else if (ligado == false) {
    jtxtEstacao.setText("");
}

  if (ligado == true) {
    jtxtVolume.setText(String.valueOf(0));
} else if (ligado == false) {
    jtxtVolume.setText("");

Agora eu preciso que o botão + incremente o valor e eu até tenho uma função para isso em um outro package que seria

public void incrementarEstacao() {
    if (estacao < 110) {
        estacao++;
    } else {
        estacao = 88;
    }
}

Todavia não consegui usar ali e to com dificuldade para entender como aplicar a incrementação de aumentar o inteiro clicando no botão +

No caso eu tenho somente isso até o momento

Desculpa por tantas perguntas, mas realmente to com dificuldade em entender essas partes

S

Eu utilizaria um algoritmo de fila circular:

// se o incremento for +1 aumenta o valor
// se o incremento for -1 diminui o valor
private void mudarValor(int incremento) {
        int limite = MAIOR_VALOR_POSSIVEL - MENOR_VALOR_POSSIVEL + 1;
        valorAtual -= MENOR_VALOR_POSSIVEL;
        valorAtual = (valorAtual + limite + incremento) % limite;
        valorAtual += MENOR_VALOR_POSSIVEL;
}

Veja como implementei na sua tela nos métodos mudarEstacao e mudarVolume:

package tela;

import java.awt.EventQueue;
import java.awt.Font;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.LayoutStyle;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

/**
 * @author André
 */
public class TelaRadio extends JFrame {

    private static final long serialVersionUID = 1;

    private static int MENOR_ESTACAO = 88;
    private static int MAIOR_ESTACAO = 110;

    private static int MENOR_VOLUME = 0;
    private static int MAIOR_VOLUME = 100;

    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            Logger.getLogger(TelaRadio.class.getName()).log(Level.SEVERE, null, ex);
        }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaRadio().setVisible(true);
            }
        });
    }

    private JPanel JPanelEstacao;
    private JToggleButton btnLigaDesliga;
    private JButton btnMais;
    private JButton btnMaisVolume;
    private JButton btnMenos;
    private JButton btnMenosVolume;

    private JTextField jtxtEstacao;
    private JTextField jtxtVolume;

    private JLabel lblEstacao;
    private JLabel lblVolume;

    private int estacao = MENOR_ESTACAO;
    private int volume = MENOR_VOLUME;
    private boolean ligado = false;

    /**
     * Creates new form TelaRadio
     */
    public TelaRadio() {
        super("Meu Rádio");
        initComponents();
        atualizarTela();
    }

    private void initComponents() {
        lblEstacao = new JLabel();
        lblVolume = new JLabel();
        btnMais = new JButton();
        btnMenos = new JButton();
        btnMaisVolume = new JButton();
        btnMenosVolume = new JButton();
        btnLigaDesliga = new JToggleButton();
        JPanelEstacao = new JPanel();
        jtxtEstacao = new JTextField();
        jtxtVolume = new JTextField();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        lblEstacao.setText("Estação");

        lblVolume.setText("Volume");

        btnMais.setText("+");
        btnMais.addActionListener(event -> mudarEstacao(+1));

        btnMenos.setText("-");
        btnMenos.addActionListener(event -> mudarEstacao(-1));

        btnMaisVolume.setText("+");
        btnMaisVolume.addActionListener(event -> mudarVolume(+1));

        btnMenosVolume.setText("-");
        btnMenosVolume.addActionListener(event -> mudarVolume(-1));

        btnLigaDesliga.setText("LIGAR");
        btnLigaDesliga.addActionListener(event -> ligarDesligar());

        JPanelEstacao.setBorder(BorderFactory.createEtchedBorder());

        jtxtEstacao.setEditable(false);
        jtxtEstacao.setFont(new Font("Dialog", 1, 18)); // NOI18N
        jtxtEstacao.setHorizontalAlignment(JTextField.CENTER);

        GroupLayout JPanelEstacaoLayout = new GroupLayout(JPanelEstacao);
        JPanelEstacao.setLayout(JPanelEstacaoLayout);
        JPanelEstacaoLayout.setHorizontalGroup(JPanelEstacaoLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jtxtEstacao, GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE));
        JPanelEstacaoLayout.setVerticalGroup(JPanelEstacaoLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jtxtEstacao, GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE));

        jtxtVolume.setEditable(false);
        jtxtVolume.setFont(new Font("Dialog", 1, 18)); // NOI18N
        jtxtVolume.setHorizontalAlignment(JTextField.CENTER);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addGap(27, 27, 27).addComponent(lblEstacao, GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE).addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(GroupLayout.Alignment.TRAILING,
                                layout.createSequentialGroup().addContainerGap(24, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(btnLigaDesliga, GroupLayout.PREFERRED_SIZE, 172, GroupLayout.PREFERRED_SIZE).addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addComponent(lblVolume, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(JPanelEstacao, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jtxtVolume))
                                                .addGap(18, 18, 18)
                                                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(btnMenos, GroupLayout.Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(btnMais, GroupLayout.Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE))
                                                        .addComponent(btnMaisVolume, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE).addComponent(btnMenosVolume, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE))))
                                        .addGap(33, 33, 33)));
        layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(39, 39, 39).addComponent(lblEstacao, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addComponent(JPanelEstacao, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addComponent(lblVolume,
                                GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup().addComponent(btnMais).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(btnMenos)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addGroup(layout.createSequentialGroup().addComponent(btnMaisVolume).addGap(18, 18, 18).addComponent(btnMenosVolume)).addComponent(jtxtVolume))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE).addComponent(btnLigaDesliga, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE).addGap(25, 25, 25)));

        pack();
    }

    private void ligarDesligar() {
        ligado = !ligado;
        if (ligado) {
            estacao = MENOR_ESTACAO;
            volume = MENOR_VOLUME;
        }
        atualizarTela();
    }

    private void mudarEstacao(int proximaEstacao) {
        if (ligado) {
            int quantidade = MAIOR_ESTACAO - MENOR_ESTACAO + 1;
            estacao -= MENOR_ESTACAO;
            estacao = (estacao + quantidade + proximaEstacao) % quantidade;
            estacao += MENOR_ESTACAO;
            atualizarTela();
        }
    }

    private void mudarVolume(int proximoNivel) {
        if (ligado) {
            int quantidade = MAIOR_VOLUME - MENOR_VOLUME + 1;
            volume -= MENOR_VOLUME;
            volume = (volume + quantidade + proximoNivel) % quantidade;
            volume += MENOR_VOLUME;
            atualizarTela();
        }
    }

    private void atualizarTela() {
        if (ligado) {
            btnLigaDesliga.setText("DESLIGAR");
            jtxtEstacao.setText(String.valueOf(estacao));
            jtxtVolume.setText(String.valueOf(volume));
        } else {
            btnLigaDesliga.setText("LIGAR");
            jtxtEstacao.setText("");
            jtxtVolume.setText("");
        }
        btnMais.setEnabled(ligado);
        btnMenos.setEnabled(ligado);
        btnMaisVolume.setEnabled(ligado);
        btnMenosVolume.setEnabled(ligado);
    }
}
A

Consegui finalizar meu projeto com a ajuda de todos.
Muito obrigado por tudo!

Criado 26 de agosto de 2020
Ultima resposta 26 de ago. de 2020
Respostas 7
Participantes 3