Search code examples
javaswingjlabel

Change jLable-text from another class


My problem: I can't change the text of a jLabel from an other class. In my JFrame-Class, which is called "NewJFrame" I have defined a method called "setLabelText()" in which the text of jLable1 is changed. This method is called from the main-Method, but the text doesn't change. What's wrong? would be very grateful for help!

public class Main {

    static NewJFrame f = new NewJFrame();

    public static void main(String[] args) {

        f.main(null);
        f.setLabelText("changedText");

    }

}

and here my new JFrame class with a lot of generated stuff in there. The important thing is the setText()-Method.

 public class NewJFrame extends javax.swing.JFrame {


    public NewJFrame() {
        initComponents();
    }


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

        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        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(156, 156, 156)
                .addComponent(jLabel1)
                .addContainerGap(203, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(152, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(132, 132, 132))
        );

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



    public static void main(String args[]) {

        //<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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }



        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }


    public void setLabelText (String text){
        jLabel1.setText(text);

    }



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

Solution

  • I need to call the setText()-method from Main-class

    What is the purpose of f.main(null); and you are trying to set text to the JFrame in this line: f.setText("changedText");

    As a solution, change your JLabel access modifier to public. By default it is private, because of that you cannot change it in another class.

    Change:

    private javax.swing.JLabel jLabel1;
    

    To:

    public javax.swing.JLabel jLabel1;
    

    In netbenas you cannot edit generated codes by default. So to change access modifier, right click on the JLabel in design window* and go to the customize code. In that window change the Access: to public.

    enter image description here

    Now, change the Main class as below:

    public class Main {
        static NewJFrame f = new NewJFrame();
    
        public static void main(String[] args) {
            f.jLabel1.setText("changedText");//this line will get the label in NewJFrame and set the text
            //f.setVisible(true);//this is added to open the frame. May be you dont want this line
        }
    }