Diferentemente do Eclipse (IBM), o NetBeans possui uma IDE gráfica que em seus primórdios foi baseada na IDE do Delphi (Borland), para quem conhece Delphi já sabe que a sua interface de GUI RAD foi um dos seus pontos fortes. O NetBeans adotado pela Sun e agora pela Oracle, possui uma magnifica e produtiva IDE para Java.
Há até uma certa disputa entre as duas IDEs e a preferencia dos desenvolvedores, se por um lado o Eclipse lhe proporciona um código mais limpo e mais leve, o NetBeans sem duvida lhe dará mais produtividade. Você precisa entender que o NetBeans assim o Eclipse não são apenas uma IDE e sim uma plataforma, apesar de serem famosos por proporcionarem uma IDE Java, cada um possui um proposito diferente.
O Eclipse é uma plataforma baseada em plug-ins que permite expansão infinita de suas funcionalidades, permitindo que à partir da plataforma Eclipse outros softwares sejam criados, como por exemplo o IBM Data Studio. O NetBeans é uma plataforma dedicada a desenvolvimento de softwares desktop proporcionando técnicas de desenvolvimento modulares prometendo reduzir o tempo de desenvolvimento de aplicações gráficas em até um ano a menos que outras plataformas.
Disputas a parte, você que esta começando pode escolher por conta própria a sua interface preferida e decidimos lhe ajudar a escolher a melhor forma para criar seus programas em Java.
Para baixar o NetBeans você pode ir diretamente no site da Oracle ou : https://netbeans.org/downloads/index.html
Desenvolvemos o mesmo programa baseado na diferença de escrita de código para as duas IDEs Java. Para ver o mesmo programa desenvolvido para a IDE Eclipse use o link abaixo:
IDE Eclipse: https://desenvolvimentoaberto.wordpress.com/2014/03/12/visual-controles-radiobutton-events-getstatechange-java/
Design First, Code Later em Java Free Design
No Construtor de GUIs da IDE, você pode construir seus formulários simplesmente colocando os componentes onde quiser, como se você estivesse usando o posicionamento absoluto. O GUI Builder descobre quais são atributos de layout necessários e, em seguida, gera o código para você automaticamente. Você não precisa se preocupar com inserções, âncoras, preenchimentos, e assim por diante .
Para referencia de como deve ficar o seu projeto e o design de seu programa utilize a imagem abaixo:
NetBeans
- Crie um novo Projeto Java Application chamado JDevAberto e clique em Next.
- Deixe marcado o checkbox Criar Classe Principal, mas apague o conteúdo do campo de edição, o deixando em branco, em seguida clique em Finalizar.
- Já na IDE com o projeto aberto, clique com o botão direito no projeto escolha novo JFrame e o nomeie para JDevAberto_Main
- Na janela de propriedades do JFrame clique em Title coloque: “Desenvolvimento Aberto”.
- Coloque um JPanel e modifique sua largura e altura até atingir metade do JFrame.
- Com o JPanel selecionado, clique em Border na janela de propriedades.
- Em Borda com Titulo, coloque o titulo: “Escolha uma opção ou pressione Alt A, B, C ou D” e clique em OK.
- Arraste quatro Botões de Radio e em sua respectiva propriedade Text, nomei cada um dos elementos como: Somar, Subtrair, Multiplicar, Dividir.
- Na propriedade Mnemonic de cada botão coloque respectivamente as letras : A, B, C e D.
- Coloque um Grupo de Botões no JPanel, ele ficara invisivel no formulario.
- Clique em cada RadioButton e na propriedade buttonGroup escolha o grupo de botões.
- Coloque dois JLabel na tela e dois Campos de textos.
- Coloque o valor 0 na propriedade Text dos campos e nomeie a propriedade Texts dos Labels para : Numero
- Coloque um botão na tela, mude sua propriedade Text para “OK” e o alinhe ao lado dos labels e campos de texto.
- Coloque uma Area de Texto e modifique sua largura e altura para que complete a parte inferior da tela.
- No modo Design, na barra de ferramentas ao lado da paleta Histórico, clique no botão Visualizar Design para ver as funcionalidades da sua GUI.
- Clique no botão Run na barra de ferramentas para rodar sua aplicação.
Finalização
Neste ponto sua aplicação já possui o design mas ainda nenhuma funcionalidade, precisamos programar os eventos de cada botão, para isso de um duplo clique em cada RadioButton e um duplo clique no botão.
O NetBeans criou para você os eventos automaticamente, agora só precisamos olhar o código abaixo e completar os eventos em nosso programa, após a finalização seu programa deve funcionar como na imagem abaixo:
Exemplo:
Este é o código criado automaticamente acrescentado do código dentro dos eventos para a funcionalidade do programa, para visualizar os eventos de um modo mais fácil, procure o bloco de código que está marcado com o comentário: “//************** DA”.
Java
// * // * 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. // */ // ** // * // * @author Desenvolvimento Aberto // */ public class JDevAberto_Main extends javax.swing.JFrame { //** //* Creates new form JDevAberto_Main //*/ public JDevAberto_Main() { 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() { buttonGroup1 = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jRadioButton4 = new javax.swing.JRadioButton(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Desenvolvimento Aberto"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Escolha uma opção ou pressione Alt A, B, C ou D")); buttonGroup1.add(jRadioButton1); jRadioButton1.setMnemonic('A'); jRadioButton1.setText("Somar"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton2); jRadioButton2.setMnemonic('B'); jRadioButton2.setText("Subtrair"); jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton3); jRadioButton3.setMnemonic('C'); jRadioButton3.setText("Multiplicar"); jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton4); jRadioButton4.setMnemonic('D'); jRadioButton4.setText("Dividir"); jRadioButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jRadioButton3) .addComponent(jRadioButton4, javax.swing.GroupLayout.Alignment.LEADING))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton4)) ); jLabel1.setText("Numero:"); jTextField1.setText("0"); jTextField2.setText("0"); jLabel2.setText("Numero:"); jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)) .addComponent(jScrollPane1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold> //************** DA // Preencha os Eventos a seguir: private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jTextArea1.append("Dividir:\n"); } private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jTextArea1.append("Somar:\n"); } private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jTextArea1.append("Subtrair:\n"); } private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jTextArea1.append("Multiplicar:\n"); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: double total; if (jRadioButton1.getSelectedObjects() != null) { total = Double.parseDouble(jTextField1.getText()) + Double.parseDouble(jTextField2.getText()); jTextArea1.append(jTextField1.getText() + " + " + jTextField2.getText() + " = " + String.valueOf(total)+ "\n"); } if (jRadioButton2.getSelectedObjects() != null) { total = Double.parseDouble(jTextField1.getText()) - Double.parseDouble(jTextField2.getText()); jTextArea1.append(jTextField1.getText() + " - " + jTextField2.getText() + " = " + String.valueOf(total)+ "\n"); } if (jRadioButton3.getSelectedObjects() != null) { total = Double.parseDouble(jTextField1.getText()) * Double.parseDouble(jTextField2.getText()); jTextArea1.append(jTextField1.getText() + " * " + jTextField2.getText() + " = " + String.valueOf(total) + "\n"); } if (jRadioButton4.getSelectedObjects() != null) { total = Double.parseDouble(jTextField1.getText()) / Double.parseDouble(jTextField2.getText()); jTextArea1.append(jTextField1.getText() + " / " + jTextField2.getText() + " = " + String.valueOf(total) + "\n"); } } //************** DA // Fim dos Eventos //** //* @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(JDevAberto_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JDevAberto_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JDevAberto_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JDevAberto_Main.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 JDevAberto_Main().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JRadioButton jRadioButton4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration }