簡體   English   中英

如何使用 JLabels 在 JFrame 中顯示矩陣

[英]How to show matrix in a JFrame with JLabels

我想在JFrame Java 顯示一個矩陣,我知道怎么做,但我現在有這個問題,我不知道如何解決。 我嘗試了很多東西,但沒有任何效果。

在此處輸入圖片說明

問題是圖片中標記的這些空位。

代碼:

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]);
        }

    }

}

您的圖像顯示,當您將容器的布局設置為 4x4 網格時,您向該容器添加了 16 個以上的項目,這可能是由於您設置了錯誤的容器布局。 您可能正在設置主 JFrame 的 contentPane 的布局,向其中添加 JLabels,並向其中添加其他內容,從而弄亂了網格的大小。

我建議你創建一個新的 JPanel,一個用來保存你的 JLabel 網格,給它一個 4x4 的網格布局,添加 JLabels,然后將此 JPanel 添加到主 GUI(JFrame),或添加到顯示在框架。

是的,您使用的 arreglo 數組索引是錯誤的,因為您試圖將整行添加到單個數組項中。 例如:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM