我想在每次点击面板时返回鼠标点击次数。我有一个BasePanel类,其中包含以下代码片段:
DELETE
FROM wp_postmeta
WHERE post_id IN (
SELECT ID
FROM wp_posts
WHERE post_type = 'attachment' AND post_parent IN (
SELECT post_id
FROM wp_postmeta
WHERE meta_value = 'mycbgenie'
)
)
在这里,我想返回count变量。我希望ButtonsPanel类能够访问BasePanel类中的getCount()方法。
BasePanel(){ //inside the BasePanel Class
addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(clicked == troop1){
count1--;
count = count1; //i want count to be accessible in another class
System.out.println("Troop1 count: "+count);
}else if(clicked == troop2){
count2--;
count = count2;
System.out.println("Troop2 count: "+count);
}
}
public int getCount(){ //how can this method be accessible in another class
return count;
}
});
}
但我认为,我在ButtonsPanel类中访问getCount()方法的方式是错误的。
答案 0 :(得分:1)
getCount()
是MouseAdapter
的匿名类实现方法。
如果您希望能够访问它,则必须将其从匿名状态中删除:
BasePanel(){
MouseAdapter mouseAdapter = new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(clicked == troop1){
count1--;
count = count1; //i want count to be accessible in another class
System.out.println("Troop1 count: "+count);
}else if(clicked == troop2){
count2--;
count = count2;
System.out.println("Troop2 count: "+count);
}
}
public int getCount(){
return count;
}
});
addMouseListener(mouseAdapater);
}
并为您的班级添加一个getter方法:
public MouseAdapter getMouseAdapater() {
return mouseAdapter;
}
然后您可以这样访问它:
ButtonsPanel(){ //inside the ButtonsPanel class
BasePanel pane = new BasePanel();
MouseAdapter adapater = pane.getMouseAdapater();
troop1 = new JButton(""+adapater.getCount());
troop2 = new JButton(""+adapater.getCount());
}