【发布时间】: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()”中的方法名称