简体   繁体   中英

How to show matrix in a JFrame with JLabels

I want to show a matrix in Java in a JFrame , I know how to do it, but I have this problem now, and I don´t know how to solve it. I've tried a lot of things, but nothing has worked.

在此处输入图片说明

The problem are these empty places marked in the picture.

code:

public class VentanaConsulta extends javax.swing.JFrame {

JLabel[] arreglo = new JLabel[16];

public VentanaConsulta(Sistema sistema, VentanaInicial ventanaInicial) {
    this.modelo = sistema;
    this.ventanaInicial = ventanaInicial;
    initComponents();
    IniciarComponentes();

}

private void IniciarComponentes() {

    int[][] campo = {{1,2,3,4}, {0,0,0,0} , {0,0,0,0}, {0,0,0,0}};

    setLayout(new GridLayout(4, 4));
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {

            arreglo[i] = new JLabel(Integer.toString(campo[i][j]));
            arreglo[i].setHorizontalAlignment(SwingConstants.CENTER);
            add(arreglo[i]);
        }

    }

}

Your image shows that while you're setting the layout of your container to a 4x4 grid, you are adding more than 16 items to this container, and this is likely due to your setting the layout of the wrong container. You are probably setting the layout of the main JFrame's contentPane, adding your JLabels to it, and adding other things to it as well, messing up the size of the grid.

I suggest that you create a new JPanel, one to hold your JLabel grid, give it a 4x4 grid layout, add the JLabels, and then add this JPanel to the main GUI (the JFrame), or to a container that is displayed within the JFrame.

And yes, your arreglo array indices use is wrong, since you are trying to add a whole row to a single array item. eg something like:

private void IniciarComponentes() {
    int[][] campo = {{1,2,3,4}, {0,0,0,0} , {0,0,0,0}, {0,0,0,0}};
    JPanel gridPanel = new JPanel(new GridLayout(4, 4));
    // setLayout(new GridLayout(4, 4));
    for (int i = 0; i < campo.length; i++) {  // avoid using "magic" numbers
        for (int j = 0; j < campo[i].length; j++) {
            JLabel label new JLabel(Integer.toString(campo[i][j]));
            label.setHorizontalAlignment(SwingConstants.CENTER);
            arreglo[4 * i + j] = label
            gridPanel.add(label);
        }
    }
    
    // here add gridPanel to the main GUI
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM