从文本字段矩阵中

时间:2018-05-15 20:08:03

标签: java swing matrix textfield

我创建了一个文本字段矩阵,但我无法获取正在键入这些文本字段的文本。我只能访问矩阵中的文本字段对象本身,而不能访问这些文本字段中的实际文本。

这是整个代码。我的主要语言是西班牙语,所以一些语言是西班牙语和一些短语。根据代码,我将写下我的主要问题:

import java.awt.Color;
import java.awt.Cursor;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.scene.layout.Border;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.util.Arrays;

public class FrmArregloControles extends javax.swing.JFrame implements ActionListener{
    public FrmArregloControles() {
        initComponents();
        iniciarComponentes();
    }    
    private void iniciarComponentes() {
        byte numRen = Byte.parseByte(JOptionPane.showInputDialog(null, "¿Número de Renglones?")),
             numCol = Byte.parseByte(JOptionPane.showInputDialog(null, "¿Número de Columnas?"));
        int [][] intMatriz = new int[numRen][numCol];
        txtMatriz = new JTextField[numRen][numCol];
        String txt = JOptionPane.showInputDialog(this,"¿Qué ponemos?");

        if (numRen >= 1 && numCol >= 1) {
            lblRen = new JLabel[numRen];
            lblCol = new JLabel[numCol];

            for (byte r = 0; r < txtMatriz.length; r++) {//for controla los renglones (r)
                // creacion del vector de etiquetas lblRen
                lblRen[r] = new JLabel();
                // CONFIURACION DE PROPIEDADES PARA EL VECTOR PARA ETIQUTAS DE RENGLONES
                lblRen[r].setBounds(new Rectangle(15, 
                                                  15 + (25 + 10) * (r + 1), 
                                                  40, 25));

                lblRen[r].setText("[" + (r+1) + "]");
                lblRen[r].setBorder(border);
                lblRen[r].setHorizontalAlignment(SwingConstants.CENTER);
              //Adición de la etiqueta a la forma
                this.add(lblRen[r]);
                for (byte c = 0; c < txtMatriz[r].length; c++){
                  // creacion del vector de etiquetas lblRen
                lblCol[c] = new JLabel();
                // CONFIURACION DE PROPIEDADES PARA EL VECTOR PARA ETIQUTAS DE COLUMNAS
                lblCol[c].setBounds(new Rectangle(15 + (lblRen[0].getWidth() + 10) * (c + 1), 
                                                  15, 
                                                  40, 25));

                lblCol[c].setText("[" + (c+1) + "]");
                lblCol[c].setBorder(border);
                lblCol[c].setVerticalAlignment(SwingConstants.CENTER);
                lblCol[c].setHorizontalAlignment(SwingConstants.CENTER);
              //Adición de la etiqueta a la forma
                this.add(lblCol[c]);

              //Creación de matriz de campos de texto
                txtMatriz[r][c] = new JTextField();
              //Configuración de propiedades de campos de texto
                txtMatriz[r][c].setBounds(new Rectangle(15 + (lblRen[0].getWidth() + 10) * (c+1), 
                                                        15 + (lblRen[0].getHeight() + 10) * (r + 1), 
                                                        40, 25));

                txtMatriz[r][c].setToolTipText("Campo " + (r + 1) + ", " + (c + 1));
                txtMatriz[r][c].setCursor(new Cursor(Cursor.TEXT_CURSOR));
                this.add(txtMatriz[r][c]);
                txtMatriz[r][c].setText(txt);
                txtMatriz[r][c].getText();
                }
            }
        }
        else {
            JOptionPane.showMessageDialog(null, "Tamaño Invalido");
        }

        btnCapturar.setBounds (new Rectangle(((((40 + (numRen * 20))- 30) + (numRen * 10)/2)), 
                                                ((numCol*35) + 50 ), 
                                                 100, 25));

        this.add(btnCapturar);
        btnCapturar.addActionListener(this);
    }


            //Button's function
        public void actionPerformed(ActionEvent e){
            System.out.println(Arrays.deepToString(txtMatriz));
        }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

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

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmArregloControles().setVisible(true);
            }
        });
    }
//DECLARACIÓN DE CONTROLES
    JLabel lblRen[], lblCol[];
    JTextField txtMatriz[][];
    JButton btnCapturar = new JButton("Capturar");
    javax.swing.border.Border border = BorderFactory.createLineBorder(Color.black, 1);

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

我想要的是从其中的每个文本字段中获取 txtMatriz 的文本,并将它们分配到不同的矩阵,但是是int类型矩阵。我已经尝试了一些方法,但是我越接近,就是当我注意到JTextField无法转换为int时。所以说这个,我假设我无法通过使用Integer.parseInt方法获取这些文本字段的文本。总而言之,我需要帮助将txtMatriz转换为intMatriz

2 个答案:

答案 0 :(得分:1)

[注意,我已经改变了原来的答案,因为问题已经大大扩展,包括完整的源代码,允许我直接解决问题)

确定。这是相当奇怪的,因为你原来的代码示例虽然不再存在,但却是正确的,所以我不太明白为什么它不起作用。无论如何,这是你需要做的:

  1. 将int [] [] intMatrix声明移动为实例变量,就像txtMatriz一样。我更喜欢将它们放在构造函数之上:

    int [][] intMatriz;

  2. 同样,一旦您知道矩阵维度,请初始化:

    intMatriz = new int[numRen][numCol];

  3. 最后,更新actionPerformed,如下所示:

    public void actionPerformed(ActionEvent e){
        for (byte r = 0; r < txtMatriz.length; r++) {
            for (byte c = 0; c < txtMatriz[r].length; c++) {
                intMatriz[r][c] = Integer.parseInt(txtMatriz[r][c].getText());
            }
        }
        System.out.println(Arrays.deepToString(intMatriz));
    }
    
  4. 当我进行这些更改时,我会看到如下输出:

    [[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [6, 6, 5, 6, 6]]
    

答案 1 :(得分:0)

为什么不尝试使用for循环遍历每个数组?

public class ColorBoxes {
  private int grid = 12;
  private int pause = 50;

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            ColorBoxes applet = new ColorBoxes();
            if (args.length > 0) {
              grid = Integer.parseInt(args[0]);
            }
            if (args.length > 1) {
              pause = Integer.parseInt(args[1]);
            }
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new GridLayout(grid, grid));
            for (int i = 0; i < grid * grid; i++){
                frame.add(new CBox(pause));
            }
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
  }

}