這一切都取決於你將如何使用標誌變量,在你的代碼示例中,我沒有看到標誌的使用,我不明白爲什麼你寧願避免在你的情況下使用靜態變量,但如果這東西關鍵,解決方案之一是使用該標誌變量作爲MyFrame類的公共變量(無靜態變量),然後從你的main函數訪問到它:
public class MyFrame extends JFrame
{
private Panel1 ;
private Panel2 ;
public boolean flag;
public MyFrame()
{
super("MyFrame");
this.flag = true;
P1 = new Panel1();
P2 = new Panel2();
setLayout(new BorderLayout());
add(P1,BorderLayout.CENTER);
add(P2,BorderLayout.EAST);
setSize(500,400);
setVisible(true);
}
public static void main(String[] args) {
MyFrame mF=new MyFrame();
// you can access your flag this way
mF.flag = false; // or use it the way you want !
mF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
但如果你想在Panel2類中使用該標誌,那麼你可能需要添加一個新的構造函數到你的Panel2類,它接受JFrame類型作爲參數,你將作爲實例傳遞給它...
public class MyFrame extends JFrame
{
private Panel1 ;
private Panel2 ;
public boolean flag;
public MyFrame()
{
super("MyFrame");
P1 = new Panel1();
this.flag = true;
P2 = new Panel2(this); /* then you will be able to have a visibility
on the flag variable of your MyFrame instance.*/
setLayout(new BorderLayout());
add(P1,BorderLayout.CENTER);
add(P2,BorderLayout.EAST);
setSize(500,400);
setVisible(true);
}
public static void main(String[] args) {
MyFrame mF=new MyFrame();
// you can access your flag this way
mF.flag = false; // or use it the way you want !
mF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
您還可以添加功能,是Panel2接受boolean變量中,當你在你的主要功能,您可以通過標記變量
是的,你可以。只需在'main'方法內創建'MyFrame'的實例並從那裏繼續。 –
他不是已經這樣做了嗎? – raam86
這個問題還不清楚。 – raam86