[英]Why is my constructor called twice
我正在創建一個多線程客戶端服務器程序。
有一個客戶端登錄JPanel,它通過將用戶名和密碼發送到服務器進行檢查來對用戶進行身份驗證,如果正確,服務器將發回客戶端:“是”
if (UsernameandPasswordMatch.equals("Yes"))
{
String numofplayers = Utility.ReadFromServer();
int numofplayer_int = Integer.parseInt(numofplayers);
new GameTablePanel(numofplayer_int).start(numofplayer_int);
//change to game table panel
}
這是GameTablePanel類的啟動方法
void start(int numofplayer_int)
{
JLayeredPane lpane = new JLayeredPane();
lpane.setBounds(0, 0, 1200, 750);
JPanel background = new WallPaper();
//background.setBounds(0, 0, 1200, 750);
background.setOpaque(true);
GameTablePanel panel = new GameTablePanel(numofplayer_int); //called 2nd time
//panel.setBounds(100, 100, 400, 400);
panel.setBounds(0,0,1200,750);
panel.setOpaque(false);
lpane.add(background, new Integer(0), 0);
lpane.add(panel, new Integer(1), 0);
Utility.ChangeJLPanel(lpane);
}
使用調試器,我意識到,一旦我進入start方法,構造函數便會立即被調用,而當到達
GameTablePanel面板=新的GameTablePanel(numofplayer_int)
僅供參考:每當客戶端連接到服務器時,我都會在服務器端創建一個新線程
我怎么只一次調用我的構造函數而不是兩次
似乎您是兩次明確地調用它,一次是從這里
new GameTablePanel(numofplayer_int).start(numofplayer_int);
再從GametablePanel
的start方法GametablePanel
。 那是你要的嗎? 我不熟悉您要嘗試執行的操作,但是由於您的啟動方法已經屬於該面板,因此您也可以這樣做:
void start(int numofplayer_int) {
JLayeredPane lpane = new JLayeredPane();
lpane.setBounds(0, 0, 1200, 750);
JPanel background = new WallPaper();
//background.setBounds(0, 0, 1200, 750);
background.setOpaque(true);
//this.setBounds(100, 100, 400, 400);
this.setBounds(0,0,1200,750);
this.setOpaque(false);
lpane.add(background, new Integer(0), 0);
lpane.add(this, new Integer(1), 0);
Utility.ChangeJLPanel(lpane);
}
我不確定您期望什么,但是您正在實例化兩個GameTablePanel
。 每次在其前面使用new
,都會調用其構造函數。 每次您這樣做時,結果將對類的實例有不同的引用(但您是第一次扔掉一個)。 在您的代碼中,當密碼匹配時,您將首次實例化GameTablePanel
:
new GameTablePanel(numofplayer_int).start(numofplayer_int);
^
然后再次在start()
:
GameTablePanel panel = new GameTablePanel(numofplayer_int);
^
似乎您正在尋找一種從start()
內引用第一次創建的類的實例的方法。 您可以簡單地使用this
關鍵字來做到這一點:
void start() // don't need the parameter anymore
{
JLayeredPane lpane = new JLayeredPane();
lpane.setBounds(0, 0, 1200, 750);
JPanel background = new WallPaper();
//background.setBounds(0, 0, 1200, 750);
background.setOpaque(true);
// Update self
//this.setBounds(100, 100, 400, 400);
this.setBounds(0,0,1200,750);
this.setOpaque(false);
lpane.add(background, new Integer(0), 0);
lpane.add(this, new Integer(1), 0);
Utility.ChangeJLPanel(lpane);
}
更改行:
new GameTablePanel(numofplayer_int).start(numofplayer_int);
至
new GameTablePanel(numofplayer_int).start();
由於您已使用構造函數中的參數對其進行了初始化,因此不需要它。
在開始之內,您已經有了GameTablePanel的實例,因此無需使用“ this”來創建新實例:
//panel.setBounds(100, 100, 400, 400);
this.setBounds(0,0,1200,750);
this.setOpaque(false);
lpane.add(background, new Integer(0), 0);
lpane.add(this, new Integer(1), 0);
Utility.ChangeJLPanel(lpane);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.