【问题标题】:Change jLable-text from another class从另一个类更改 jLabel-text
【发布时间】:2017-07-14 08:07:10
【问题描述】:

我的问题:我无法从其他类更改 jLabel 的文本。在我的名为“NewJFrame”的 JFrame-Class 中,我定义了一个名为“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() 方法。

 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                   
}

【问题讨论】:

  • 是否需要给标签设置文本?如果是标签这是什么:static NewJFrame f = new NewJFrame(); f.setText("changedText");?
  • 你说得对,但不清楚。我已经编辑了我的问题并更改了“setLabeltext()”中的方法名称

标签: java swing jlabel


【解决方案1】:

我需要从 Main-class 调用 setText() 方法

f.main(null); 的用途是什么,您正在尝试将文本设置为此行中的 JFramef.setText("changedText");

作为一种解决方案,将您的 JLabel 访问修饰符更改为 public。默认为private,因此您无法在其他类中更改它。

变化:

private javax.swing.JLabel jLabel1;

收件人:

public javax.swing.JLabel jLabel1;

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

现在,将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
    }
}

【讨论】:

  • 非常感谢!你让我意识到了一个更普遍的错误:甚至没有必要将 jLable1 公开,但只需忽略 f.main(null) 就足够了。显然,当首先执行 f.main 时,无法再对 jLable 进行任何更改,我不太明白。
  • @taxus1 很好。如果您不想更改访问修饰符,您可以实现一个方法并传递值。你的程序现在运行了吗?
  • 我现在终于发现了我的错误:在主类中,我使用了f.main()以使框架可见并对其进行初始化等等。但仔细观察,方法 main() 包含public void run() { new NewJFrame().setVisible(true); },所以每次我调用它时,它都会创建一个 NewJFrame 的新实例,该实例设置为可见,而不是我的框架“f”,其文本已更改。
【解决方案2】:

当您创建 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");***
            }
        });
    }

【讨论】:

  • 感谢您的回答!但我需要从 Main-class 调用 setText() 方法,因为在那里会生成 setText-String。还是没搞明白为什么文字没有变:是不是都一样,是在类里面应用setText()还是从另一个类调用public setText()-method?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
相关资源
最近更新 更多