下面是创建我的ImageIcon和JLabel的代码片段:
ImageIcon armorShopIcon = new ImageIcon("/images/armorshop.png", "Armor Shop");
JLabel armorShopLabel = new JLabel("Armor Shop", armorShopIcon, JLabel.CENTER);
object.setArmorImage(armorShopLabel);
然后在我的对象类中,有一个setter:
public void setArmorImage(JLabel label) {
this.jLabel1 = label;
}
当我测试我的应用程序时,这没有显示图像,我想知道是否有人可以指出我的错误
编辑
大多数源代码:
主要:
public class Main extends javax.swing.JFrame {
public Main() {
initComponents();
ImageIcon armorIcon = new ImageIcon("/images/armorshop.png", "Armor Shop");
JLabel armorShopLabel = new JLabel("Armor Shop", armorShopIcon, JLabel.CENTER);
ShopDisplay armorShop = new ShopDisplay();
armorShop.setArmorImage(armorShopLabel);
public initComponents() { /*more generated code here*/ }
}
}
显示:
public class ShopDisplay extends javax.swing.JPanel {
/** Creates new form ShopDisplay */
public ShopDisplay() {
initComponents();
}
//generated by the gui builder
//initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("Shop Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jLabel1, gridBagConstraints);
}
//Variable declarationg
private javax.swing.JLabel jLabel1;
//Setter for Shop Name
public void setArmorImage(JLabel shopLabel) {
this.jLabel1 = shopLabel;
}
//other setters for
//multiple jLabels
}
最佳答案
您传递的标签未添加到GUI,以下方法可能会帮助您-
添加另一个JPanel作为jLabel1
的容器,仅替换其内容:
即:
private javax.swing.JPanel containerPanel;
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("Shop Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
containerPanel = new javax.swing.JPanel();
containerPanel.add(jLabel1);
add(containerPanel, gridBagConstraints);
}
//Variable declarationg
private javax.swing.JLabel jLabel1;
//Setter for Shop Name
public void setArmorImage(JLabel shopLabel) {
containerPanel.remove(jLabel1);
containerPanel.add(shopLabel);
jLabel1 = shopLabel;
revalidate();
}
,如果要将其添加到gui中,可以执行以下操作之一:
将
jLabel1
的属性设置为shopLabel
的属性,例如this.jLabel1.setText(shopLabel.getText());
或-删除
jLabel1
,添加shopLabel
并将this.jLabel1
设置为shopLabel
:例如:
public void setArmorImage(JLabel shopLabel) {
remove(jLabel1);
add(shopLabel);
jLabel1 = shopLabel;
revalidate();
}