Problem getting Java JComboBox data

0

I am learning to use Java and I want to get the information of a JTextField and a JComboBox already generate them in the Jframe the problem is that I am trying to get its content through a method and it marks me the error

  

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;

public class pruebas extends JFrame {
    static String[] lista = { "RUTEO", "ESTATICO","BGP" };
    private JPanel contentPane;
    static String[][][] ValueTypes;
    static JComboBox combo_rutmen;
    static JTextField tf_REFERENCIA;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    pruebas frame = new pruebas();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

/**
 * Create the frame.
 */
public pruebas() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    ValueTypes = new String[3][50][4];

    JComboBox combo_rutmen = new JComboBox(lista);
    combo_rutmen.setBounds(128, 63, 78, 20);
    contentPane.add(combo_rutmen);

    JButton btnMerge = new JButton("Merge");
    btnMerge.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            combo();
        }
    });
    btnMerge.setBounds(190, 228, 89, 23);
    contentPane.add(btnMerge);

    JTextField tf_REFERENCIA = new JTextField();
    tf_REFERENCIA.setText("a32");
    tf_REFERENCIA.setBounds(128, 94, 86, 20);
    contentPane.add(tf_REFERENCIA);
    tf_REFERENCIA.setColumns(10);
}

static  void combo() {
    System.out.println("REFERENCIA " + tf_REFERENCIA.getText());
    System.out.println("Ruteo " + combo_rutmen.getSelectedItem().toString());
}
}

The error is generated when clicking on the Merge button

  

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException     at pruebas.combo (pruebas.java:67) at   $ 2.actionPerformed tests (tests.java:54) at   javax.swing.AbstractButton.fireActionPerformed (Unknown Source) at   javax.swing.AbstractButton $ Handler.actionPerformed (Unknown Source) at   javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source) at   javax.swing.DefaultButtonModel.setPressed (Unknown Source) at   javax.swing.plaf.basic.BasicButtonListener.mouseReleased (Unknown   Source) at java.awt.Component.processMouseEvent (Unknown Source) at   javax.swing.JComponent.processMouseEvent (Unknown Source) at   java.awt.Component.processEvent (Unknown Source) at   java.awt.Container.processEvent (Unknown Source) at   java.awt.Component.dispatchEventImpl (Unknown Source) at   java.awt.Container.dispatchEventImpl (Unknown Source) at   java.awt.Component.dispatchEvent (Unknown Source) at   java.awt.LightweightDispatcher.retargetMouseEvent (Unknown Source) at   java.awt.LightweightDispatcher.processMouseEvent (Unknown Source) at   java.awt.LightweightDispatcher.dispatchEvent (Unknown Source) at   java.awt.Container.dispatchEventImpl (Unknown Source) at   java.awt.Window.dispatchEventImpl (Unknown Source) at   java.awt.Component.dispatchEvent (Unknown Source) at   java.awt.EventQueue.dispatchEventImpl (Unknown Source) at   java.awt.EventQueue.access $ 500 (Unknown Source) at   java.awt.EventQueue $ 3.run (Unknown Source) at   java.awt.EventQueue $ 3.run (Unknown Source) at   java.security.AccessController.doPrivileged (Native Method) at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege (Unknown   Source) at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege (Unknown   Source) at java.awt.EventQueue $ 4.run (Unknown Source) at   java.awt.EventQueue $ 4.run (Unknown Source) at   java.security.AccessController.doPrivileged (Native Method) at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege (Unknown   Source) at java.awt.EventQueue.dispatchEvent (Unknown Source) at   java.awt.EventDispatchThread.pumpOneEventForFilters (Unknown Source)     at java.awt.EventDispatchThread.pumpEventsForFilter (Unknown Source)     at java.awt.EventDispatchThread.pumpEventsForHierarchy (Unknown   Source) at java.awt.EventDispatchThread.pumpEvents (Unknown Source)     at java.awt.EventDispatchThread.pumpEvents (Unknown Source) at   java.awt.EventDispatchThread.run (Unknown Source)

    
asked by Necros 23.07.2017 в 20:02
source

2 answers

0
public class pruebas extends JFrame {
    ...
    static JComboBox combo_rutmen;
    static JTextField tf_REFERENCIA;
    ...
    public pruebas() {
       JComboBox combo_rutmen = new JComboBox(lista);
       ...
       JTextField tf_REFERENCIA = new JTextField();
       ...
    }

    static  void combo() {
       System.out.println("REFERENCIA " + tf_REFERENCIA.getText());
       System.out.println("Ruteo " + combo_rutmen.getSelectedItem().toString());
    }

The problem is that what your code does is to define variables combo_rutmen and tf_REFERENCIA that are local to the method pruebas() and that hide the definition of the "global" variables. When you do the assignment, you do it to a variable that is not the one you have defined in the class, and that ceases to exist as soon as you exit the method.

That's why, when you execute combo() (which does use the "global" variables), you find that these have not been initialized and you have the NullPointerException .

Solution: assign to the variables, without declaring new ones.

 public pruebas() {
    ...
    combo_rutmen = new JComboBox(lista);

One way to make sure that you do not use local variables (for example, if you have become clueless and have called another local variable equal) is to indicate your scope each time you use them. In the case of static variables, the name of the class:

    pruebas.combo_rutmen = new JComboBox(lista);

; in the case of instance variables, this :

    this.combo_rutmen = new JComboBox(lista);

A couple of unrelated, but important notes:

  • Where it is not necessary, you must avoid methods and attributes static . Here there is no need to make the variables or combo are static . The static elements do not match well with object-oriented programming.

  • Check the Java naming documentation (class names start with uppercase, variables, and methods in camel_case ). Once used to read the code, and at the same time it is difficult and strange to read that the name of the class is pruebas and not Pruebas , for example.

answered by 23.07.2017 / 20:44
source
0

Thank you very much for the support, I was reviewing and as you say the variables were being hidden.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;

public class pruebas extends JFrame {
    static String[] lista = { "RUTEO", "ESTATICO","BGP" };
    private JPanel contentPane;
    static JComboBox combo_rutmen = new JComboBox(lista);
    static JTextField tf_REFERENCIA = new JTextField();
    private final JButton btnColoca = new JButton("COLOCA");
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    pruebas frame = new pruebas();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

/**
 * Create the frame.
 */
public pruebas() {


    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    combo_rutmen.setBounds(128, 63, 78, 20);
    contentPane.add(combo_rutmen);

    JButton btnMerge = new JButton("Merge");
    btnMerge.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            combo();
        }
    });
    btnMerge.setBounds(35, 120, 89, 23);
    contentPane.add(btnMerge);


    tf_REFERENCIA.setText("a32");
    tf_REFERENCIA.setBounds(128, 94, 86, 20);
    contentPane.add(tf_REFERENCIA);
    tf_REFERENCIA.setColumns(10);
    btnColoca.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            combo_rutmen.setSelectedIndex(1);
        }
    });
    btnColoca.setBounds(138, 120, 89, 23);

    contentPane.add(btnColoca);
}

static  void combo() {
    System.out.println("REFERENCIA " + pruebas.tf_REFERENCIA.getText());
    System.out.println("Ruteo " + pruebas.combo_rutmen.getSelectedItem().toString());
}
}

What I did was remove the definition of the object that was inside the test and put them on

public class tests extends JFrame {

Try as you recommended to remove the static attribute but I was still marking error eclipse I gave as help put it back so that it was fixed in this way I was finally able to read the content of the objects and thanks for the extra comments I will get to apply them as you tell me.

greetings

    
answered by 23.07.2017 в 23:26