如果我有按鈕單擊處理函數,我希望能夠通過使用以下參數識別哪個按鈕被其引用名稱(例如minimize_button或maximize_button)和NOT單擊:
如何通過聲明名稱引用局部變量
minimize_button.setName("minimize_button");
class Game extends JFrame
{
public Game()
{
JButton minimize_button = new JButton();
minimize_button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent mouse)
{
setWindowState(mouse);
}
});
JButton maximize_button = new JButton();
maximize_button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent mouse)
{
setWindowState(mouse);
}
});
}
private void setWindowState(MouseEvent mouse)
{
int window_state = Game.this.getExtendedState();
JButton button = (JButton)mouse.getComponent();
if (button == minimize_button)
{
if (window_state == JFrame.NORMAL || window_state == JFrame.MAXIMIZED_BOTH)
window_state = JFrame.ICONIFIED;
}
else if (button == maximize_button)
{
if (window_state == JFrame.NORMAL)
window_state = JFrame.MAXIMIZED_BOTH;
else if (window_state == JFrame.MAXIMIZED_BOTH)
window_state = JFrame.NORMAL;
}
Game.this.setExtendedState(window_state);
}
}
注:我不想聲明它作爲類變量
編輯:我需要在一個函數中處理按鈕點擊的原因是因爲我不想重複代碼(見下文)。我不想如下:
class Game extends JFrame
{
public Game()
{
JButton minimize_button = new JButton();
minimize_button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent mouse)
{
int window_state = Game.this.getExtendedState();
if (window_state == JFrame.NORMAL || window_state == JFrame.MAXIMIZED_BOTH)
Game.this.setExtendedState(JFrame.ICONIFIED);
}
});
JButton maximize_button = new JButton();
maximize_button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent mouse)
{
int window_state = Game.this.getExtendedState();
if (window_state == JFrame.NORMAL)
window_state = JFrame.MAXIMIZED_BOTH;
else if (window_state == JFrame.MAXIMIZED_BOTH)
window_state = JFrame.NORMAL;
Game.this.setExtendedState(window_state);
}
});
}
}
注:好心從評論:「哦,你應該這樣做這樣」不要。我想知道的是,我可以通過它的參考名稱引用一個變量。如果是這樣,怎麼樣?在上面的例子中反射將不起作用,正如我所說的,我不想將它們聲明爲類變量。
你看過https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html嗎? – randominstanceOfLivingThing
(1-)重複的代碼是什麼?我看到的唯一重複代碼是獲取/設置擴展狀態。沒有理由去做你正在做的事情。你真的使整個過程變得複雜。最小化和最大化偵聽器都包含不同的功能,不應該被組合成一個單一的偵聽器。你甚至不應該在JButton上使用MouseListener。你應該使用'ActionListener'。 – camickr
@camickr,你是正確的,只有一個設置被修改。然而,正如我已經指出的那樣,以上只是一個例子。每當窗口狀態發生變化時,都會進行一些更改。關於「您應該使用....」,請閱讀底部注意。 – johnny