从另一个类更改jLable-text

时间:2017-07-14 08:07:10

标签: java swing jlabel

我的问题:我无法从其他类改变jLabel的文本。在我的JFrame-Class中,它被称为" NewJFrame"我已经定义了一个名为" setLabelText()"的方法。其中jLable1的文本被更改。从main-Method调用此方法,但文本不会更改。怎么了?非常感谢你的帮助!

public class Main {

    static NewJFrame f = new NewJFrame();

    public static void main(String[] args) {

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

    }

}

这里是我的新JFrame类,里面有很多生成的东西。重要的是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                   
}

2 个答案:

答案 0 :(得分:0)

当你创建JFrame框架(来自netbeans)时,它已经有了它的主要功能。所以要么你必须创建JPanel并在具有main函数的类中手动初始化,要么你可以移动f.setText(“XYZ”);到NewJFrame()类。 这就像是:

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() {
                ***NewJFrame f=new NewJFrame();
f.setVisible(true);
f.setText("Your Text Goes Here");***
            }
        });
    }

答案 1 :(得分:0)

  

我需要从Main-class

调用setText()方法

f.main(null);的目的是什么?您尝试将文字设置为此行中的JFramef.setText("changedText");

作为解决方案,请将JLabel访问修饰符更改为public。默认情况下它是private,因此您无法在另一个类中更改它。

变化:

private javax.swing.JLabel jLabel1;

要:

public javax.swing.JLabel jLabel1;

在netbenas中,您无法默认编辑生成的代码。因此,要更改访问修饰符,右键单击设计窗口中的JLabel * ,然后转到自定义代码。在该窗口中,将访问权限更改为公开

enter image description here

现在,更改Main课程如下:

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
    }
}