簡體   English   中英

如何從其他方法訪問JLabel?

[英]How to access a JLabel from another method?

我正在開發一個GUI應用程序,我想讓我的代碼執行的操作是,單擊您可以在基於swing的GUI中看到的唯一按鈕后,其中包含的2個jLabel使用戶可以感知字符串“工作” 。 這是我的代碼:

public class DiligentGUI extends javax.swing.JFrame {

public DiligentGUI() {
    initComponents();
}
void a()
{
  fahrenheitLabel.setText("Working");  
}

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

    tempTextField = new javax.swing.JTextField();
    celsiusLabel = new javax.swing.JLabel();
    convertButton = new javax.swing.JButton();
    fahrenheitLabel = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Celsius Converter");

    tempTextField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tempTextFieldActionPerformed(evt);
        }
    });

    celsiusLabel.setText("Celsius");

    convertButton.setText("Convert");
    convertButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            convertButtonActionPerformed(evt);
        }
    });

    fahrenheitLabel.setText("Fahrenheit");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(tempTextField,  
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,  
javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(12, 12, 12)
                    .addComponent(celsiusLabel))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(convertButton)


.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(fahrenheitLabel)))
            .addContainerGap(59, Short.MAX_VALUE))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {convertButton, tempTextField});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(tempTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(celsiusLabel))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(convertButton)
                .addComponent(fahrenheitLabel))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

private void tempTextFieldActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
}                                             

private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              

DiligentGUI b = new DiligentGUI();
b.a();
celsiusLabel.setText("Working");
}                                             

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

// Variables declaration - do not modify                     
private javax.swing.JLabel celsiusLabel;
private javax.swing.JButton convertButton;
private javax.swing.JLabel fahrenheitLabel;
private javax.swing.JTextField tempTextField;
// End of variables declaration                   

}

如您所見,其中有2個jLabel:fahrenheitLabel和celsiusLabel。 我創建了一個稱為“ a”的輔助方法,該方法應將fahrenheitLabel的狀態更改為“正在工作”。 我無法實現所需的輸出。 有什么建議么?

不會發生這種情況是因為您在convertButtonActionPerformed方法中創建了DiligentGUI類的另一個對象。 這將創建另一個JFrame 您看不到它,因為您沒有通過d.setVisible(true)將其設置為可見。

在您的位置進行更改

private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              

    a();  // This will call the a() method in the current running instance. 
    celsiusLabel.setText("Working");
}                                             

暫無
暫無

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

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