[英]How do I make a JLabel that has an imageIcon that is available to all methods and classes?
我希望在JLabel中有一個ImageIcon,我將能夠從其他方法進行更新。 但我想不出一種方法來創建靜態JLabel(以便能夠從另一種方法訪問它),也無法將其安裝為包含imageIcon的Jlabel-除了JLabel標簽之外,還有其他方法嗎? = new JLabel(imgIcon)使用imageIcon創建標簽? 嘗試使用setIcon方法,而標簽沒有像上面那樣被固定,但是給出了空指針異常。 感謝您的協助。
不要將JLabel設為靜態-而是在其他方法之外但仍在您的類中定義它。
public class Test {
private JLabel label = new JLabel(new ImageIcon(/*your icon*/));
}
如果需要從另一個類訪問它,請創建一個訪問器方法:
public JLabel getLabel() {
return label;
}
如果要在不創建對象的情況下訪問它們,則僅在任何類(例如Clazz
)中使用靜態方法或對象(例如Clazz c = new Clazz();
)。 例如,如果我使一個靜態方法public static void staticMethod() {}
和一個常規方法public void regularMethod() {}
,這就是我訪問它們的方式:
public class Clazz //A class with methods
{
public void regularMethod()
{
//Do something local
}
public static void staticMethod()
{
//Do something static
}
}
public class Main //The main class with the main method.
{
public static void main(String[] args)
{
Clazz.staticMethod();
Clazz c = new Clazz();
c.regularMethod();
}
}
注意,我沒有調用Clazz.regularMethod();
,因為這是不可能的。 我沒有打電話給c.staticMethod();
因為那是不好的形式,即使有可能。
總之,除非絕對必要(A),或者必須隨時從任何上下文訪問(B),否則請盡量不要使用靜態對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.