JDateChooser and JComboBox picking up blank values

1

I'm having some problems trying to capture the value of some elements of my code.

1st - Problem with JDateChoose component

The code runs smoothly however the captured value goes blank, follows code

 String dtreceb = ((JTextField) this.txtdtreceb.getDateEditor().getUiComponent()).getText();

2nd - Problem with the JComboBox component

When trying to capture the value, the code writes "NULL" in the database

 String trincado = (String) txttrincado.getSelectedItem();

Full application code;

package matheus.arruda.lab.wn.tratermik;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.JTextComponent;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;

import com.jgoodies.forms.layout.FormLayout;

import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import java.awt.Choice;
import java.awt.List;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JSeparator;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;

import com.ibm.icu.text.DateFormat;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import javax.swing.JSpinner;
import javax.swing.JEditorPane;
import javax.swing.JTextPane;
import com.toedter.components.JSpinField;
import com.toedter.calendar.JCalendar;
import com.toedter.calendar.JDateChooser;
import javax.swing.JFileChooser;

public class novaos extends JFrame {

    private JPanel contentPane;
    private JTextField txtos;
    JComboBox txtcliente = new JComboBox<Object>();
    JComboBox txttrincado = new JComboBox();
    JComboBox txtamassado = new JComboBox();
    JComboBox txtpesodiv = new JComboBox();
    private JTextField txtresp;
    private JTextField txtqtdpesodiv;
    JLabel lblQtdPesoFora = new JLabel();
    JDateChooser txtdtreceb = new  JDateChooser();
    private JTextField textField;
    private JTextField txtcopiacliente;
    private JTextField txtoutrasdiv;
    private JTextField txtoutrasdiv1;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    novaos frame = new novaos();
                    frame.setVisible(true);


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });




    }


private void fechar() {
    this.dispose();
}

    /**
     * Create the frame.
     */
    public novaos() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(novaos.class.getResource("/com/jgoodies/looks/plastic/icons/File.gif")));

        setTitle("Tratermik Metais  - Nova O.S");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(136, 55, 694, 661);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);




        JLabel lblos = new JLabel("#O.S:");
        lblos.setBounds(10, 48, 46, 20);
        lblos.setFont(new Font("Tahoma", Font.BOLD, 16));
        contentPane.add(lblos);

        txtos = new JTextField();
        txtos.setEditable(false);
        txtos.setBounds(59, 48, 46, 20);
        txtos.setFont(new Font("Tahoma", Font.BOLD, 16));
        contentPane.add(txtos);
        txtos.setColumns(2);
        buscar_dados();

        JLabel lblCliente = new JLabel("Cliente:");
        lblCliente.setFont(new Font("Tahoma", Font.BOLD, 16));
        lblCliente.setBounds(157, 48, 66, 20);
        contentPane.add(lblCliente);

        JLabel lblRespRelatrio = new JLabel("Respons\u00E1vel:");
        lblRespRelatrio.setFont(new Font("Tahoma", Font.BOLD, 16));
        lblRespRelatrio.setBounds(10, 79, 117, 20);
        contentPane.add(lblRespRelatrio);

        txtresp = new JTextField();
        txtresp.setBounds(128, 81, 211, 20);
        contentPane.add(txtresp);
        txtresp.setColumns(10);

        JSeparator separator = new JSeparator();
        separator.setBounds(0, 128, 243, 8);
        contentPane.add(separator);

        JLabel lblCaracteristicasDoMatrial = new JLabel("Caracteristicas do Mat\u00E9rial");
        lblCaracteristicasDoMatrial.setBounds(253, 122, 165, 14);
        contentPane.add(lblCaracteristicasDoMatrial);

        JSeparator separator_1 = new JSeparator();
        separator_1.setBounds(421, 128, 267, 8);
        contentPane.add(separator_1);

        JLabel lblMaterialTrincado = new JLabel("Material Trincado?");
        lblMaterialTrincado.setBounds(21, 140, 106, 16);
        contentPane.add(lblMaterialTrincado);

        JComboBox txttrincado = new JComboBox();
        txttrincado.setBounds(10, 163, 129, 25);
        contentPane.add(txttrincado);
        txttrincado.addItem("");
        txttrincado.addItem("Sim");
        txttrincado.addItem("Não");

        JComboBox txtamassado = new JComboBox();
        txtamassado.setBounds(169, 163, 129, 25);
        contentPane.add(txtamassado);
        txtamassado.addItem("");
        txtamassado.addItem("Sim");
        txtamassado.addItem("Não");
        JLabel lblMaterialAmassado = new JLabel("Material Amassado?");
        lblMaterialAmassado.setBounds(169, 140, 118, 16);
        contentPane.add(lblMaterialAmassado);




        JComboBox txtpesodiv = new JComboBox();
        txtpesodiv.setBounds(331, 163, 129, 25);
        contentPane.add(txtpesodiv);
        txtpesodiv.addItem("");
        txtpesodiv.addItem("Sim");
        txtpesodiv.addItem("Não");
         txtpesodiv.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    //
                    // Get the source of the component, which is our combo
                    // box.
                    //
                    JComboBox comboBox = (JComboBox) event.getSource();

                    Object selected = comboBox.getSelectedItem();
                    if(selected.toString().equals("Sim"))
                        txtqtdpesodiv.setEditable(true);


                    else if(selected.toString().equals("Não"))
                        txtqtdpesodiv.setEditable(false);

                }
            });

        // Icone




        JLabel lblPesoDivergente = new JLabel("Peso Divergente?");
        lblPesoDivergente.setBounds(342, 140, 106, 16);
        contentPane.add(lblPesoDivergente);

        JLabel lblestr = new JLabel("Qtd Peso Divergente?");
        lblestr.setBounds(524, 140, 129, 16);
        contentPane.add(lblestr);


        txtqtdpesodiv = new JTextField();
        txtqtdpesodiv.setEditable(false);
        txtqtdpesodiv.setColumns(10);
        txtqtdpesodiv.setBounds(524, 163, 138, 25);
        contentPane.add(txtqtdpesodiv);

        JLabel lblOutrasObservaoes = new JLabel("Outras Observa\u00E7\u00F5es do Material");
        lblOutrasObservaoes.setBounds(10, 195, 213, 20);
        contentPane.add(lblOutrasObservaoes);

        JDateChooser txtdtreceb = new JDateChooser();
        txtdtreceb.setBounds(21, 377, 142, 20);
        contentPane.add(txtdtreceb);
        String data = new SimpleDateFormat("dd/MM/yyyy",
                Locale.getDefault()).format(new Date());


        JSeparator separator_2 = new JSeparator();
        separator_2.setBounds(0, 351, 288, 8);
        contentPane.add(separator_2);

        JLabel lblData = new JLabel("Data");
        lblData.setBounds(306, 340, 88, 14);
        contentPane.add(lblData);

        JSeparator separator_3 = new JSeparator();
        separator_3.setBounds(350, 351, 338, 8);
        contentPane.add(separator_3);

        JLabel lblDataRecebimentoDa = new JLabel("Data de Recebimento da Pe\u00E7a");
        lblDataRecebimentoDa.setBounds(10, 358, 184, 14);
        contentPane.add(lblDataRecebimentoDa);

        JDateChooser dateChooser_1 = new JDateChooser();
        dateChooser_1.setBounds(432, 377, 142, 20);
        contentPane.add(dateChooser_1);



        JLabel lblDataPrevistaPara = new JLabel("Data Prevista para Entrega");
        lblDataPrevistaPara.setBounds(421, 358, 184, 14);
        contentPane.add(lblDataPrevistaPara);

        JSeparator separator_4 = new JSeparator();
        separator_4.setBounds(0, 420, 288, 8);
        contentPane.add(separator_4);

        JLabel lblOutros = new JLabel("Outros");
        lblOutros.setBounds(302, 407, 76, 14);
        contentPane.add(lblOutros);

        JSeparator separator_5 = new JSeparator();
        separator_5.setBounds(350, 420, 338, 8);
        contentPane.add(separator_5);

        JTextPane textPane = new JTextPane();
        textPane.setBounds(10, 453, 652, 106);
        contentPane.add(textPane);

        JLabel label = new JLabel("Outras observa\u00E7\u00F5es");
        label.setBounds(10, 420, 153, 20);
        contentPane.add(label);

        JSeparator separator_6 = new JSeparator();
        separator_6.setBounds(0, 582, 34, 3);
        contentPane.add(separator_6);

        JLabel lblPesoBalana = new JLabel("Peso Balan\u00E7a");
        lblPesoBalana.setBounds(51, 571, 88, 14);
        contentPane.add(lblPesoBalana);

        JSeparator separator_7 = new JSeparator();
        separator_7.setBounds(140, 582, 34, 3);
        contentPane.add(separator_7);

        textField = new JTextField();
        textField.setBounds(10, 597, 153, 20);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton btnGravar = new JButton("Gravar");
        btnGravar.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent arg0) {
                salvar();
            }
        });
        btnGravar.setBounds(572, 594, 90, 25);
        contentPane.add(btnGravar);

        txtoutrasdiv1 = new JTextField();
        txtoutrasdiv1.setBounds(13, 216, 649, 123);
        contentPane.add(txtoutrasdiv1);
        txtoutrasdiv1.setColumns(10);







    }


     public void buscar_dados() {
         try {
     Class.forName("org.sqlite.JDBC");
     Connection con = DriverManager.getConnection("jdbc:sqlite:C:\Users\Matheus\Documents\Java Apps\Tratermik\banco de dados\tratermik.db");
     Statement stat = con.createStatement();
     ResultSet rs;
     rs = stat.executeQuery("select count (*) from tratermik");
     ResultSetMetaData md = rs.getMetaData();
     int columnCount = md.getColumnCount();
     Vector columns = new Vector(columnCount);

    //store column names
     for(int i=1; i<=columnCount; i++)
       columns.add(md.getColumnName(i));

   Vector data = new Vector();
   Vector row;

     while (rs.next()) {

       row = new Vector(columnCount);
          for(int i=1; i<=columnCount; i++)
          {
              row.add(rs.getString(i));
          }
          data.add(row);

         //Calculo Número da Ordem de serviço

         String osn = rs.getString(1);
         int osns = Integer.parseInt(osn);
         int soma = 1;
         int oscal = osns+soma;
         String osv = Integer.toString(oscal);
         txtos.setText(osv);

            ResultSet rs1;
            rs1 = stat.executeQuery("select * From clientes order by nome");
            JComboBox txtcliente = new JComboBox();
            txtcliente.setEditable(true);
            txtcliente.setBounds(229, 49, 293, 23);
            txtcliente.addItem(" ");
            contentPane.add(txtcliente);
                     while (rs1.next()) {
            String name = rs1.getString("nome");

            txtcliente.addItem(name);

            //System.out.println(rs1.getString("nome"));
                     }
             //AutoCompletion.enable(txtcliente);







                     }


     rs.close();
     con.close();
 } catch (SQLException sqle) {
   JOptionPane.showMessageDialog(new JFrame(), sqle + "\n"+"Por favor contate o desenvolvedor ou o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

     sqle.printStackTrace();
 }




         catch (ClassNotFoundException cnfe) {
     JOptionPane.showMessageDialog(new JFrame(), cnfe + "\n"+"Por favor contate o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

     cnfe.printStackTrace();
 } }


     public void salvar() {
         try {
     Class.forName("org.sqlite.JDBC");
     Connection con = DriverManager.getConnection("jdbc:sqlite:C:\Users\Matheus\Documents\Java Apps\Tratermik\banco de dados\tratermik.db");
     Statement stat = con.createStatement();
     String os = txtos.getText().toString();
     txtcliente.setSelectedItem("Não funcional");
     String cliente = (String) txtcliente.getSelectedItem();
     String resp = txtresp.getText().toString();
     String amassado = (String) txtamassado.getSelectedItem();
     String trincado = (String) txttrincado.getSelectedItem();
     String peso = (String) txtpesodiv.getSelectedItem();
     String pesodiv = (String) txtqtdpesodiv.getText().toString();
     String outrasdiv =  txtoutrasdiv1.getText().toString();
     String dtreceb = ((JTextField) this.txtdtreceb.getDateEditor().getUiComponent()).getText();


     if (pesodiv.equals("")) {
         pesodiv = "N/A";
     }
     if (outrasdiv.equals("")) {
         outrasdiv = "N/A";
     }

     try {

     stat.executeQuery("INSERT INTO Tratermik (_id, cliente, Responsavel_Relatorio, Material_Trincado,Mateiral_Amassado,Quantidade_Divergente,Peso_Divergente,Motivo_Divergencia,data_inicio,data_fim,foto,peso,outros)"
            + "values ('"+os+"','"+cliente+"','"+resp+"','"+trincado+"','"+amassado+"','"+peso+"','"+pesodiv+"','"+outrasdiv+"',"
                    + "'"+dtreceb+"','a','a','a','a')");
     } catch(Exception e) { }





     con.close();
 } catch (SQLException sqle) {
   JOptionPane.showMessageDialog(new JFrame(), sqle + "\n"+"Por favor contate o desenvolvedor ou o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

     sqle.printStackTrace();
 }




         catch (ClassNotFoundException cnfe) {
     JOptionPane.showMessageDialog(new JFrame(), cnfe + "\n"+"Por favor contate o administrador do sistema.","Error",JOptionPane.ERROR_MESSAGE);

     cnfe.printStackTrace();
 } }
}
    
asked by anonymous 20.04.2016 / 03:27

1 answer

3
  

1st - Problem with JDateChoose component

In this snippet inside your constructor:

JDateChooser txtdtreceb = new JDateChooser();
txtdtreceb.setBounds(21, 377, 142, 20);
contentPane.add(txtdtreceb);

You are declaring a local variable of the same name as a variable declared at the start of your class ( JDateChooser txtdtreceb = new JDateChooser(); ). The JVM will always consider the local variable within that method (in its case, in the constructor), since there is no explicit reference to class property, through this .

Remove the line JDateChooser txtdtreceb = new JDateChooser(); to solve the problem.

  

2nd - Problem with the JComboBox component

The same problem as before, you are starting a JComboBox local name txttrincado within the constructor, in this line:

JComboBox txttrincado = new JComboBox();
txttrincado.setBounds(10, 163, 129, 25);
contentPane.add(txttrincado);

And you are doing the same for all other properties that you declared in the start class, there will probably be many other errors of that type.

Explanation of the problem

When you start a class declaring ownership, to refer to them in the methods of this class, it is recommended to use this , unless you are sure same name of any of the properties for other local scope variables.

The advantage of always referencing variables that are class properties with this is that it makes the identification of these easier because seeing this, we already know that the reference is to a property of that class. / p>

Just one example of the error you're making, just to be clearer:

class A {

    private String myScope = "property";

    //...
    public A() {
        String myScope = "local variable";

        System.out.println(this.myScope);
        System.out.println(myScope);
    }
}

Notice that I declared myScope as class property, but I ended up creating a local variable of the same name in the constructor. The console output will be:

  

property
  local variable

Another thing that is important to alert about is the name of the class. There is a default to be followed , where the first letter must be uppercase, followed by lowercase, and in case of names containing concatenated words, the beginning of the next word must start with capital letters too (eg, MyClass).

Take a look at your code, find local variables of the same name as the properties of the class, to prevent other elements from giving the same error.

    
20.04.2016 / 14:29