Search code examples
javaclassjformattedtextfield

Generate JFormattedTextField with a class


i'm in trouble here, i'm trying to create a class that create JFormattedTextFields, and it works, but i need to get it's value, that's when i got NullPointerExeption, theres is my code:

JDialog:

package br.edu.faculdadedosguararapes;

import java.awt.EventQueue;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;

import java.awt.Dialog.ModalityType;
import java.awt.FlowLayout;
import java.awt.Color;

import javax.swing.JTextField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Det4x4 extends JDialog {

    private JFormattedTextField aL1C1;
    private JFormattedTextField aL1C2;
    private JFormattedTextField aL1C3;
    private JFormattedTextField aL1C4;
    private JFormattedTextField aL2C1;
    private JFormattedTextField aL2C2;
    private JFormattedTextField aL2C3;
    private JFormattedTextField aL2C4;
    private JFormattedTextField aL3C1;
    private JFormattedTextField aL3C2;
    private JFormattedTextField aL3C3;
    private JFormattedTextField aL3C4;
    private JFormattedTextField aL4C1;
    private JFormattedTextField aL4C2;
    private JFormattedTextField aL4C3;
    private JFormattedTextField aL4C4;
    private JTextField tfDeterminante;
    private GeraObjeto textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Det4x4 dialog = new Det4x4();
                    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    dialog.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Det4x4() {
        setTitle("Matriz 4x4");
        setModalityType(ModalityType.APPLICATION_MODAL);
        setResizable(false);
        setBounds(100, 100, 487, 362);
        getContentPane().setLayout(null);

        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz", TitledBorder.CENTER, TitledBorder.TOP, null, null));
        panel.setBounds(12, 12, 143, 130);
        getContentPane().add(panel);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        textField = new GeraObjeto();

        textField.novoFtf(aL1C1, panel);
        textField.novoFtf(aL1C2, panel);
        textField.novoFtf(aL1C3, panel);
        textField.novoFtf(aL1C4, panel);

        textField.novoFtf(aL2C1, panel);
        textField.novoFtf(aL2C2, panel);
        textField.novoFtf(aL2C3, panel);
        textField.novoFtf(aL2C4, panel);

        textField.novoFtf(aL3C1, panel);
        textField.novoFtf(aL3C2, panel);
        textField.novoFtf(aL3C3, panel);
        textField.novoFtf(aL3C4, panel);

        textField.novoFtf(aL4C1, panel);
        textField.novoFtf(aL4C2, panel);
        textField.novoFtf(aL4C3, panel);
        textField.novoFtf(aL4C4, panel);

        JPanel panelDet = new JPanel();
        panelDet.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Determinante", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
        panelDet.setBounds(12, 169, 125, 52);
        getContentPane().add(panelDet);

        tfDeterminante = new JTextField();
        tfDeterminante.setHorizontalAlignment(SwingConstants.CENTER);
        tfDeterminante.setEditable(false);
        tfDeterminante.setColumns(5);
        panelDet.add(tfDeterminante);

        JButton btnCalcular = new JButton("Calcular");
        btnCalcular.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                int a[][] = new int[4][4];  
                //CalculaDet determinante = new CalculaDet();

                a[0][0] = Integer.parseInt(textField.getFtfContent(aL1C1));
                /*a[0][1] = Integer.parseInt(textField.getFtfContent(aL1C2));
                a[0][2] = Integer.parseInt(textField.getFtfContent(aL1C3));
                a[0][3] = Integer.parseInt(textField.getFtfContent(aL1C4));
                a[1][0] = Integer.parseInt(textField.getFtfContent(aL2C1));
                a[1][1] = Integer.parseInt(textField.getFtfContent(aL2C2));
                a[1][2] = Integer.parseInt(textField.getFtfContent(aL2C3));
                a[1][3] = Integer.parseInt(textField.getFtfContent(aL2C4));             
                a[2][0] = Integer.parseInt(textField.getFtfContent(aL3C1));
                a[2][1] = Integer.parseInt(textField.getFtfContent(aL3C2));
                a[2][2] = Integer.parseInt(textField.getFtfContent(aL3C3));
                a[2][3] = Integer.parseInt(textField.getFtfContent(aL3C4));
                a[3][0] = Integer.parseInt(textField.getFtfContent(aL4C1));
                a[3][1] = Integer.parseInt(textField.getFtfContent(aL4C2));
                a[3][2] = Integer.parseInt(textField.getFtfContent(aL4C3));
                a[3][3] = Integer.parseInt(textField.getFtfContent(aL4C4));*/

                tfDeterminante.setText(String.valueOf(a[0][0]));

                //determinante.Determinante(a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2],
                    //  tfDiagonalPrincipal, tfDiagonalSecundaria, tfDeterminante);
            }
        });

        btnCalcular.setBounds(187, 154, 99, 23);
        getContentPane().add(btnCalcular);

        JButton btnLimpar = new JButton("Limpar");
        btnLimpar.setBounds(187, 189, 99, 23);
        getContentPane().add(btnLimpar);


    }
}

Class:

package br.edu.faculdadedosguararapes;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class GeraObjeto {

        public JFormattedTextField novoFtf(JFormattedTextField nome, JPanel panel, int bound1, int bound2){
            nome = new JFormattedTextField();
            nome.setBounds(bound1, bound2, 22, 20);
            nome.setHorizontalAlignment(SwingConstants.CENTER);
            nome.setColumns(2);
            nome.addKeyListener(new KeyAdapter() {
                @Override
                public void keyTyped(KeyEvent arg0) {
                    char c = arg0.getKeyChar();
                    if (!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE) || c==KeyEvent.VK_DELETE || Character.toString(c).equals("-"))){
                        arg0.consume();
                    }
                }
            });

            panel.add(nome);
            return nome;
        }

        public JFormattedTextField novoFtf(JFormattedTextField nome, JPanel panel){
            nome = new JFormattedTextField();
            nome.setHorizontalAlignment(SwingConstants.CENTER);
            nome.setColumns(2);
            nome.addKeyListener(new KeyAdapter() {
                @Override
                public void keyTyped(KeyEvent arg0) {
                    char c = arg0.getKeyChar();
                    if (!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE) || c==KeyEvent.VK_DELETE || Character.toString(c).equals("-"))){
                        arg0.consume();
                    }
                }
            });

            panel.add(nome);
            return nome;
        }

        public String getFtfContent(JFormattedTextField nome){
            return nome.getText();
        }

}

Just for test, i've commented some lines, and tried to get the value of one of the textfields, but i got:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at br.edu.faculdadedosguararapes.GeraObjeto.getFtfContent(GeraObjeto.java:50)
    at br.edu.faculdadedosguararapes.Det4x4$2.actionPerformed(Det4x4.java:110)

I'm sure that what i need is to create a method to set the value of the JFT, but i don't now how.


Solution

  • You're creating a new JFormattedTextField but you're not assigning the new objects to the variables held by your class, and so all variables are null. You are in fact assigning the object to the parameter of your novoFtf method, which does not automatically assign it to the JFormattedTextField variable held by the class. I suppose you could do:

    aL1C1 = textField.novoFtf(aL1C1, panel);
    

    Other problems:

    • Your code seems to be unnecessarily complex making debugging hard. I'd refactor and simplify.
    • If you need a grid of fields, use an array or ArrayList which will help with my suggestion above, with simplification.
    • You're using setBounds and null layout. I'm going suggest that you not do this as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
    • For example, your matrix fields should be held by a JPanel that uses a 4 by 4 GridLayout, and this JPanel could be put in a main JPanel that uses GridBagLayout.
    • Avoid using a KeyListener with a JTextComponent such as a JTextField or a JFormattedTextField as this can cause significant and hard to debug problems. Also there are better ways of doing this sort of thing including use of DocumentListener, DocumentFilter, InputVerifier...