为了澄清起见,我在 Netbeans 中使用 JFrame Form。
好吧,基本上我正在尝试使用构造函数更改公共(public)全局字符串(PictureName)的值,因为我正在尝试从另一个类获取另一个值,但是当我尝试在 JLabel 的代码中使用它时,它显示为空。这是代码
public class ShowPage extends javax.swing.JFrame {
public javax.swing.JLabel Picture;
public String PictureName;
public ShowPage() {
initComponents();
}
public ShowPage (String picName){
PictureName = picName;
}
private void initComponents() {
Picture = new javax.swing.JLabel();
getContentPane().add(Picture);
Picture.setBounds(20, 60, 300, 130);
Picture.setIcon(new javax.swing.ImageIcon(getClass().getResource("/MiniProject/imagesMain/"+PictureName)));
pack();
}
有什么想法为什么 PictureName 即使在构造函数中更改后仍然为空(是的,它已使用 SOP 检查)?
这是 PSVM 顺便说一句
public static void main(String args[]) {
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(ShowPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ShowPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ShowPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ShowPage.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 ShowPage().setVisible(true);
}
});
最佳答案
您正在调用无参构造函数,而不是使用图片名称作为参数的构造函数。在 main
中你应该调用:
public void run() {
new ShowPage(pictureName).setVisible(true);
}
其中pictureName
是存储图片文件名的变量。
构造函数还需要调用 initComponents()
就像无参构造函数一样:
public ShowPage (String picName) {
PictureName = picName;
initComponents();
}
关于java - JFrame:在构造函数中更改值后,字符串更改回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234144/