Почему String не печатает на JLabel? (Java) - PullRequest
0 голосов
/ 09 апреля 2020

Я пытаюсь напечатать строку на JLabel, вывод должен выглядеть как на JLabel [[1,0,1] [0,1,1]]

Я пытался, но я не могу показаться чтобы заставить это работать .. Пожалуйста, посмотрите в конце кода, чтобы увидеть соответствующий код sr c.

Мой исходный код:

import java.util.*;
import javax.swing.*;
import javax.swing.JLabel;

public class ProjectFrame extends javax.swing.JFrame {

    /**
     * Creates new form ProjectFrame
     */
    public ProjectFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        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)
            .addGroup(layout.createSequentialGroup()
                .addGap(101, 101, 101)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(119, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(99, Short.MAX_VALUE))
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProjectFrame().setVisible(true);
            }
        });
        arrayGen();
    }

    public static void arrayGen() {

        int[][] ranArr = new int[2][3];


        for(int i = 0; i < 4; i++) {
            //Get random values b/w 0-2
            Random r = new Random();
            int posOne = r.nextInt(2);
            int posTwo = r.nextInt(3);


            while (ranArr[posOne][posTwo] == 1) {
                posOne = r.nextInt(2);
                posTwo = r.nextInt(3);
            }


            ranArr[posOne][posTwo] = 1;
        }


        for (int x = 0; x < 2; x++) {
            for (int j = 0; j < 3; j++) {
                //System.out.printf("%5d ", ranArr[x][j]);
            }
            //System.out.println();
        }

        String twoD = Arrays.deepToString(ranArr);
        int mid = twoD.length()/2;
        String firstHalf = twoD.substring(0,mid-1);
        String secondHalf = twoD.substring(mid);

        String firstSecond = firstHalf + secondHalf;

        JLabel jLabel1 = new JLabel();
        jLabel1.setText(firstHalf+"\n"+secondHalf);




    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

1 Ответ

0 голосов
/ 09 апреля 2020

Вы создали новую метку в arrayGen (), в этом проблема.

Я изменил код.

import java.util.*;
import javax.swing.*;
import javax.swing.JLabel;

public class ProjectFrame extends javax.swing.JFrame {

/**
 * Creates new form ProjectFrame
 */
public ProjectFrame() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();

    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)
        .addGroup(layout.createSequentialGroup()
            .addGap(101, 101, 101)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(119, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(76, 76, 76)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(99, Short.MAX_VALUE))
    );

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

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ProjectFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    ProjectFrame f = new ProjectFrame();
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            //new ProjectFrame().setVisible(true);
            f.setVisible(true);
        }
    });
    f.arrayGen();
}

public  void arrayGen() {

    int[][] ranArr = new int[2][3];


    for(int i = 0; i < 4; i++) {
        //Get random values b/w 0-2
        Random r = new Random();
        int posOne = r.nextInt(2);
        int posTwo = r.nextInt(3);


        while (ranArr[posOne][posTwo] == 1) {
            posOne = r.nextInt(2);
            posTwo = r.nextInt(3);
        }


        ranArr[posOne][posTwo] = 1;
    }


    for (int x = 0; x < 2; x++) {
        for (int j = 0; j < 3; j++) {
            //System.out.printf("%5d ", ranArr[x][j]);
        }
        //System.out.println();
    }

    String twoD = Arrays.deepToString(ranArr);
    int mid = twoD.length()/2;
    String firstHalf = twoD.substring(0,mid-1);
    String secondHalf = twoD.substring(mid);

    String firstSecond = firstHalf + secondHalf;

  //  JLabel jLabel1 = new JLabel();
    jLabel1.setText(firstHalf+"\n"+secondHalf);




}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
// End of variables declaration                   

}

...